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
import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() __a = [ 'word_embeddings_layernorm.weight', 'word_embeddings_layernorm.bias', 'input_layernorm.weight', 'input_layernorm.bias', 'post_attention_layernorm.weight', 'post_attention_layernorm.bias', 'self_attention.dense.bias', 'mlp.dense_4h_to_h.bias', 'ln_f.weight', 'ln_f.bias', ] __a = [ 'mlp.dense_4h_to_h.weight', 'self_attention.dense.weight', ] def a ( snake_case__: List[Any] , snake_case__: Dict ): '''simple docstring''' lowercase_ = { '''word_embeddings.weight''': '''word_embeddings.weight''', '''word_embeddings.norm.weight''': '''word_embeddings_layernorm.weight''', '''word_embeddings.norm.bias''': '''word_embeddings_layernorm.bias''', '''weight''': '''ln_f.weight''', '''bias''': '''ln_f.bias''', } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks lowercase_ = int(re.match(r'''.*layer_(\d*).*''' , _UpperCamelCase )[1] ) layer_number -= 3 return F'''h.{layer_number}.''' + key def a ( snake_case__: int ): '''simple docstring''' if dtype == torch.bool: return 1 / 8 lowercase_ = re.search(r'''[^\d](\d+)$''' , str(_UpperCamelCase ) ) if bit_search is None: raise ValueError(F'''`dtype` is not a valid dtype: {dtype}.''' ) lowercase_ = int(bit_search.groups()[0] ) return bit_size // 8 def a ( snake_case__: int , snake_case__: List[str] , snake_case__: Tuple , snake_case__: Dict , snake_case__: Optional[Any] ): '''simple docstring''' if bloom_config_file == "": lowercase_ = BloomConfig() else: lowercase_ = BloomConfig.from_json_file(_UpperCamelCase ) if shard_model: lowercase_ = os.listdir(_UpperCamelCase ) lowercase_ = sorted(filter(lambda snake_case__ : s.startswith('''layer''' ) and "model_00" in s , _UpperCamelCase ) ) lowercase_ = {'''weight_map''': {}, '''metadata''': {}} lowercase_ = 0 lowercase_ = None lowercase_ = BloomConfig() for j, file in enumerate(_UpperCamelCase ): print('''Processing file: {}'''.format(_UpperCamelCase ) ) lowercase_ = None for i in range(_UpperCamelCase ): # load all TP files lowercase_ = file.replace('''model_00''' , F'''model_0{i}''' ) lowercase_ = torch.load(os.path.join(_UpperCamelCase , _UpperCamelCase ) , map_location='''cpu''' ) # Rename keys in the transformers names lowercase_ = list(temp.keys() ) for key in keys: lowercase_ = temp.pop(_UpperCamelCase ) if tensors is None: lowercase_ = temp else: for key in tensors.keys(): if any(key.endswith(_UpperCamelCase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel lowercase_ = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks lowercase_ = torch.cat([tensors[key], temp[key]] , dim=_UpperCamelCase ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(_UpperCamelCase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): lowercase_ = tensors[key] / pretraining_tp torch.save( _UpperCamelCase , os.path.join( _UpperCamelCase , '''pytorch_model_{}-of-{}.bin'''.format(str(j + 1 ).zfill(5 ) , str(len(_UpperCamelCase ) ).zfill(5 ) ) , ) , ) for key in tensors.keys(): lowercase_ = tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: lowercase_ = '''pytorch_model_{}-of-{}.bin'''.format( str(j + 1 ).zfill(5 ) , str(len(_UpperCamelCase ) ).zfill(5 ) ) lowercase_ = BloomConfig() lowercase_ = pytorch_dump_folder_path + '''/''' + CONFIG_NAME lowercase_ = total_size with open(_UpperCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) with open(os.path.join(_UpperCamelCase , WEIGHTS_NAME + '''.index.json''' ) , '''w''' , encoding='''utf-8''' ) as f: lowercase_ = json.dumps(_UpperCamelCase , indent=2 , sort_keys=_UpperCamelCase ) + '''\n''' f.write(_UpperCamelCase ) else: lowercase_ = BloomModel(_UpperCamelCase ) lowercase_ = os.listdir(_UpperCamelCase ) lowercase_ = sorted(filter(lambda snake_case__ : s.startswith('''layer''' ) and "model_00" in s , _UpperCamelCase ) ) lowercase_ = None for i, file in enumerate(_UpperCamelCase ): lowercase_ = None for i in range(_UpperCamelCase ): # load all TP files lowercase_ = file.replace('''model_00''' , F'''model_0{i}''' ) lowercase_ = torch.load(os.path.join(_UpperCamelCase , _UpperCamelCase ) , map_location='''cpu''' ) # Rename keys in the transformers names lowercase_ = list(temp.keys() ) for key in keys: lowercase_ = temp.pop(_UpperCamelCase ) if tensors is None: lowercase_ = temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(_UpperCamelCase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel lowercase_ = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks lowercase_ = torch.cat([tensors[key], temp[key]] , dim=_UpperCamelCase ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(_UpperCamelCase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): lowercase_ = tensors[key] / pretraining_tp lowercase_ = model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) assert not other_keys.unexpected_keys, F'''The keys {other_keys.unexpected_keys} are unexpected''' if missing_keys is None: lowercase_ = set(other_keys.missing_keys ) else: lowercase_ = missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, F'''The keys {missing_keys} are missing''' # Save pytorch-model os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase ) lowercase_ = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME lowercase_ = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'''Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}''' ) if config.torch_dtype is not None: lowercase_ = model.to(config.torch_dtype ) torch.save(model.state_dict() , _UpperCamelCase ) print(F'''Save configuration file to {pytorch_config_dump_path}''' ) with open(_UpperCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __a = argparse.ArgumentParser() # Required parameters parser.add_argument( '--bloom_checkpoint_path', default=None, type=str, required=True, help='Path to the Megatron-LM checkpoint path.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--bloom_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--shard_model', action='store_true', help='An optional setting to shard the output model \nThis enables sharding the converted checkpoint', ) parser.add_argument( '--pretraining_tp', default=4, type=int, help='Pretraining TP rank that has been used when training the model in Megatron-LM \n', ) __a = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
30
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase_ = logging.getLogger(__name__) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : List[str] = argparse.ArgumentParser( description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' ) parser.add_argument( '''--dataset_name''' , type=_UpperCamelCase , default='''wikitext''' , help='''Name of the training. Explore datasets at: hf.co/datasets.''' , ) parser.add_argument( '''--dataset_config''' , type=_UpperCamelCase , default='''wikitext-103-raw-v1''' , help='''Configuration name of the dataset.''' ) parser.add_argument( '''--tokenizer_name_or_path''' , type=_UpperCamelCase , default='''sayakpaul/unigram-tokenizer-wikitext''' , help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' , ) parser.add_argument( '''--shard_size''' , type=_UpperCamelCase , default=1_000 , help='''Number of entries to go in a single shard.''' , ) parser.add_argument('''--split''' , type=_UpperCamelCase , default='''train''' , choices=['''train''', '''test''', '''validation'''] ) parser.add_argument( '''--limit''' , default=_UpperCamelCase , type=_UpperCamelCase , help='''Limit the number of shards (used for debugging).''' , ) parser.add_argument( '''--max_length''' , type=_UpperCamelCase , default=512 , help='''Maximum sequence length. For training on TPUs, it helps to have a maximum''' ''' sequence length that is a multiple of 8.''' , ) parser.add_argument( '''--output_dir''' , default='''tf-tpu''' , type=_UpperCamelCase , help='''Output directory where the TFRecord shards will be saved. If the''' ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord''' ''' shards will be directly saved to a Google Cloud Storage bucket.''' , ) snake_case_ : List[Any] = parser.parse_args() return args def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple: """simple docstring""" def fn(_UpperCamelCase ): return tokenizer(examples['''text'''] ) return fn def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : Any = [] for i in range(len(tokenized_data['''input_ids'''] ) ): snake_case_ : Any = { '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ), '''attention_mask''': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ), } snake_case_ : Optional[int] = tf.train.Features(feature=_UpperCamelCase ) snake_case_ : Optional[Any] = tf.train.Example(features=_UpperCamelCase ) snake_case_ : Optional[Any] = example.SerializeToString() records.append(_UpperCamelCase ) return records def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : int = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: snake_case_ : Union[str, Any] = min(len(_UpperCamelCase ) , args.limit ) snake_case_ : int = dataset.select(range(_UpperCamelCase ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) snake_case_ : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) snake_case_ : str = os.path.join(args.output_dir , args.split ) if not os.path.exists(_UpperCamelCase ): os.makedirs(_UpperCamelCase ) else: snake_case_ : Optional[Any] = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. snake_case_ : Optional[Any] = tokenize_function(_UpperCamelCase ) snake_case_ : List[Any] = dataset.map(_UpperCamelCase , batched=_UpperCamelCase , num_proc=4 , remove_columns=['''text'''] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(_UpperCamelCase ): # Concatenate all texts. snake_case_ : Tuple = {k: sum(examples[k] , [] ) for k in examples.keys()} snake_case_ : List[str] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 snake_case_ : int = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. snake_case_ : Union[str, Any] = { k: [t[i : i + args.max_length] for i in range(0 , _UpperCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result snake_case_ : int = dataset_tokenized.map(_UpperCamelCase , batched=_UpperCamelCase , batch_size=1_000 , num_proc=4 ) snake_case_ : str = 0 snake_case_ : Optional[Any] = 0 for shard in range(0 , len(_UpperCamelCase ) , args.shard_size ): snake_case_ : Any = grouped_dataset[shard : shard + args.shard_size] snake_case_ : str = len(dataset_snapshot['''input_ids'''] ) snake_case_ : Union[str, Any] = os.path.join(_UpperCamelCase , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) snake_case_ : Dict = get_serialized_examples(_UpperCamelCase ) with tf.io.TFRecordWriter(_UpperCamelCase ) as out_file: for i in range(len(_UpperCamelCase ) ): snake_case_ : List[str] = serialized_examples[i] out_file.write(_UpperCamelCase ) print('''Wrote file {} containing {} records'''.format(_UpperCamelCase , _UpperCamelCase ) ) shard_count += 1 total_records += records_containing with open(f'''split-{args.split}-records-count.txt''' , '''w''' ) as f: print(f'''Total {args.split} records: {total_records}''' , file=_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = parse_args() main(args)
279
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING a_ = logging.get_logger(__name__) a_ = { """salesforce/blip2-opt-2.7b""": """https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json""", } class __lowerCAmelCase ( _a ): lowerCAmelCase__ = '''blip_2_vision_model''' def __init__( self , __UpperCAmelCase=1408 , __UpperCAmelCase=6144 , __UpperCAmelCase=39 , __UpperCAmelCase=16 , __UpperCAmelCase=224 , __UpperCAmelCase=14 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.00_001 , __UpperCAmelCase=0.0 , __UpperCAmelCase=1E-1_0 , __UpperCAmelCase=True , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) __lowerCamelCase = hidden_size __lowerCamelCase = intermediate_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = patch_size __lowerCamelCase = image_size __lowerCamelCase = initializer_range __lowerCamelCase = attention_dropout __lowerCamelCase = layer_norm_eps __lowerCamelCase = hidden_act __lowerCamelCase = qkv_bias @classmethod def lowerCamelCase ( cls , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' cls._set_token_in_kwargs(__UpperCAmelCase ) __lowerCamelCase = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": __lowerCamelCase = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) class __lowerCAmelCase ( _a ): lowerCAmelCase__ = '''blip_2_qformer''' def __init__( self , __UpperCAmelCase=30522 , __UpperCAmelCase=768 , __UpperCAmelCase=12 , __UpperCAmelCase=12 , __UpperCAmelCase=3072 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=512 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-1_2 , __UpperCAmelCase=0 , __UpperCAmelCase="absolute" , __UpperCAmelCase=2 , __UpperCAmelCase=1408 , **__UpperCAmelCase , ): '''simple docstring''' super().__init__(pad_token_id=__UpperCAmelCase , **__UpperCAmelCase ) __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = position_embedding_type __lowerCamelCase = cross_attention_frequency __lowerCamelCase = encoder_hidden_size @classmethod def lowerCamelCase ( cls , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' cls._set_token_in_kwargs(__UpperCAmelCase ) __lowerCamelCase = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": __lowerCamelCase = config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) class __lowerCAmelCase ( _a ): lowerCAmelCase__ = '''blip-2''' lowerCAmelCase__ = True def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=32 , **__UpperCAmelCase ): '''simple docstring''' super().__init__(**__UpperCAmelCase ) if vision_config is None: __lowerCamelCase = {} logger.info('''vision_config is None. initializing the Blip2VisionConfig with default values.''' ) if qformer_config is None: __lowerCamelCase = {} logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.''' ) if text_config is None: __lowerCamelCase = {} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) __lowerCamelCase = BlipaVisionConfig(**__UpperCAmelCase ) __lowerCamelCase = BlipaQFormerConfig(**__UpperCAmelCase ) __lowerCamelCase = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' __lowerCamelCase = CONFIG_MAPPING[text_model_type](**__UpperCAmelCase ) __lowerCamelCase = self.text_config.tie_word_embeddings __lowerCamelCase = self.text_config.is_encoder_decoder __lowerCamelCase = num_query_tokens __lowerCamelCase = self.vision_config.hidden_size __lowerCamelCase = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __lowerCamelCase = 1.0 __lowerCamelCase = 0.02 @classmethod def lowerCamelCase ( cls , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase , ): '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **__UpperCAmelCase , ) def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.vision_config.to_dict() __lowerCamelCase = self.qformer_config.to_dict() __lowerCamelCase = self.text_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
330
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Any = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Any = hf_hub_download( repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : List[Any] = VideoClassificationPipeline(model=__magic_name__ , image_processor=__magic_name__ , top_k=2 ) snake_case_ : str = [ example_video_filepath, '''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''', ] return video_classifier, examples def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' for example in examples: snake_case_ : Union[str, Any] = video_classifier(__magic_name__ ) self.assertEqual( __magic_name__ , [ {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, ] , ) @require_torch def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Any = '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification''' snake_case_ : str = VideoMAEFeatureExtractor( size={'''shortest_edge''': 10} , crop_size={'''height''': 10, '''width''': 10} ) snake_case_ : int = pipeline( '''video-classification''' , model=__magic_name__ , feature_extractor=__magic_name__ , frame_sampling_rate=4 ) snake_case_ : List[str] = hf_hub_download(repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : Union[str, Any] = video_classifier(__magic_name__ , top_k=2 ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}] , ) snake_case_ : int = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], ] , ) @require_tf def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' pass
279
0
'''simple docstring''' import copy from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging a_ : Tuple = logging.get_logger(__name__) class a ( _a ): _lowerCAmelCase = ['''input_features'''] def __init__( self , __magic_name__=80 , __magic_name__=1_60_00 , __magic_name__=1_60 , __magic_name__=30 , __magic_name__=4_00 , __magic_name__=0.0 , __magic_name__=False , **__magic_name__ , ) -> Optional[int]: super().__init__( feature_size=__magic_name__ , sampling_rate=__magic_name__ , padding_value=__magic_name__ , return_attention_mask=__magic_name__ , **__magic_name__ , ) _a = n_fft _a = hop_length _a = chunk_length _a = chunk_length * sampling_rate _a = self.n_samples // hop_length _a = sampling_rate _a = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=__magic_name__ , min_frequency=0.0 , max_frequency=80_00.0 , sampling_rate=__magic_name__ , norm='slaney' , mel_scale='slaney' , ) def __UpperCAmelCase ( self , __magic_name__ ) -> np.ndarray: _a = spectrogram( __magic_name__ , window_function(self.n_fft , 'hann' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel='log10' , ) _a = log_spec[:, :-1] _a = np.maximum(__magic_name__ , log_spec.max() - 8.0 ) _a = (log_spec + 4.0) / 4.0 return log_spec @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def __UpperCAmelCase ( __magic_name__ , __magic_name__ , __magic_name__ = 0.0 ) -> List[np.ndarray]: if attention_mask is not None: _a = np.array(__magic_name__ , np.intaa ) _a = [] for vector, length in zip(__magic_name__ , attention_mask.sum(-1 ) ): _a = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 ) if length < normed_slice.shape[0]: _a = padding_value normed_input_values.append(__magic_name__ ) else: _a = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values] return normed_input_values def __call__( self , __magic_name__ , __magic_name__ = True , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , __magic_name__ = "max_length" , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , **__magic_name__ , ) -> BatchFeature: if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a' f' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input' f' was sampled with {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( 'It is strongly recommended to pass the `sampling_rate` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) _a = isinstance(__magic_name__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) _a = is_batched_numpy or ( isinstance(__magic_name__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: _a = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(__magic_name__ , np.ndarray ): _a = np.asarray(__magic_name__ , dtype=np.floataa ) elif isinstance(__magic_name__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): _a = raw_speech.astype(np.floataa ) # always return batch if not is_batched: _a = [np.asarray([raw_speech] ).T] _a = BatchFeature({'input_features': raw_speech} ) # convert into correct format for padding _a = self.pad( __magic_name__ , padding=__magic_name__ , max_length=max_length if max_length else self.n_samples , truncation=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_attention_mask=return_attention_mask or do_normalize , ) # zero-mean and unit-variance normalization if do_normalize: _a = self.zero_mean_unit_var_norm( padded_inputs['input_features'] , attention_mask=padded_inputs['attention_mask'] , padding_value=self.padding_value , ) _a = np.stack(padded_inputs['input_features'] , axis=0 ) # make sure list is in array format _a = padded_inputs.get('input_features' ).transpose(2 , 0 , 1 ) _a = [self._np_extract_fbank_features(__magic_name__ ) for waveform in input_features[0]] if isinstance(input_features[0] , __magic_name__ ): _a = [np.asarray(__magic_name__ , dtype=np.floataa ) for feature in input_features] else: _a = input_features if return_attention_mask: # rescale from sample (48000) to feature (3000) _a = padded_inputs['''attention_mask'''][:, :: self.hop_length] if return_tensors is not None: _a = padded_inputs.convert_to_tensors(__magic_name__ ) return padded_inputs def __UpperCAmelCase ( self ) -> Dict[str, Any]: _a = copy.deepcopy(self.__dict__ ) _a = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] return output
168
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" return "\n".join( f'''{number} * {i} = {number * i}''' for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=1_0))
279
0
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__)
302
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCAmelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" snake_case_ : List[str] = ['''layers''', '''blocks'''] for k in ignore_keys: state_dict.pop(_UpperCamelCase , _UpperCamelCase ) lowerCAmelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" snake_case_ : str = list(s_dict.keys() ) for key in keys: snake_case_ : Optional[int] = key for k, v in WHISPER_MAPPING.items(): if k in key: snake_case_ : List[str] = new_key.replace(_UpperCamelCase , _UpperCamelCase ) print(f'''{key} -> {new_key}''' ) snake_case_ : Tuple = s_dict.pop(_UpperCamelCase ) return s_dict def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" snake_case_ , snake_case_ : Dict = emb.weight.shape snake_case_ : Tuple = nn.Linear(_UpperCamelCase , _UpperCamelCase , bias=_UpperCamelCase ) snake_case_ : Any = emb.weight.data return lin_layer def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> bytes: """simple docstring""" os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase ) snake_case_ : List[Any] = os.path.basename(_UpperCamelCase ) snake_case_ : Any = url.split('''/''' )[-2] snake_case_ : str = os.path.join(_UpperCamelCase , _UpperCamelCase ) if os.path.exists(_UpperCamelCase ) and not os.path.isfile(_UpperCamelCase ): raise RuntimeError(f'''{download_target} exists and is not a regular file''' ) if os.path.isfile(_UpperCamelCase ): snake_case_ : Union[str, Any] = open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file''' ) with urllib.request.urlopen(_UpperCamelCase ) as source, open(_UpperCamelCase , '''wb''' ) as output: with tqdm( total=int(source.info().get('''Content-Length''' ) ) , ncols=80 , unit='''iB''' , unit_scale=_UpperCamelCase , unit_divisor=1_024 ) as loop: while True: snake_case_ : Dict = source.read(8_192 ) if not buffer: break output.write(_UpperCamelCase ) loop.update(len(_UpperCamelCase ) ) snake_case_ : Any = open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() != expected_shaaaa: raise RuntimeError( '''Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.''' ) return model_bytes def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" if ".pt" not in checkpoint_path: snake_case_ : str = _download(_MODELS[checkpoint_path] ) else: snake_case_ : Union[str, Any] = torch.load(_UpperCamelCase , map_location='''cpu''' ) snake_case_ : int = original_checkpoint['''dims'''] snake_case_ : List[str] = original_checkpoint['''model_state_dict'''] snake_case_ : str = state_dict['''decoder.token_embedding.weight'''] remove_ignore_keys_(_UpperCamelCase ) rename_keys(_UpperCamelCase ) snake_case_ : Optional[int] = True snake_case_ : int = state_dict['''decoder.layers.0.fc1.weight'''].shape[0] snake_case_ : List[str] = WhisperConfig( vocab_size=dimensions['''n_vocab'''] , encoder_ffn_dim=_UpperCamelCase , decoder_ffn_dim=_UpperCamelCase , num_mel_bins=dimensions['''n_mels'''] , d_model=dimensions['''n_audio_state'''] , max_target_positions=dimensions['''n_text_ctx'''] , encoder_layers=dimensions['''n_audio_layer'''] , encoder_attention_heads=dimensions['''n_audio_head'''] , decoder_layers=dimensions['''n_text_layer'''] , decoder_attention_heads=dimensions['''n_text_state'''] , max_source_positions=dimensions['''n_audio_ctx'''] , ) snake_case_ : Union[str, Any] = WhisperForConditionalGeneration(_UpperCamelCase ) snake_case_ , snake_case_ : List[Any] = model.model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) if len(_UpperCamelCase ) > 0 and not set(_UpperCamelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' f''' but all the following weights are missing {missing}''' ) if tie_embeds: snake_case_ : List[str] = make_linear_from_emb(model.model.decoder.embed_tokens ) else: snake_case_ : Any = proj_out_weights model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCAmelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
279
0
class SCREAMING_SNAKE_CASE_ : def __init__( self : int , _A : Tuple , _A : List[str] , _A : List[Any] ) -> Dict: """simple docstring""" snake_case_ : Any = name snake_case_ : int = value snake_case_ : Optional[int] = weight def __repr__( self : Any ) -> Dict: """simple docstring""" return F"""{self.__class__.__name__}({self.name}, {self.value}, {self.weight})""" def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: """simple docstring""" return self.value def UpperCAmelCase_ ( self : str ) -> List[str]: """simple docstring""" return self.name def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" return self.weight def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: """simple docstring""" return self.value / self.weight def SCREAMING_SNAKE_CASE__ ( __a , __a , __a ): snake_case_ : Tuple = [] for i in range(len(_UpperCamelCase ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def SCREAMING_SNAKE_CASE__ ( __a , __a , __a ): snake_case_ : Union[str, Any] = sorted(_UpperCamelCase , key=_UpperCamelCase , reverse=_UpperCamelCase ) snake_case_ : Any = [] snake_case_ : List[Any] = 0.0, 0.0 for i in range(len(_UpperCamelCase ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def SCREAMING_SNAKE_CASE__ ( ): pass if __name__ == "__main__": import doctest doctest.testmod()
327
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCAmelCase_ = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) lowerCAmelCase_ = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 1_4]), ('''2H 5D 3C AS 5S''', False, [1_4, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [1_4, 1_3, 1_2, 1_1, 1_0]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 2_3), ('''JH 9H TH KH QH''', 2_2), ('''JC KH JS JD JH''', 2_1), ('''KH KC 3S 3H 3D''', 2_0), ('''8C 9C 5C 3C TC''', 1_9), ('''JS QS 9H TS KH''', 1_8), ('''7C 7S KH 2H 7H''', 1_7), ('''3C KH 5D 5S KH''', 1_6), ('''QH 8H KD JH 8S''', 1_5), ('''2D 6D 9D TH 7D''', 1_4), ) def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ , snake_case_ : Any = randrange(len(_UpperCamelCase ) ), randrange(len(_UpperCamelCase ) ) snake_case_ : Any = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] snake_case_ , snake_case_ : Tuple = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def lowerCamelCase_ ( _UpperCamelCase = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(_UpperCamelCase )) @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : str = PokerHand(_UpperCamelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[Any]: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = [PokerHand(_UpperCamelCase ) for hand in SORTED_HANDS] snake_case_ : str = poker_hands.copy() shuffle(_UpperCamelCase ) snake_case_ : List[str] = chain(sorted(_UpperCamelCase ) ) for index, hand in enumerate(_UpperCamelCase ): assert hand == poker_hands[index] def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ : Union[str, Any] = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=_UpperCamelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = PokerHand('''2C 4S AS 3D 5C''' ) snake_case_ : str = True snake_case_ : Tuple = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def lowerCamelCase_ ( ) -> List[str]: """simple docstring""" snake_case_ : List[str] = 0 snake_case_ : Union[str, Any] = os.path.abspath(os.path.dirname(_UpperCamelCase ) ) snake_case_ : Dict = os.path.join(_UpperCamelCase , '''poker_hands.txt''' ) with open(_UpperCamelCase ) as file_hand: for line in file_hand: snake_case_ : Dict = line[:14].strip() snake_case_ : List[str] = line[15:].strip() snake_case_ , snake_case_ : str = PokerHand(_UpperCamelCase ), PokerHand(_UpperCamelCase ) snake_case_ : int = player.compare_with(_UpperCamelCase ) if output == "Win": answer += 1 assert answer == 376
279
0
'''simple docstring''' import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup A__: int = { '''User-Agent''': '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36''' ''' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582''' } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] = "dhaka" ,_UpperCAmelCase : int = 5 ) -> int: _a : Dict =min(_UpperCamelCase ,50 ) # Prevent abuse! _a : str ={ '''q''': query, '''tbm''': '''isch''', '''hl''': '''en''', '''ijn''': '''0''', } _a : Tuple =requests.get("""https://www.google.com/search""" ,params=_UpperCamelCase ,headers=_UpperCamelCase ) _a : Optional[int] =BeautifulSoup(html.text ,"""html.parser""" ) _a : Tuple =''''''.join( re.findall(R"""AF_initDataCallback\(([^<]+)\);""" ,str(soup.select("""script""" ) ) ) ) _a : Optional[Any] =json.dumps(_UpperCamelCase ) _a : Union[str, Any] =json.loads(_UpperCamelCase ) _a : Dict =re.findall( R"""\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",""" ,_UpperCamelCase ,) if not matched_google_image_data: return 0 _a : int =re.sub( R"""\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]""" ,"""""" ,str(_UpperCamelCase ) ,) _a : List[Any] =re.findall( R"""(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]""" ,_UpperCamelCase ,) for index, fixed_full_res_image in enumerate(_UpperCamelCase ): if index >= max_images: return index _a : Union[str, Any] =bytes(_UpperCamelCase ,"""ascii""" ).decode( """unicode-escape""" ) _a : Any =bytes(_UpperCamelCase ,"""ascii""" ).decode( """unicode-escape""" ) _a : Tuple =urllib.request.build_opener() _a : Union[str, Any] =[ ( '''User-Agent''', '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36''' ''' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582''', ) ] urllib.request.install_opener(_UpperCamelCase ) _a : Optional[Any] =F"query_{query.replace(' ' ,'_' )}" if not os.path.exists(_UpperCamelCase ): os.makedirs(_UpperCamelCase ) urllib.request.urlretrieve( # noqa: S310 _UpperCamelCase ,F"{path_name}/original_size_img_{index}.jpg" ) return index if __name__ == "__main__": try: A__: str = download_images_from_google_query(sys.argv[1]) print(F"{image_count} images were downloaded to disk.") except IndexError: print('''Please provide a search term.''') raise
276
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available lowerCAmelCase_ = logging.getLogger(__name__) @dataclass class __lowerCAmelCase : lowerCamelCase_ : str lowerCamelCase_ : List[str] lowerCamelCase_ : Optional[List[str]] @dataclass class __lowerCAmelCase : lowerCamelCase_ : List[int] lowerCamelCase_ : List[int] lowerCamelCase_ : Optional[List[int]] = None lowerCamelCase_ : Optional[List[int]] = None class __lowerCAmelCase ( _a ): lowerCamelCase_ : str = '''train''' lowerCamelCase_ : List[str] = '''dev''' lowerCamelCase_ : List[Any] = '''test''' class __lowerCAmelCase : @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def lowerCamelCase (__magic_name__ ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=False , __magic_name__="[CLS]" , __magic_name__=1 , __magic_name__="[SEP]" , __magic_name__=False , __magic_name__=False , __magic_name__=0 , __magic_name__=0 , __magic_name__=-100 , __magic_name__=0 , __magic_name__=True , ) -> List[InputFeatures]: '''simple docstring''' snake_case_ : Optional[int] = {label: i for i, label in enumerate(__magic_name__ )} snake_case_ : Dict = [] for ex_index, example in enumerate(__magic_name__ ): if ex_index % 1_0000 == 0: logger.info('''Writing example %d of %d''' , __magic_name__ , len(__magic_name__ ) ) snake_case_ : List[str] = [] snake_case_ : List[str] = [] for word, label in zip(example.words , example.labels ): snake_case_ : Optional[Any] = tokenizer.tokenize(__magic_name__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(__magic_name__ ) > 0: tokens.extend(__magic_name__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__magic_name__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. snake_case_ : Union[str, Any] = tokenizer.num_special_tokens_to_add() if len(__magic_name__ ) > max_seq_length - special_tokens_count: snake_case_ : str = tokens[: (max_seq_length - special_tokens_count)] snake_case_ : Any = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] snake_case_ : Union[str, Any] = [sequence_a_segment_id] * len(__magic_name__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: snake_case_ : Union[str, Any] = [cls_token] + tokens snake_case_ : List[Any] = [pad_token_label_id] + label_ids snake_case_ : Optional[Any] = [cls_token_segment_id] + segment_ids snake_case_ : Optional[Any] = tokenizer.convert_tokens_to_ids(__magic_name__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. snake_case_ : int = [1 if mask_padding_with_zero else 0] * len(__magic_name__ ) # Zero-pad up to the sequence length. snake_case_ : Optional[int] = max_seq_length - len(__magic_name__ ) if pad_on_left: snake_case_ : Optional[Any] = ([pad_token] * padding_length) + input_ids snake_case_ : Optional[int] = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask snake_case_ : Optional[Any] = ([pad_token_segment_id] * padding_length) + segment_ids snake_case_ : Dict = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(__magic_name__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(__magic_name__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: snake_case_ : int = None features.append( InputFeatures( input_ids=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , label_ids=__magic_name__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[InputFeatures] lowerCamelCase_ : int = nn.CrossEntropyLoss().ignore_index def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=False , __magic_name__ = Split.train , ) -> Union[str, Any]: '''simple docstring''' snake_case_ : List[str] = os.path.join( __magic_name__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(__magic_name__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case_ : Dict = cached_features_file + '''.lock''' with FileLock(__magic_name__ ): if os.path.exists(__magic_name__ ) and not overwrite_cache: logger.info(F'''Loading features from cached file {cached_features_file}''' ) snake_case_ : Dict = torch.load(__magic_name__ ) else: logger.info(F'''Creating features from dataset file at {data_dir}''' ) snake_case_ : Any = token_classification_task.read_examples_from_file(__magic_name__ , __magic_name__ ) # TODO clean up all this to leverage built-in features of tokenizers snake_case_ : int = token_classification_task.convert_examples_to_features( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , __magic_name__ ) def __len__(self ) -> Optional[Any]: '''simple docstring''' return len(self.features ) def __getitem__(self , __magic_name__ ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class __lowerCAmelCase : lowerCamelCase_ : List[InputFeatures] lowerCamelCase_ : int = -100 def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=False , __magic_name__ = Split.train , ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[int] = token_classification_task.read_examples_from_file(__magic_name__ , __magic_name__ ) # TODO clean up all this to leverage built-in features of tokenizers snake_case_ : int = token_classification_task.convert_examples_to_features( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: snake_case_ : Optional[Any] = tf.data.Dataset.from_generator( __magic_name__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: snake_case_ : int = tf.data.Dataset.from_generator( __magic_name__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__(self ) -> str: '''simple docstring''' return len(self.features ) def __getitem__(self , __magic_name__ ) -> InputFeatures: '''simple docstring''' return self.features[i]
279
0
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home SCREAMING_SNAKE_CASE_ = HUGGINGFACE_HUB_CACHE SCREAMING_SNAKE_CASE_ = '''config.json''' SCREAMING_SNAKE_CASE_ = '''diffusion_pytorch_model.bin''' SCREAMING_SNAKE_CASE_ = '''diffusion_flax_model.msgpack''' SCREAMING_SNAKE_CASE_ = '''model.onnx''' SCREAMING_SNAKE_CASE_ = '''diffusion_pytorch_model.safetensors''' SCREAMING_SNAKE_CASE_ = '''weights.pb''' SCREAMING_SNAKE_CASE_ = '''https://huggingface.co''' SCREAMING_SNAKE_CASE_ = default_cache_path SCREAMING_SNAKE_CASE_ = '''diffusers_modules''' SCREAMING_SNAKE_CASE_ = os.getenv('''HF_MODULES_CACHE''', os.path.join(hf_cache_home, '''modules''')) SCREAMING_SNAKE_CASE_ = ['''fp16''', '''non-ema'''] SCREAMING_SNAKE_CASE_ = '''.self_attn'''
301
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir('''fixtures/test_sentencepiece_bpe_char.model''') @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[int] = SpeechTaTokenizer lowerCamelCase_ : int = False lowerCamelCase_ : Dict = True def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing snake_case_ : Tuple = SpeechTaTokenizer(__magic_name__ ) snake_case_ : Any = AddedToken('''<mask>''' , lstrip=__magic_name__ , rstrip=__magic_name__ ) snake_case_ : int = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Dict = '''this is a test''' snake_case_ : int = '''this is a test''' return input_text, output_text def lowerCamelCase (self , __magic_name__ , __magic_name__=False , __magic_name__=20 , __magic_name__=5 ) -> List[Any]: '''simple docstring''' snake_case_ , snake_case_ : int = self.get_input_output_texts(__magic_name__ ) snake_case_ : Optional[Any] = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) snake_case_ : Any = tokenizer.decode(__magic_name__ , clean_up_tokenization_spaces=__magic_name__ ) return text, ids def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[str] = '''<pad>''' snake_case_ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__magic_name__ ) , 81 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : int = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): snake_case_ : int = tokenizer.vocab_size snake_case_ : Optional[Any] = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case_ : List[Any] = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] snake_case_ : List[Any] = tokenizer.add_tokens(__magic_name__ ) snake_case_ : Dict = tokenizer.vocab_size snake_case_ : Optional[Any] = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size + len(__magic_name__ ) ) snake_case_ : Union[str, Any] = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case_ : Union[str, Any] = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} snake_case_ : List[str] = tokenizer.add_special_tokens(__magic_name__ ) snake_case_ : Dict = tokenizer.vocab_size snake_case_ : Dict = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size_a + len(__magic_name__ ) ) snake_case_ : Tuple = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> List[str]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.get_tokenizer() snake_case_ : Optional[Any] = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__magic_name__ , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case_ : List[Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) snake_case_ : List[str] = tokenizer.convert_tokens_to_ids(__magic_name__ ) # fmt: off self.assertListEqual(__magic_name__ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case_ : int = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Tuple = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off snake_case_ : List[Any] = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__magic_name__ , )
279
0
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import torch from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available @dataclass class UpperCamelCase__ ( _a ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_text_to_video_synth import TextToVideoSDPipeline from .pipeline_text_to_video_synth_imgaimg import VideoToVideoSDPipeline # noqa: F401 from .pipeline_text_to_video_zero import TextToVideoZeroPipeline
323
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' ) for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): if dist[i][j] != float('''inf''' ): print(int(dist[i][j] ) , end='''\t''' ) else: print('''INF''' , end='''\t''' ) print() def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : int = [[float('''inf''' ) for _ in range(_UpperCamelCase )] for _ in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): snake_case_ : Dict = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(_UpperCamelCase ): # looping through rows of graph array for i in range(_UpperCamelCase ): # looping through columns of graph array for j in range(_UpperCamelCase ): if ( dist[i][k] != float('''inf''' ) and dist[k][j] != float('''inf''' ) and dist[i][k] + dist[k][j] < dist[i][j] ): snake_case_ : List[Any] = dist[i][k] + dist[k][j] _print_dist(_UpperCamelCase , _UpperCamelCase ) return dist, v if __name__ == "__main__": lowerCAmelCase_ = int(input('''Enter number of vertices: ''')) lowerCAmelCase_ = int(input('''Enter number of edges: ''')) lowerCAmelCase_ = [[float('''inf''') for i in range(v)] for j in range(v)] for i in range(v): lowerCAmelCase_ = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print('''\nEdge ''', i + 1) lowerCAmelCase_ = int(input('''Enter source:''')) lowerCAmelCase_ = int(input('''Enter destination:''')) lowerCAmelCase_ = float(input('''Enter weight:''')) lowerCAmelCase_ = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
279
0
"""simple docstring""" from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE ={ "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } __SCREAMING_SNAKE_CASE ={ "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } __SCREAMING_SNAKE_CASE ={ "facebook/blenderbot_small-90M": 512, } class UpperCamelCase ( _a ): lowercase = VOCAB_FILES_NAMES lowercase = PRETRAINED_VOCAB_FILES_MAP lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase = BlenderbotSmallTokenizer def __init__( self ,__UpperCamelCase=None ,__UpperCamelCase=None ,__UpperCamelCase="<|endoftext|>" ,__UpperCamelCase="<|endoftext|>" ,__UpperCamelCase="<|endoftext|>" ,__UpperCamelCase=False ,__UpperCamelCase=True ,**__UpperCamelCase ,) -> Any: '''simple docstring''' super().__init__( ByteLevelBPETokenizer( vocab=__UpperCamelCase ,merges=__UpperCamelCase ,add_prefix_space=__UpperCamelCase ,trim_offsets=__UpperCamelCase ,) ,bos_token=__UpperCamelCase ,eos_token=__UpperCamelCase ,unk_token=__UpperCamelCase ,**__UpperCamelCase ,) lowercase_ : List[Any] = add_prefix_space def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase=None ) -> List[str]: '''simple docstring''' lowercase_ : str = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase = None ) -> List[int]: '''simple docstring''' lowercase_ : Tuple = [self.sep_token_id] lowercase_ : List[Any] = [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]
213
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class __lowerCAmelCase : def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' return None class __lowerCAmelCase : def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' return None class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Dict = [ # (model_name, model_kwargs) ('''bert-base-cased''', {}), ('''gpt2''', {'''use_cache''': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__magic_name__ , '''tf''' , 12 , **__magic_name__ ) @require_torch @slow def lowerCamelCase (self ) -> int: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__magic_name__ , '''pt''' , 12 , **__magic_name__ ) @require_torch @slow def lowerCamelCase (self ) -> int: '''simple docstring''' from transformers import BertModel snake_case_ : str = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(__magic_name__ ) ) vocab_file.flush() snake_case_ : Optional[Any] = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: snake_case_ : str = BertModel(BertConfig(vocab_size=len(__magic_name__ ) ) ) model.save_pretrained(__magic_name__ ) self._test_export(__magic_name__ , '''pt''' , 12 , __magic_name__ ) @require_tf @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ : Tuple = self._test_export(__magic_name__ , '''tf''' , 12 , **__magic_name__ ) snake_case_ : List[str] = quantize(Path(__magic_name__ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__magic_name__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ : Any = self._test_export(__magic_name__ , '''pt''' , 12 , **__magic_name__ ) snake_case_ : Any = quantize(__magic_name__ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__magic_name__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None , **__magic_name__ ) -> Tuple: '''simple docstring''' try: # Compute path with TemporaryDirectory() as tempdir: snake_case_ : List[str] = Path(__magic_name__ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) return path except Exception as e: self.fail(__magic_name__ ) @require_torch @require_tokenizers @slow def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' from transformers import BertModel snake_case_ : Optional[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case_ : int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(__magic_name__ , __magic_name__ , '''pt''' ) @require_tf @require_tokenizers @slow def lowerCamelCase (self ) -> List[str]: '''simple docstring''' from transformers import TFBertModel snake_case_ : Any = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case_ : str = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(__magic_name__ , __magic_name__ , '''tf''' ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : Tuple = FeatureExtractionPipeline(__magic_name__ , __magic_name__ ) snake_case_ : Optional[int] = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] snake_case_ , snake_case_ , snake_case_ , snake_case_ : Optional[int] = infer_shapes(__magic_name__ , __magic_name__ ) # Assert all variables are present self.assertEqual(len(__magic_name__ ) , len(__magic_name__ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __magic_name__ ) self.assertSequenceEqual(variable_names[3:] , __magic_name__ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Tuple = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] snake_case_ : List[str] = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} snake_case_ , snake_case_ : Tuple = ensure_valid_input(FuncContiguousArgs() , __magic_name__ , __magic_name__ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__magic_name__ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__magic_name__ ) , set(__magic_name__ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__magic_name__ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) snake_case_ , snake_case_ : Dict = ensure_valid_input(FuncNonContiguousArgs() , __magic_name__ , __magic_name__ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Optional[int] = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
279
0
def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> List[str]: '''simple docstring''' print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' ) for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): if dist[i][j] != float('''inf''' ): print(int(dist[i][j] ) , end='''\t''' ) else: print('''INF''' , end='''\t''' ) print() def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> Union[str, Any]: '''simple docstring''' UpperCAmelCase : int =[[float('''inf''' ) for _ in range(_UpperCamelCase )] for _ in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): UpperCAmelCase : Dict =graph[i][j] # check vertex k against all other vertices (i, j) for k in range(_UpperCamelCase ): # looping through rows of graph array for i in range(_UpperCamelCase ): # looping through columns of graph array for j in range(_UpperCamelCase ): if ( dist[i][k] != float('''inf''' ) and dist[k][j] != float('''inf''' ) and dist[i][k] + dist[k][j] < dist[i][j] ): UpperCAmelCase : List[Any] =dist[i][k] + dist[k][j] _print_dist(_UpperCamelCase , _UpperCamelCase ) return dist, v if __name__ == "__main__": __snake_case = int(input('''Enter number of vertices: ''')) __snake_case = int(input('''Enter number of edges: ''')) __snake_case = [[float('''inf''') for i in range(v)] for j in range(v)] for i in range(v): __snake_case = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print('''\nEdge ''', i + 1) __snake_case = int(input('''Enter source:''')) __snake_case = int(input('''Enter destination:''')) __snake_case = float(input('''Enter weight:''')) __snake_case = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
348
lowerCAmelCase_ = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.602_176_634e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.355_818, } def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: snake_case_ : str = ( f'''Incorrect \'from_type\' or \'to_type\' value: {from_type!r}, {to_type!r}\n''' f'''Valid values are: {", ".join(_UpperCamelCase )}''' ) raise ValueError(_UpperCamelCase ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
279
0
'''simple docstring''' import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class UpperCamelCase__ ( _a): UpperCAmelCase__ : int = '''''' UpperCAmelCase__ : str = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) UpperCAmelCase__ : str = None # compression type in fsspec. ex: "gzip" UpperCAmelCase__ : str = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self :int , _A :List[Any] = "" , _A :Any = None , _A :Optional[int] = None , **_A :Any ) -> Any: '''simple docstring''' super().__init__(self , **_A ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode __A = fsspec.open( _A , mode='rb' , protocol=_A , compression=self.compression , client_kwargs={ 'requote_redirect_url': False, # see https://github.com/huggingface/datasets/pull/5459 'trust_env': True, # Enable reading proxy env variables. **(target_options or {}).pop('client_kwargs' , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) __A = os.path.basename(self.file.path.split('::' )[0] ) __A = ( self.compressed_name[: self.compressed_name.rindex('.' )] if '''.''' in self.compressed_name else self.compressed_name ) __A = None @classmethod def lowercase_ ( cls :List[str] , _A :List[Any] ) -> Optional[int]: '''simple docstring''' return super()._strip_protocol(_A ).lstrip('/' ) def lowercase_ ( self :List[str] ) -> Union[str, Any]: '''simple docstring''' if self.dir_cache is None: __A = {**self.file.fs.info(self.file.path ), '''name''': self.uncompressed_name} __A = {f['''name''']: f} def lowercase_ ( self :str , _A :Tuple ) -> Optional[Any]: '''simple docstring''' return self.file.open().read() def lowercase_ ( self :Any , _A :Optional[int] , _A :int = "rb" , _A :List[Any]=None , _A :Optional[Any]=True , _A :Any=None , **_A :List[Any] , ) -> int: '''simple docstring''' __A = self._strip_protocol(_A ) if mode != "rb": raise ValueError(F'Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'' ) return self.file.open() class UpperCamelCase__ ( _a): UpperCAmelCase__ : Union[str, Any] = '''bz2''' UpperCAmelCase__ : Any = '''bz2''' UpperCAmelCase__ : int = '''.bz2''' class UpperCamelCase__ ( _a): UpperCAmelCase__ : Union[str, Any] = '''gzip''' UpperCAmelCase__ : Dict = '''gzip''' UpperCAmelCase__ : int = '''.gz''' class UpperCamelCase__ ( _a): UpperCAmelCase__ : Any = '''lz4''' UpperCAmelCase__ : Any = '''lz4''' UpperCAmelCase__ : Optional[Any] = '''.lz4''' class UpperCamelCase__ ( _a): UpperCAmelCase__ : Tuple = '''xz''' UpperCAmelCase__ : Any = '''xz''' UpperCAmelCase__ : int = '''.xz''' class UpperCamelCase__ ( _a): UpperCAmelCase__ : Union[str, Any] = '''zstd''' UpperCAmelCase__ : Tuple = '''zstd''' UpperCAmelCase__ : Any = '''.zst''' def __init__( self :List[Any] , _A :int , _A :Any = "rb" , _A :Union[str, Any] = None , _A :str = None , _A :Optional[int] = DEFAULT_BLOCK_SIZE , **_A :Tuple , ) -> Tuple: '''simple docstring''' super().__init__( fo=_A , mode=_A , target_protocol=_A , target_options=_A , block_size=_A , **_A , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 __A = self.file.__enter__ class UpperCamelCase__ : def __init__( self :Optional[Any] , _A :str ) -> List[Any]: '''simple docstring''' __A = file_ def __enter__( self :Dict ) -> List[Any]: '''simple docstring''' self._file.__enter__() return self def __exit__( self :Tuple , *_A :Any , **_A :str ) -> int: '''simple docstring''' self._file.__exit__(*_A , **_A ) def __iter__( self :int ) -> Optional[int]: '''simple docstring''' return iter(self._file ) def lowercase_ ( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return next(self._file ) def __getattr__( self :int , _A :Optional[Any] ) -> str: '''simple docstring''' return getattr(self._file , _A ) def fixed_enter(*_A :Tuple , **_A :Optional[int] ): return WrappedFile(_enter(*_A , **_A ) ) __A = fixed_enter
161
import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets lowerCAmelCase_ = datasets.logging.get_logger(__name__) lowerCAmelCase_ = '''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } ''' lowerCAmelCase_ = '''\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project\'s README at https://github.com/google-research/bleurt#readme for more information. ''' lowerCAmelCase_ = ''' BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: \'scores\': List of scores. Examples: >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> bleurt = datasets.load_metric("bleurt") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results["scores"]]) [1.03, 1.04] ''' lowerCAmelCase_ = { '''bleurt-tiny-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip''', '''bleurt-tiny-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip''', '''bleurt-base-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip''', '''bleurt-base-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip''', '''bleurt-large-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip''', '''bleurt-large-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip''', '''BLEURT-20-D3''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip''', '''BLEURT-20-D6''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip''', '''BLEURT-20-D12''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip''', '''BLEURT-20''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip''', } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/google-research/bleurt''' , 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/bleurt'''] , reference_urls=['''https://github.com/google-research/bleurt''', '''https://arxiv.org/abs/2004.04696'''] , ) def lowerCamelCase (self , __magic_name__ ) -> List[Any]: '''simple docstring''' if self.config_name == "default": logger.warning( '''Using default BLEURT-Base checkpoint for sequence maximum length 128. ''' '''You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').''' ) snake_case_ : Dict = '''bleurt-base-128''' if self.config_name.lower() in CHECKPOINT_URLS: snake_case_ : Optional[int] = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: snake_case_ : Union[str, Any] = self.config_name.upper() else: raise KeyError( F'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}''' ) # download the model checkpoint specified by self.config_name and set up the scorer snake_case_ : Any = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) snake_case_ : Dict = score.BleurtScorer(os.path.join(__magic_name__ , __magic_name__ ) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Dict = self.scorer.score(references=__magic_name__ , candidates=__magic_name__ ) return {"scores": scores}
279
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a = { '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: __a = [ '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 __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
30
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''): lowerCAmelCase_ = { '''linear''': PIL.Image.Resampling.BILINEAR, '''bilinear''': PIL.Image.Resampling.BILINEAR, '''bicubic''': PIL.Image.Resampling.BICUBIC, '''lanczos''': PIL.Image.Resampling.LANCZOS, '''nearest''': PIL.Image.Resampling.NEAREST, } else: lowerCAmelCase_ = { '''linear''': PIL.Image.LINEAR, '''bilinear''': PIL.Image.BILINEAR, '''bicubic''': PIL.Image.BICUBIC, '''lanczos''': PIL.Image.LANCZOS, '''nearest''': PIL.Image.NEAREST, } def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : Dict = (images / 2 + 0.5).clamp(0 , 1 ) snake_case_ : Dict = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() snake_case_ : int = numpy_to_pil(_UpperCamelCase ) return images def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" if images.ndim == 3: snake_case_ : Optional[Any] = images[None, ...] snake_case_ : Any = (images * 255).round().astype('''uint8''' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images snake_case_ : str = [Image.fromarray(image.squeeze() , mode='''L''' ) for image in images] else: snake_case_ : List[Any] = [Image.fromarray(_UpperCamelCase ) for image in images] return pil_images
279
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer a_ = logging.get_logger(__name__) a_ = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} a_ = { """vocab_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json""" ), }, } a_ = { """yjernite/retribert-base-uncased""": 512, } a_ = { """yjernite/retribert-base-uncased""": {"""do_lower_case""": True}, } class __lowerCAmelCase ( _a ): lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase__ = RetriBertTokenizer lowerCAmelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase="[UNK]" , __UpperCAmelCase="[SEP]" , __UpperCAmelCase="[PAD]" , __UpperCAmelCase="[CLS]" , __UpperCAmelCase="[MASK]" , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ): '''simple docstring''' super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) __lowerCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): __lowerCamelCase = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) __lowerCamelCase = do_lower_case __lowerCamelCase = strip_accents __lowerCamelCase = tokenize_chinese_chars __lowerCamelCase = normalizer_class(**__UpperCAmelCase ) __lowerCamelCase = do_lower_case def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase=None ): '''simple docstring''' __lowerCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' __lowerCamelCase = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
330
import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Any = BioGptTokenizer lowerCamelCase_ : Optional[Any] = False def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case_ : Optional[Any] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] snake_case_ : Union[str, Any] = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) snake_case_ : Union[str, Any] = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] snake_case_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(__magic_name__ ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(__magic_name__ ) ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : str = '''lower newer''' snake_case_ : Dict = '''lower newer''' return input_text, output_text def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Optional[int] = BioGptTokenizer(self.vocab_file , self.merges_file ) snake_case_ : Union[str, Any] = '''lower''' snake_case_ : Optional[int] = ['''low''', '''er</w>'''] snake_case_ : Any = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) snake_case_ : Optional[int] = tokens + ['''<unk>'''] snake_case_ : List[str] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) @slow def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) snake_case_ : List[Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=__magic_name__ ) snake_case_ : str = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__magic_name__ ) snake_case_ : str = tokenizer.build_inputs_with_special_tokens(__magic_name__ ) snake_case_ : List[str] = tokenizer.build_inputs_with_special_tokens(__magic_name__ , __magic_name__ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
279
0
'''simple docstring''' import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class a ( _a ): _lowerCAmelCase = 42 _lowerCAmelCase = None def _A (lowerCAmelCase__ :List[Any] , lowerCAmelCase__ :Optional[int]=0.9_9_9 , lowerCAmelCase__ :List[str]="cosine" , ) -> Optional[int]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(lowerCAmelCase__ :Dict ): return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(lowerCAmelCase__ :int ): return math.exp(t * -1_2.0 ) else: raise ValueError(f'Unsupported alpha_tranform_type: {alpha_transform_type}' ) _a = [] for i in range(_UpperCamelCase ): _a = i / num_diffusion_timesteps _a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_UpperCamelCase ) / alpha_bar_fn(_UpperCamelCase ) , _UpperCamelCase ) ) return torch.tensor(_UpperCamelCase , dtype=torch.floataa ) class a ( _a , _a ): @register_to_config def __init__( self , __magic_name__ = 10_00 , __magic_name__ = "fixed_small_log" , __magic_name__ = True , __magic_name__ = 1.0 , __magic_name__ = "epsilon" , __magic_name__ = "squaredcos_cap_v2" , ) -> str: if beta_schedule != "squaredcos_cap_v2": raise ValueError('UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'' ) _a = betas_for_alpha_bar(__magic_name__ ) _a = 1.0 - self.betas _a = torch.cumprod(self.alphas , dim=0 ) _a = torch.tensor(1.0 ) # standard deviation of the initial noise distribution _a = 1.0 # setable values _a = None _a = torch.from_numpy(np.arange(0 , __magic_name__ )[::-1].copy() ) _a = variance_type def __UpperCAmelCase ( self , __magic_name__ , __magic_name__ = None ) -> torch.FloatTensor: return sample def __UpperCAmelCase ( self , __magic_name__ , __magic_name__ = None ) -> str: _a = num_inference_steps _a = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) _a = (np.arange(0 , __magic_name__ ) * step_ratio).round()[::-1].copy().astype(np.intaa ) _a = torch.from_numpy(__magic_name__ ).to(__magic_name__ ) def __UpperCAmelCase ( self , __magic_name__ , __magic_name__=None , __magic_name__=None , __magic_name__=None ) -> Optional[Any]: if prev_timestep is None: _a = t - 1 _a = self.alphas_cumprod[t] _a = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one _a = 1 - alpha_prod_t _a = 1 - alpha_prod_t_prev if prev_timestep == t - 1: _a = self.betas[t] else: _a = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _a = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: _a = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": _a = torch.log(torch.clamp(__magic_name__ , min=1e-20 ) ) _a = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler _a = variance.log() _a = beta.log() _a = (predicted_variance + 1) / 2 _a = frac * max_log + (1 - frac) * min_log return variance def __UpperCAmelCase ( self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=None , __magic_name__ = True , ) -> Union[UnCLIPSchedulerOutput, Tuple]: _a = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": _a = torch.split(__magic_name__ , sample.shape[1] , dim=1 ) else: _a = None # 1. compute alphas, betas if prev_timestep is None: _a = t - 1 _a = self.alphas_cumprod[t] _a = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one _a = 1 - alpha_prod_t _a = 1 - alpha_prod_t_prev if prev_timestep == t - 1: _a = self.betas[t] _a = self.alphas[t] else: _a = 1 - alpha_prod_t / alpha_prod_t_prev _a = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _a = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _a = model_output else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`' ' for the UnCLIPScheduler.' ) # 3. Clip "predicted x_0" if self.config.clip_sample: _a = torch.clamp( __magic_name__ , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _a = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t _a = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _a = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _a = 0 if t > 0: _a = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=__magic_name__ , device=model_output.device ) _a = self._get_variance( __magic_name__ , predicted_variance=__magic_name__ , prev_timestep=__magic_name__ , ) if self.variance_type == "fixed_small_log": _a = variance elif self.variance_type == "learned_range": _a = (0.5 * variance).exp() else: raise ValueError( f'variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`' ' for the UnCLIPScheduler.' ) _a = variance * variance_noise _a = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=__magic_name__ , pred_original_sample=__magic_name__ ) def __UpperCAmelCase ( self , __magic_name__ , __magic_name__ , __magic_name__ , ) -> torch.FloatTensor: _a = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) _a = timesteps.to(original_samples.device ) _a = alphas_cumprod[timesteps] ** 0.5 _a = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): _a = sqrt_alpha_prod.unsqueeze(-1 ) _a = (1 - alphas_cumprod[timesteps]) ** 0.5 _a = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): _a = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) _a = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
168
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> tuple[float, list[float]]: """simple docstring""" snake_case_ : Dict = list(range(len(_UpperCamelCase ) ) ) snake_case_ : Dict = [v / w for v, w in zip(_UpperCamelCase , _UpperCamelCase )] index.sort(key=lambda _UpperCamelCase : ratio[i] , reverse=_UpperCamelCase ) snake_case_ : float = 0 snake_case_ : list[float] = [0] * len(_UpperCamelCase ) for i in index: if weight[i] <= capacity: snake_case_ : Dict = 1 max_value += value[i] capacity -= weight[i] else: snake_case_ : Union[str, Any] = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
279
0
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" __a = np.array([[1, item, train_mtch[i]] for i, item in enumerate(_UpperCamelCase )] ) __a = np.array(_UpperCamelCase ) __a = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , _UpperCamelCase ) ) , x.transpose() ) , _UpperCamelCase ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Union[str, Any] ): """simple docstring""" __a = (1, 2, 1) __a = (1, 1, 0, 7) __a = SARIMAX( _UpperCamelCase , exog=_UpperCamelCase , order=_UpperCamelCase , seasonal_order=_UpperCamelCase ) __a = model.fit(disp=_UpperCamelCase , maxiter=600 , method="""nm""" ) __a = model_fit.predict(1 , len(_UpperCamelCase ) , exog=[test_match] ) return result[0] def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" __a = SVR(kernel="""rbf""" , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(_UpperCamelCase , _UpperCamelCase ) __a = regressor.predict(_UpperCamelCase ) return y_pred[0] def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" train_user.sort() __a = np.percentile(_UpperCamelCase , 25 ) __a = np.percentile(_UpperCamelCase , 75 ) __a = qa - qa __a = qa - (iqr * 0.1) return low_lim def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" __a = 0 __a = 0 for i in list_vote: if i > actual_result: __a = not_safe + 1 else: if abs(abs(_UpperCamelCase ) - abs(_UpperCamelCase ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) lowerCamelCase__ = [[1_8231, 0.0, 1], [2_2621, 1.0, 2], [1_5675, 0.0, 3], [2_3583, 1.0, 4]] lowerCamelCase__ = pd.DataFrame( data_input, columns=["""total_user""", """total_even""", """days"""] ) lowerCamelCase__ = Normalizer().fit_transform(data_input_df.values) # split data lowerCamelCase__ = normalize_df[:, 2].tolist() lowerCamelCase__ = normalize_df[:, 0].tolist() lowerCamelCase__ = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) lowerCamelCase__ = normalize_df[:, [1, 2]].tolist() lowerCamelCase__ = x[: len(x) - 1] lowerCamelCase__ = x[len(x) - 1 :] # for linear regression & sarimax lowerCamelCase__ = total_date[: len(total_date) - 1] lowerCamelCase__ = total_user[: len(total_user) - 1] lowerCamelCase__ = total_match[: len(total_match) - 1] lowerCamelCase__ = total_date[len(total_date) - 1 :] lowerCamelCase__ = total_user[len(total_user) - 1 :] lowerCamelCase__ = total_match[len(total_match) - 1 :] # voting system with forecasting lowerCamelCase__ = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data lowerCamelCase__ = """""" if data_safety_checker(res_vote, tst_user) else """not """ print("""Today\'s data is {not_str}safe.""")
302
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=3 , __magic_name__=18 , __magic_name__=30 , __magic_name__=400 , __magic_name__=True , __magic_name__=32 , __magic_name__=True , ) -> Dict: '''simple docstring''' snake_case_ : Tuple = parent snake_case_ : Union[str, Any] = batch_size snake_case_ : Union[str, Any] = num_channels snake_case_ : Optional[Any] = image_size snake_case_ : int = min_resolution snake_case_ : Any = max_resolution snake_case_ : Tuple = do_resize snake_case_ : str = size_divisor snake_case_ : Optional[Any] = do_rescale def lowerCamelCase (self ) -> Dict: '''simple docstring''' return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[Any] = GLPNImageProcessor if is_vision_available() else None def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : str = GLPNImageProcessingTester(self ) @property def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , '''do_resize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''size_divisor''' ) ) self.assertTrue(hasattr(__magic_name__ , '''resample''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_rescale''' ) ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
279
0
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def SCREAMING_SNAKE_CASE__ ( __a ): return (data["data"], data["target"]) def SCREAMING_SNAKE_CASE__ ( __a , __a ): snake_case_ : Dict = XGBClassifier() classifier.fit(_UpperCamelCase , _UpperCamelCase ) return classifier def SCREAMING_SNAKE_CASE__ ( ): snake_case_ : Tuple = load_iris() snake_case_ : Union[str, Any] = data_handling(_UpperCamelCase ) snake_case_ : Optional[Any] = train_test_split( _UpperCamelCase , _UpperCamelCase , test_size=0.25 ) snake_case_ : Optional[Any] = iris['''target_names'''] # Create an XGBoost Classifier from the training data snake_case_ : Any = xgboost(_UpperCamelCase , _UpperCamelCase ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , display_labels=_UpperCamelCase , cmap='Blues' , normalize='true' , ) plt.title('Normalized Confusion Matrix - IRIS Dataset' ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
327
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
279
0
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch A__: Optional[int] = random.Random() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : str=1.0 ,_UpperCAmelCase : Optional[int]=None ,_UpperCAmelCase : Dict=None ) -> List[Any]: if rng is None: _a : str =global_rng _a : Any =[] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class A__ ( unittest.TestCase ): def __init__( self :str , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Tuple=7 , SCREAMING_SNAKE_CASE :Optional[int]=4_0_0 , SCREAMING_SNAKE_CASE :Dict=2_0_0_0 , SCREAMING_SNAKE_CASE :Optional[Any]=1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=1_6_0 , SCREAMING_SNAKE_CASE :List[str]=8 , SCREAMING_SNAKE_CASE :List[Any]=0.0 , SCREAMING_SNAKE_CASE :Optional[int]=4_0_0_0 , SCREAMING_SNAKE_CASE :Optional[Any]=False , SCREAMING_SNAKE_CASE :List[Any]=True , ) -> List[str]: '''simple docstring''' _a : Tuple =parent _a : str =batch_size _a : Union[str, Any] =min_seq_length _a : Tuple =max_seq_length _a : Optional[Any] =(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _a : Optional[int] =padding_value _a : Union[str, Any] =sampling_rate _a : Optional[int] =return_attention_mask _a : str =do_normalize _a : str =feature_size _a : Optional[Any] =chunk_length _a : Union[str, Any] =hop_length def __UpperCAmelCase ( self :Tuple ) -> Optional[int]: '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=False ) -> Optional[Any]: '''simple docstring''' def _flatten(SCREAMING_SNAKE_CASE :str ): return list(itertools.chain(*SCREAMING_SNAKE_CASE ) ) if equal_length: _a : int =[floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size _a : int =[ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _a : str =[np.asarray(SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A__ ( _a , unittest.TestCase ): __UpperCamelCase : Optional[Any] = WhisperFeatureExtractor if is_speech_available() else None def __UpperCAmelCase ( self :int ) -> Optional[int]: '''simple docstring''' _a : List[str] =WhisperFeatureExtractionTester(self ) def __UpperCAmelCase ( self :int ) -> List[str]: '''simple docstring''' _a : str =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Union[str, Any] =feat_extract_first.save_pretrained(SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(SCREAMING_SNAKE_CASE ) _a : List[Any] =self.feature_extraction_class.from_pretrained(SCREAMING_SNAKE_CASE ) _a : Optional[int] =feat_extract_first.to_dict() _a : Dict =feat_extract_second.to_dict() _a : List[str] =feat_extract_first.mel_filters _a : Union[str, Any] =feat_extract_second.mel_filters self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] =os.path.join(SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(SCREAMING_SNAKE_CASE ) _a : Optional[int] =self.feature_extraction_class.from_json_file(SCREAMING_SNAKE_CASE ) _a : int =feat_extract_first.to_dict() _a : Optional[int] =feat_extract_second.to_dict() _a : Union[str, Any] =feat_extract_first.mel_filters _a : str =feat_extract_second.mel_filters self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] ) -> int: '''simple docstring''' _a : Optional[Any] =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _a : Any =[floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _a : str =[np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size _a : str =feature_extractor(SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input _a : Dict =feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features _a : Optional[int] =feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # Test batched _a : int =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features _a : Union[str, Any] =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. _a : Union[str, Any] =[floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] _a : List[str] =np.asarray(SCREAMING_SNAKE_CASE ) _a : List[Any] =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features _a : Dict =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # Test truncation required _a : Any =[floats_list((1, x) )[0] for x in range(2_0_0 , (feature_extractor.n_samples + 5_0_0) , 2_0_0 )] _a : Union[str, Any] =[np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] _a : Tuple =[x[: feature_extractor.n_samples] for x in speech_inputs] _a : Optional[Any] =[np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] _a : Any =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features _a : List[Any] =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __UpperCAmelCase ( self :Union[str, Any] ) -> int: '''simple docstring''' import torch _a : str =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _a : Union[str, Any] =np.random.rand(1_0_0 , 3_2 ).astype(np.floataa ) _a : Dict =np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _a : Optional[Any] =feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) _a : Optional[Any] =feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :List[Any] ) -> Dict: '''simple docstring''' _a : Optional[Any] =load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech _a : Optional[Any] =ds.sort("""id""" ).select(range(SCREAMING_SNAKE_CASE ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __UpperCAmelCase ( self :Any ) -> str: '''simple docstring''' _a : str =torch.tensor( [ 0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951, 0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678, 0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554, -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854 ] ) # fmt: on _a : List[Any] =self._load_datasamples(1 ) _a : Union[str, Any] =WhisperFeatureExtractor() _a : Union[str, Any] =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 8_0, 3_0_0_0) ) self.assertTrue(torch.allclose(input_features[0, 0, :3_0] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) def __UpperCAmelCase ( self :Tuple ) -> Union[str, Any]: '''simple docstring''' _a : Tuple =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _a : Optional[int] =self._load_datasamples(1 )[0] _a : List[str] =((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5 # Rescale to [0, 65535] to show issue _a : Optional[Any] =feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE ) - 1 ) < 1e-3 ) )
276
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers lowerCAmelCase_ = float('''nan''') class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : List[Any] = sys.stdout snake_case_ : int = open(__magic_name__ , '''a''' ) def __getattr__(self , __magic_name__ ) -> Dict: '''simple docstring''' return getattr(self.stdout , __magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' self.stdout.write(__magic_name__ ) # strip tqdm codes self.file.write(re.sub(R'''^.*\r''' , '''''' , __magic_name__ , 0 , re.M ) ) def lowerCamelCase_ ( _UpperCamelCase=80 , _UpperCamelCase=False ) -> str: """simple docstring""" snake_case_ : str = [] # deal with critical env vars snake_case_ : int = ['''CUDA_VISIBLE_DEVICES'''] for key in env_keys: snake_case_ : Optional[int] = os.environ.get(_UpperCamelCase , _UpperCamelCase ) if val is not None: cmd.append(f'''{key}={val}''' ) # python executable (not always needed if the script is executable) snake_case_ : Optional[int] = sys.executable if full_python_path else sys.executable.split('''/''' )[-1] cmd.append(_UpperCamelCase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes snake_case_ : Dict = [] snake_case_ : Dict = '''''' while len(_UpperCamelCase ) > 0: current_line += f'''{cmd.pop(0 )} ''' if len(_UpperCamelCase ) == 0 or len(_UpperCamelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(_UpperCamelCase ) snake_case_ : List[Any] = '''''' return "\\\n".join(_UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" snake_case_ : str = re.sub(R'''[\\\n]+''' , ''' ''' , args.base_cmd ) # remove --output_dir if any and set our own snake_case_ : Optional[Any] = re.sub('''--output_dir\s+[^\s]+''' , '''''' , args.base_cmd ) args.base_cmd += f''' --output_dir {output_dir}''' # ensure we have --overwrite_output_dir snake_case_ : int = re.sub('''--overwrite_output_dir\s+''' , '''''' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6_666, 222.22_222_222] )} , ) snake_case_ : Tuple = subprocess.run(_UpperCamelCase , capture_output=_UpperCamelCase , text=_UpperCamelCase ) if verbose: print('''STDOUT''' , result.stdout ) print('''STDERR''' , result.stderr ) # save the streams snake_case_ : Any = variation.replace(''' ''' , '''-''' ) with open(Path(_UpperCamelCase ) / f'''log.{prefix}.stdout.txt''' , '''w''' ) as f: f.write(result.stdout ) with open(Path(_UpperCamelCase ) / f'''log.{prefix}.stderr.txt''' , '''w''' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('''failed''' ) return {target_metric_key: nan} with io.open(f'''{output_dir}/all_results.json''' , '''r''' , encoding='''utf-8''' ) as f: snake_case_ : str = json.load(_UpperCamelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) -> Tuple: """simple docstring""" snake_case_ : Tuple = [] snake_case_ : Any = [] snake_case_ : int = f'''{id}: {variation:<{longest_variation_len}}''' snake_case_ : Optional[Any] = f'''{preamble}: ''' snake_case_ : Optional[int] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(_UpperCamelCase ) , desc=_UpperCamelCase , leave=_UpperCamelCase ): snake_case_ : int = process_run_single( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) snake_case_ : List[str] = single_run_metrics[target_metric_key] if not math.isnan(_UpperCamelCase ): metrics.append(_UpperCamelCase ) results.append(_UpperCamelCase ) outcome += "✓" else: outcome += "✘" snake_case_ : Any = f'''\33[2K\r{outcome}''' if len(_UpperCamelCase ) > 0: snake_case_ : List[Any] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} snake_case_ : Any = round(mean_metrics[target_metric_key] , 2 ) snake_case_ : List[str] = f'''{outcome} {mean_target}''' if len(_UpperCamelCase ) > 1: results_str += f''' {tuple(round(_UpperCamelCase , 2 ) for x in results )}''' print(_UpperCamelCase ) snake_case_ : Optional[int] = variation return mean_metrics else: print(_UpperCamelCase ) return {variation_key: variation, target_metric_key: nan} def lowerCamelCase_ ( ) -> Optional[int]: """simple docstring""" snake_case_ : Any = torch.cuda.get_device_properties(torch.device('''cuda''' ) ) return f''' Datetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB ''' def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : str = pd.DataFrame(_UpperCamelCase ) snake_case_ : Optional[int] = '''variation''' snake_case_ : Union[str, Any] = '''diff_%''' snake_case_ : Optional[int] = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan snake_case_ : Optional[Any] = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(_UpperCamelCase ): # as a fallback, use the minimal value as the sentinel snake_case_ : Any = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(_UpperCamelCase ): snake_case_ : Dict = df.apply( lambda _UpperCamelCase : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='''columns''' , ) # re-order columns snake_case_ : Dict = [variation_key, target_metric_key, diff_key, *report_metric_keys] snake_case_ : int = df.reindex(_UpperCamelCase , axis='''columns''' ) # reorder cols # capitalize snake_case_ : Optional[int] = df.rename(str.capitalize , axis='''columns''' ) # make the cols as narrow as possible snake_case_ : Any = df.rename(lambda _UpperCamelCase : c.replace('''_''' , '''<br>''' ) , axis='''columns''' ) snake_case_ : int = df.rename(lambda _UpperCamelCase : c.replace('''_''' , '''\n''' ) , axis='''columns''' ) snake_case_ : Tuple = ['''''', '''Copy between the cut-here-lines and paste as is to github or a forum'''] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=_UpperCamelCase , floatfmt='''.2f''' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=_UpperCamelCase , floatfmt='''.2f''' )] print('''\n\n'''.join(_UpperCamelCase ) ) def lowerCamelCase_ ( ) -> Any: """simple docstring""" snake_case_ : Any = argparse.ArgumentParser() parser.add_argument( '''--base-cmd''' , default=_UpperCamelCase , type=_UpperCamelCase , required=_UpperCamelCase , help='''Base cmd''' , ) parser.add_argument( '''--variations''' , default=_UpperCamelCase , type=_UpperCamelCase , nargs='''+''' , required=_UpperCamelCase , help='''Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'''' , ) parser.add_argument( '''--base-variation''' , default=_UpperCamelCase , type=_UpperCamelCase , help='''Baseline variation to compare to. if None the minimal target value will be used to compare against''' , ) parser.add_argument( '''--target-metric-key''' , default=_UpperCamelCase , type=_UpperCamelCase , required=_UpperCamelCase , help='''Target metric key in output_dir/all_results.json, e.g., train_samples_per_second''' , ) parser.add_argument( '''--report-metric-keys''' , default='''''' , type=_UpperCamelCase , help='''Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples''' , ) parser.add_argument( '''--repeat-times''' , default=1 , type=_UpperCamelCase , help='''How many times to re-run each variation - an average will be reported''' , ) parser.add_argument( '''--output_dir''' , default='''output_benchmark''' , type=_UpperCamelCase , help='''The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked''' , ) parser.add_argument( '''--verbose''' , default=_UpperCamelCase , action='''store_true''' , help='''Whether to show the outputs of each run or just the benchmark progress''' , ) snake_case_ : Tuple = parser.parse_args() snake_case_ : Optional[Any] = args.output_dir Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) snake_case_ : Optional[int] = get_base_command(_UpperCamelCase , _UpperCamelCase ) # split each dimension into its --foo variations snake_case_ : Optional[int] = [list(map(str.strip , re.split(R'''\|''' , _UpperCamelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty snake_case_ : List[str] = list(map(str.strip , map(''' '''.join , itertools.product(*_UpperCamelCase ) ) ) ) snake_case_ : Optional[int] = max(len(_UpperCamelCase ) for x in variations ) # split wanted keys snake_case_ : int = args.report_metric_keys.split() # capture prints into a log file for convenience snake_case_ : str = f'''benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt''' print(f'''\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt''' ) print(f'''and this script\'s output is also piped into {report_fn}''' ) snake_case_ : Tuple = Tee(_UpperCamelCase ) print(f'''\n*** Running {len(_UpperCamelCase )} benchmarks:''' ) print(f'''Base command: {" ".join(_UpperCamelCase )}''' ) snake_case_ : List[Any] = '''variation''' snake_case_ : Tuple = [] for id, variation in enumerate(tqdm(_UpperCamelCase , desc='''Total completion: ''' , leave=_UpperCamelCase ) ): snake_case_ : Optional[Any] = base_cmd + variation.split() results.append( process_run( id + 1 , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , args.target_metric_key , _UpperCamelCase , args.repeat_times , _UpperCamelCase , args.verbose , ) ) process_results(_UpperCamelCase , args.target_metric_key , _UpperCamelCase , args.base_variation , _UpperCamelCase ) if __name__ == "__main__": main()
279
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self , snake_case_ , snake_case_=7 , snake_case_=3 , snake_case_=18 , snake_case_=30 , snake_case_=400 , snake_case_=True , snake_case_=32 , snake_case_=True , ) -> Dict: __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = num_channels __lowerCAmelCase = image_size __lowerCAmelCase = min_resolution __lowerCAmelCase = max_resolution __lowerCAmelCase = do_resize __lowerCAmelCase = size_divisor __lowerCAmelCase = do_rescale def A__ ( self ) -> Dict: return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class lowerCAmelCase_ ( _a , unittest.TestCase ): '''simple docstring''' _snake_case = GLPNImageProcessor if is_vision_available() else None def A__ ( self ) -> Optional[Any]: __lowerCAmelCase = GLPNImageProcessingTester(self ) @property def A__ ( self ) -> Union[str, Any]: return self.image_processor_tester.prepare_image_processor_dict() def A__ ( self ) -> List[str]: __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case_ , """do_resize""" ) ) self.assertTrue(hasattr(snake_case_ , """size_divisor""" ) ) self.assertTrue(hasattr(snake_case_ , """resample""" ) ) self.assertTrue(hasattr(snake_case_ , """do_rescale""" ) ) def A__ ( self ) -> List[Any]: pass def A__ ( self ) -> int: __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ ) for image in image_inputs: self.assertIsInstance(snake_case_ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def A__ ( self ) -> Dict: __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , numpify=snake_case_ ) for image in image_inputs: self.assertIsInstance(snake_case_ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def A__ ( self ) -> Optional[Any]: __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , torchify=snake_case_ ) for image in image_inputs: self.assertIsInstance(snake_case_ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
301
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--txt2img_unclip''', default='''kakaobrain/karlo-v1-alpha''', type=str, required=False, help='''The pretrained txt2img unclip.''', ) lowerCAmelCase_ = parser.parse_args() lowerCAmelCase_ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) lowerCAmelCase_ = CLIPImageProcessor() lowerCAmelCase_ = CLIPVisionModelWithProjection.from_pretrained('''openai/clip-vit-large-patch14''') lowerCAmelCase_ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
279
0
'''simple docstring''' __UpperCAmelCase = { """joule""": 1.0, """kilojoule""": 1000, """megajoule""": 1000000, """gigajoule""": 1000000000, """wattsecond""": 1.0, """watthour""": 3600, """kilowatthour""": 3600000, """newtonmeter""": 1.0, """calorie_nutr""": 4186.8, """kilocalorie_nutr""": 4186800.00, """electronvolt""": 1.602176634e-19, """britishthermalunit_it""": 1055.05585, """footpound""": 1.355818, } def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: SCREAMING_SNAKE_CASE : str = ( f'''Incorrect \'from_type\' or \'to_type\' value: {from_type!r}, {to_type!r}\n''' f'''Valid values are: {", ".join(_UpperCamelCase )}''' ) raise ValueError(_UpperCamelCase ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
323
from math import factorial lowerCAmelCase_ = {str(digit): factorial(digit) for digit in range(1_0)} def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError('''Parameter number must be int''' ) if number < 0: raise ValueError('''Parameter number must be greater than or equal to 0''' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCamelCase ) ) def lowerCamelCase_ ( _UpperCamelCase = 60 , _UpperCamelCase = 1_000_000 ) -> int: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ) or not isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError('''Parameters chain_length and number_limit must be int''' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( '''Parameters chain_length and number_limit must be greater than 0''' ) # the counter for the chains with the exact desired length snake_case_ : Optional[Any] = 0 # the cached sizes of the previous chains snake_case_ : dict[int, int] = {} for start_chain_element in range(1 , _UpperCamelCase ): # The temporary set will contain the elements of the chain snake_case_ : List[str] = set() snake_case_ : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. snake_case_ : Any = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCamelCase ) chain_set_length += 1 snake_case_ : List[Any] = digit_factorial_sum(_UpperCamelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] snake_case_ : List[str] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F'''{solution()}''')
279
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) __SCREAMING_SNAKE_CASE ={ "weiweishi/roc-bert-base-zh": "https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json", } class UpperCamelCase ( _a ): lowercase = '''roc_bert''' def __init__( self ,__UpperCamelCase=3_0522 ,__UpperCamelCase=768 ,__UpperCamelCase=12 ,__UpperCamelCase=12 ,__UpperCamelCase=3072 ,__UpperCamelCase="gelu" ,__UpperCamelCase=0.1 ,__UpperCamelCase=0.1 ,__UpperCamelCase=512 ,__UpperCamelCase=2 ,__UpperCamelCase=0.02 ,__UpperCamelCase=1e-12 ,__UpperCamelCase=True ,__UpperCamelCase=0 ,__UpperCamelCase="absolute" ,__UpperCamelCase=None ,__UpperCamelCase=True ,__UpperCamelCase=True ,__UpperCamelCase=768 ,__UpperCamelCase=910 ,__UpperCamelCase=512 ,__UpperCamelCase=2_4858 ,__UpperCamelCase=True ,**__UpperCamelCase ,) -> List[str]: '''simple docstring''' lowercase_ : int = vocab_size lowercase_ : List[Any] = max_position_embeddings lowercase_ : Dict = hidden_size lowercase_ : str = num_hidden_layers lowercase_ : Optional[int] = num_attention_heads lowercase_ : Union[str, Any] = intermediate_size lowercase_ : Tuple = hidden_act lowercase_ : Tuple = hidden_dropout_prob lowercase_ : Tuple = attention_probs_dropout_prob lowercase_ : Optional[int] = initializer_range lowercase_ : int = type_vocab_size lowercase_ : Dict = layer_norm_eps lowercase_ : Union[str, Any] = use_cache lowercase_ : Optional[int] = enable_pronunciation lowercase_ : Union[str, Any] = enable_shape lowercase_ : int = pronunciation_embed_dim lowercase_ : Optional[Any] = pronunciation_vocab_size lowercase_ : Dict = shape_embed_dim lowercase_ : List[Any] = shape_vocab_size lowercase_ : Optional[int] = concat_input lowercase_ : Tuple = position_embedding_type lowercase_ : Any = classifier_dropout super().__init__(pad_token_id=__UpperCamelCase ,**__UpperCamelCase )
213
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''''' lowerCamelCase_ : str = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) lowerCamelCase_ : str = None # compression type in fsspec. ex: "gzip" lowerCamelCase_ : str = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__(self , __magic_name__ = "" , __magic_name__ = None , __magic_name__ = None , **__magic_name__ ) -> Any: '''simple docstring''' super().__init__(self , **__magic_name__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode snake_case_ : Union[str, Any] = fsspec.open( __magic_name__ , mode='''rb''' , protocol=__magic_name__ , compression=self.compression , client_kwargs={ '''requote_redirect_url''': False, # see https://github.com/huggingface/datasets/pull/5459 '''trust_env''': True, # Enable reading proxy env variables. **(target_options or {}).pop('''client_kwargs''' , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) snake_case_ : Tuple = os.path.basename(self.file.path.split('''::''' )[0] ) snake_case_ : Optional[Any] = ( self.compressed_name[: self.compressed_name.rindex('''.''' )] if '''.''' in self.compressed_name else self.compressed_name ) snake_case_ : Dict = None @classmethod def lowerCamelCase (cls , __magic_name__ ) -> Optional[int]: '''simple docstring''' return super()._strip_protocol(__magic_name__ ).lstrip('''/''' ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' if self.dir_cache is None: snake_case_ : Optional[int] = {**self.file.fs.info(self.file.path ), '''name''': self.uncompressed_name} snake_case_ : List[str] = {f['''name''']: f} def lowerCamelCase (self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' return self.file.open().read() def lowerCamelCase (self , __magic_name__ , __magic_name__ = "rb" , __magic_name__=None , __magic_name__=True , __magic_name__=None , **__magic_name__ , ) -> int: '''simple docstring''' snake_case_ : Union[str, Any] = self._strip_protocol(__magic_name__ ) if mode != "rb": raise ValueError(F'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''bz2''' lowerCamelCase_ : Any = '''bz2''' lowerCamelCase_ : int = '''.bz2''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''gzip''' lowerCamelCase_ : Dict = '''gzip''' lowerCamelCase_ : int = '''.gz''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''lz4''' lowerCamelCase_ : Any = '''lz4''' lowerCamelCase_ : Optional[Any] = '''.lz4''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''xz''' lowerCamelCase_ : Any = '''xz''' lowerCamelCase_ : int = '''.xz''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''zstd''' lowerCamelCase_ : Tuple = '''zstd''' lowerCamelCase_ : Any = '''.zst''' def __init__(self , __magic_name__ , __magic_name__ = "rb" , __magic_name__ = None , __magic_name__ = None , __magic_name__ = DEFAULT_BLOCK_SIZE , **__magic_name__ , ) -> Tuple: '''simple docstring''' super().__init__( fo=__magic_name__ , mode=__magic_name__ , target_protocol=__magic_name__ , target_options=__magic_name__ , block_size=__magic_name__ , **__magic_name__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 snake_case_ : Dict = self.file.__enter__ class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : str = file_ def __enter__(self ) -> List[Any]: '''simple docstring''' self._file.__enter__() return self def __exit__(self , *__magic_name__ , **__magic_name__ ) -> int: '''simple docstring''' self._file.__exit__(*__magic_name__ , **__magic_name__ ) def __iter__(self ) -> Optional[int]: '''simple docstring''' return iter(self._file ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return next(self._file ) def __getattr__(self , __magic_name__ ) -> str: '''simple docstring''' return getattr(self._file , __magic_name__ ) def fixed_enter(*__magic_name__ , **__magic_name__ ): return WrappedFile(_enter(*__magic_name__ , **__magic_name__ ) ) snake_case_ : Tuple = fixed_enter
279
0
def lowerCAmelCase_ ( __lowerCAmelCase )-> int: '''simple docstring''' if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError('''Input value must be a \'int\' type''' ) return bin(_UpperCamelCase ).count('''1''' ) if __name__ == "__main__": import doctest doctest.testmod()
348
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''megatron-bert''' def __init__(self , __magic_name__=2_9056 , __magic_name__=1024 , __magic_name__=24 , __magic_name__=16 , __magic_name__=4096 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=512 , __magic_name__=2 , __magic_name__=0.02 , __magic_name__=1e-12 , __magic_name__=0 , __magic_name__="absolute" , __magic_name__=True , **__magic_name__ , ) -> Any: '''simple docstring''' super().__init__(pad_token_id=__magic_name__ , **__magic_name__ ) snake_case_ : Union[str, Any] = vocab_size snake_case_ : Dict = hidden_size snake_case_ : Dict = num_hidden_layers snake_case_ : Optional[int] = num_attention_heads snake_case_ : int = hidden_act snake_case_ : List[str] = intermediate_size snake_case_ : Dict = hidden_dropout_prob snake_case_ : str = attention_probs_dropout_prob snake_case_ : str = max_position_embeddings snake_case_ : Any = type_vocab_size snake_case_ : int = initializer_range snake_case_ : int = layer_norm_eps snake_case_ : List[str] = position_embedding_type snake_case_ : Dict = use_cache
279
0
'''simple docstring''' import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def snake_case ( UpperCAmelCase="" )-> str: """simple docstring""" __A = tempfile.mkdtemp() return os.path.join(_UpperCamelCase , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class UpperCamelCase__ ( unittest.TestCase): def lowercase_ ( self :List[Any] ) -> List[str]: '''simple docstring''' __A = torch.rand(12 , dtype=torch.floataa ) - 0.5 __A = AgentAudio(_A ) __A = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(_A , agent_type.to_raw() , atol=1E-4 ) ) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(_A ) ) # Ensure that the file contains the same value as the original tensor __A = sf.read(_A ) self.assertTrue(torch.allclose(_A , torch.tensor(_A ) , atol=1E-4 ) ) def lowercase_ ( self :Any ) -> Any: '''simple docstring''' __A = torch.rand(12 , dtype=torch.floataa ) - 0.5 __A = get_new_path(suffix='.wav' ) sf.write(_A , _A , 16_000 ) __A = AgentAudio(_A ) self.assertTrue(torch.allclose(_A , agent_type.to_raw() , atol=1E-4 ) ) self.assertEqual(agent_type.to_string() , _A ) @require_vision @require_torch class UpperCamelCase__ ( unittest.TestCase): def lowercase_ ( self :Tuple ) -> List[Any]: '''simple docstring''' __A = torch.randint(0 , 256 , (64, 64, 3) ) __A = AgentImage(_A ) __A = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(_A , agent_type._tensor , atol=1E-4 ) ) self.assertIsInstance(agent_type.to_raw() , Image.Image ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(_A ) ) def lowercase_ ( self :Optional[int] ) -> int: '''simple docstring''' __A = Path(get_tests_dir('fixtures/tests_samples/COCO' ) ) / '''000000039769.png''' __A = Image.open(_A ) __A = AgentImage(_A ) self.assertTrue(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(_A ) ) def lowercase_ ( self :Optional[int] ) -> List[str]: '''simple docstring''' __A = Path(get_tests_dir('fixtures/tests_samples/COCO' ) ) / '''000000039769.png''' __A = Image.open(_A ) __A = AgentImage(_A ) self.assertFalse(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(_A ) ) class UpperCamelCase__ ( unittest.TestCase): def lowercase_ ( self :str ) -> Optional[int]: '''simple docstring''' __A = '''Hey!''' __A = AgentText(_A ) self.assertEqual(_A , agent_type.to_string() ) self.assertEqual(_A , agent_type.to_raw() ) self.assertEqual(_A , _A )
161
import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch lowerCAmelCase_ = random.Random() def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase=1.0 , _UpperCamelCase=None , _UpperCamelCase=None ) -> List[Any]: """simple docstring""" if rng is None: snake_case_ : str = global_rng snake_case_ : Any = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=400 , __magic_name__=2000 , __magic_name__=10 , __magic_name__=160 , __magic_name__=8 , __magic_name__=0.0 , __magic_name__=4000 , __magic_name__=False , __magic_name__=True , ) -> List[str]: '''simple docstring''' snake_case_ : Tuple = parent snake_case_ : str = batch_size snake_case_ : Union[str, Any] = min_seq_length snake_case_ : Tuple = max_seq_length snake_case_ : Optional[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) snake_case_ : Optional[int] = padding_value snake_case_ : Union[str, Any] = sampling_rate snake_case_ : Optional[int] = return_attention_mask snake_case_ : str = do_normalize snake_case_ : str = feature_size snake_case_ : Optional[Any] = chunk_length snake_case_ : Union[str, Any] = hop_length def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def lowerCamelCase (self , __magic_name__=False , __magic_name__=False ) -> Optional[Any]: '''simple docstring''' def _flatten(__magic_name__ ): return list(itertools.chain(*__magic_name__ ) ) if equal_length: snake_case_ : int = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size snake_case_ : int = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: snake_case_ : str = [np.asarray(__magic_name__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[Any] = WhisperFeatureExtractor if is_speech_available() else None def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[str] = WhisperFeatureExtractionTester(self ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : Union[str, Any] = feat_extract_first.save_pretrained(__magic_name__ )[0] check_json_file_has_correct_format(__magic_name__ ) snake_case_ : List[Any] = self.feature_extraction_class.from_pretrained(__magic_name__ ) snake_case_ : Optional[int] = feat_extract_first.to_dict() snake_case_ : Dict = feat_extract_second.to_dict() snake_case_ : List[str] = feat_extract_first.mel_filters snake_case_ : Union[str, Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(__magic_name__ , __magic_name__ ) ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : List[Any] = os.path.join(__magic_name__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(__magic_name__ ) snake_case_ : Optional[int] = self.feature_extraction_class.from_json_file(__magic_name__ ) snake_case_ : int = feat_extract_first.to_dict() snake_case_ : Optional[int] = feat_extract_second.to_dict() snake_case_ : Union[str, Any] = feat_extract_first.mel_filters snake_case_ : str = feat_extract_second.mel_filters self.assertTrue(np.allclose(__magic_name__ , __magic_name__ ) ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 snake_case_ : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] snake_case_ : str = [np.asarray(__magic_name__ ) for speech_input in speech_inputs] # Test feature size snake_case_ : str = feature_extractor(__magic_name__ , padding='''max_length''' , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input snake_case_ : Dict = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features snake_case_ : Optional[int] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test batched snake_case_ : int = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : Union[str, Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. snake_case_ : Union[str, Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] snake_case_ : List[str] = np.asarray(__magic_name__ ) snake_case_ : List[Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : Dict = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test truncation required snake_case_ : Any = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] snake_case_ : Union[str, Any] = [np.asarray(__magic_name__ ) for speech_input in speech_inputs] snake_case_ : Tuple = [x[: feature_extractor.n_samples] for x in speech_inputs] snake_case_ : Optional[Any] = [np.asarray(__magic_name__ ) for speech_input in speech_inputs_truncated] snake_case_ : Any = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : List[Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) def lowerCamelCase (self ) -> int: '''simple docstring''' import torch snake_case_ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case_ : Union[str, Any] = np.random.rand(100 , 32 ).astype(np.floataa ) snake_case_ : Dict = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: snake_case_ : Optional[Any] = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) snake_case_ : Optional[Any] = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Optional[Any] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech snake_case_ : Optional[Any] = ds.sort('''id''' ).select(range(__magic_name__ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : str = torch.tensor( [ 0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951, 0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678, 0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554, -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854 ] ) # fmt: on snake_case_ : List[Any] = self._load_datasamples(1 ) snake_case_ : Union[str, Any] = WhisperFeatureExtractor() snake_case_ : Union[str, Any] = feature_extractor(__magic_name__ , return_tensors='''pt''' ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __magic_name__ , atol=1e-4 ) ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case_ : Optional[int] = self._load_datasamples(1 )[0] snake_case_ : List[str] = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue snake_case_ : Optional[Any] = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__magic_name__ )[0] self.assertTrue(np.all(np.mean(__magic_name__ ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(__magic_name__ ) - 1 ) < 1e-3 ) )
279
0
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder __a = '__DUMMY_TRANSFORMERS_USER__' __a = 'Dummy User' __a = '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' __a = 'https://hub-ci.huggingface.co' __a = CI_HUB_ENDPOINT + '/datasets/{repo_id}/resolve/{revision}/{path}' __a = CI_HUB_ENDPOINT + '/{repo_id}/resolve/{revision}/{filename}' __a = Path('~/.huggingface/hub_ci_token').expanduser() @pytest.fixture def a ( snake_case__: Dict ): '''simple docstring''' monkeypatch.setattr( '''huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE''' , _UpperCamelCase ) @pytest.fixture def a ( snake_case__: Union[str, Any] ): '''simple docstring''' monkeypatch.setattr('''datasets.config.HF_ENDPOINT''' , _UpperCamelCase ) monkeypatch.setattr('''datasets.config.HUB_DATASETS_URL''' , _UpperCamelCase ) @pytest.fixture def a ( snake_case__: Optional[int] ): '''simple docstring''' monkeypatch.setattr('''huggingface_hub.hf_api.HfFolder.path_token''' , _UpperCamelCase ) @pytest.fixture def a ( snake_case__: Tuple , snake_case__: Dict ): '''simple docstring''' HfFolder.save_token(_UpperCamelCase ) yield HfFolder.delete_token() @pytest.fixture(scope='''session''' ) def a ( ): '''simple docstring''' return HfApi(endpoint=_UpperCamelCase ) @pytest.fixture(scope='''session''' ) def a ( snake_case__: Dict ): '''simple docstring''' lowercase_ = HfFolder.get_token() HfFolder.save_token(_UpperCamelCase ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(_UpperCamelCase ) @pytest.fixture def a ( snake_case__: List[Any] ): '''simple docstring''' def _cleanup_repo(snake_case__: Optional[int] ): hf_api.delete_repo(_UpperCamelCase , token=_UpperCamelCase , repo_type='''dataset''' ) return _cleanup_repo @pytest.fixture def a ( snake_case__: Dict ): '''simple docstring''' @contextmanager def _temporary_repo(snake_case__: List[str] ): try: yield repo_id finally: cleanup_repo(_UpperCamelCase ) return _temporary_repo @pytest.fixture(scope='''session''' ) def a ( snake_case__: Union[str, Any] , snake_case__: Optional[Any] , snake_case__: Optional[Any] ): '''simple docstring''' lowercase_ = F'''repo_txt_data-{int(time.time() * 1_0e3 )}''' lowercase_ = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(_UpperCamelCase , token=_UpperCamelCase , repo_type='''dataset''' , private=_UpperCamelCase ) hf_api.upload_file( token=_UpperCamelCase , path_or_fileobj=str(_UpperCamelCase ) , path_in_repo='''data/text_data.txt''' , repo_id=_UpperCamelCase , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(_UpperCamelCase , token=_UpperCamelCase , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def a ( snake_case__: int , snake_case__: Tuple , snake_case__: Dict ): '''simple docstring''' return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope='''session''' ) def a ( snake_case__: Tuple , snake_case__: Union[str, Any] , snake_case__: List[Any] ): '''simple docstring''' lowercase_ = F'''repo_zipped_txt_data-{int(time.time() * 1_0e3 )}''' lowercase_ = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(_UpperCamelCase , token=_UpperCamelCase , repo_type='''dataset''' , private=_UpperCamelCase ) hf_api.upload_file( token=_UpperCamelCase , path_or_fileobj=str(_UpperCamelCase ) , path_in_repo='''data.zip''' , repo_id=_UpperCamelCase , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(_UpperCamelCase , token=_UpperCamelCase , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def a ( snake_case__: str , snake_case__: Dict , snake_case__: List[str] ): '''simple docstring''' return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope='''session''' ) def a ( snake_case__: Optional[int] , snake_case__: Dict , snake_case__: Dict ): '''simple docstring''' lowercase_ = F'''repo_zipped_img_data-{int(time.time() * 1_0e3 )}''' lowercase_ = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(_UpperCamelCase , token=_UpperCamelCase , repo_type='''dataset''' , private=_UpperCamelCase ) hf_api.upload_file( token=_UpperCamelCase , path_or_fileobj=str(_UpperCamelCase ) , path_in_repo='''data.zip''' , repo_id=_UpperCamelCase , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(_UpperCamelCase , token=_UpperCamelCase , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def a ( snake_case__: Optional[int] , snake_case__: Union[str, Any] , snake_case__: List[str] ): '''simple docstring''' return hf_private_dataset_repo_zipped_img_data_
30
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase_ = logging.getLogger(__name__) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : List[str] = argparse.ArgumentParser( description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' ) parser.add_argument( '''--dataset_name''' , type=_UpperCamelCase , default='''wikitext''' , help='''Name of the training. Explore datasets at: hf.co/datasets.''' , ) parser.add_argument( '''--dataset_config''' , type=_UpperCamelCase , default='''wikitext-103-raw-v1''' , help='''Configuration name of the dataset.''' ) parser.add_argument( '''--tokenizer_name_or_path''' , type=_UpperCamelCase , default='''sayakpaul/unigram-tokenizer-wikitext''' , help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' , ) parser.add_argument( '''--shard_size''' , type=_UpperCamelCase , default=1_000 , help='''Number of entries to go in a single shard.''' , ) parser.add_argument('''--split''' , type=_UpperCamelCase , default='''train''' , choices=['''train''', '''test''', '''validation'''] ) parser.add_argument( '''--limit''' , default=_UpperCamelCase , type=_UpperCamelCase , help='''Limit the number of shards (used for debugging).''' , ) parser.add_argument( '''--max_length''' , type=_UpperCamelCase , default=512 , help='''Maximum sequence length. For training on TPUs, it helps to have a maximum''' ''' sequence length that is a multiple of 8.''' , ) parser.add_argument( '''--output_dir''' , default='''tf-tpu''' , type=_UpperCamelCase , help='''Output directory where the TFRecord shards will be saved. If the''' ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord''' ''' shards will be directly saved to a Google Cloud Storage bucket.''' , ) snake_case_ : List[Any] = parser.parse_args() return args def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple: """simple docstring""" def fn(_UpperCamelCase ): return tokenizer(examples['''text'''] ) return fn def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : Any = [] for i in range(len(tokenized_data['''input_ids'''] ) ): snake_case_ : Any = { '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ), '''attention_mask''': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ), } snake_case_ : Optional[int] = tf.train.Features(feature=_UpperCamelCase ) snake_case_ : Optional[Any] = tf.train.Example(features=_UpperCamelCase ) snake_case_ : Optional[Any] = example.SerializeToString() records.append(_UpperCamelCase ) return records def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : int = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: snake_case_ : Union[str, Any] = min(len(_UpperCamelCase ) , args.limit ) snake_case_ : int = dataset.select(range(_UpperCamelCase ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) snake_case_ : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) snake_case_ : str = os.path.join(args.output_dir , args.split ) if not os.path.exists(_UpperCamelCase ): os.makedirs(_UpperCamelCase ) else: snake_case_ : Optional[Any] = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. snake_case_ : Optional[Any] = tokenize_function(_UpperCamelCase ) snake_case_ : List[Any] = dataset.map(_UpperCamelCase , batched=_UpperCamelCase , num_proc=4 , remove_columns=['''text'''] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(_UpperCamelCase ): # Concatenate all texts. snake_case_ : Tuple = {k: sum(examples[k] , [] ) for k in examples.keys()} snake_case_ : List[str] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 snake_case_ : int = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. snake_case_ : Union[str, Any] = { k: [t[i : i + args.max_length] for i in range(0 , _UpperCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result snake_case_ : int = dataset_tokenized.map(_UpperCamelCase , batched=_UpperCamelCase , batch_size=1_000 , num_proc=4 ) snake_case_ : str = 0 snake_case_ : Optional[Any] = 0 for shard in range(0 , len(_UpperCamelCase ) , args.shard_size ): snake_case_ : Any = grouped_dataset[shard : shard + args.shard_size] snake_case_ : str = len(dataset_snapshot['''input_ids'''] ) snake_case_ : Union[str, Any] = os.path.join(_UpperCamelCase , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) snake_case_ : Dict = get_serialized_examples(_UpperCamelCase ) with tf.io.TFRecordWriter(_UpperCamelCase ) as out_file: for i in range(len(_UpperCamelCase ) ): snake_case_ : List[str] = serialized_examples[i] out_file.write(_UpperCamelCase ) print('''Wrote file {} containing {} records'''.format(_UpperCamelCase , _UpperCamelCase ) ) shard_count += 1 total_records += records_containing with open(f'''split-{args.split}-records-count.txt''' , '''w''' ) as f: print(f'''Total {args.split} records: {total_records}''' , file=_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = parse_args() main(args)
279
0
import os import string import sys a_ = 1 << 8 a_ = { """tab""": ord("""\t"""), """newline""": ord("""\r"""), """esc""": 27, """up""": 65 + ARROW_KEY_FLAG, """down""": 66 + ARROW_KEY_FLAG, """right""": 67 + ARROW_KEY_FLAG, """left""": 68 + ARROW_KEY_FLAG, """mod_int""": 91, """undefined""": sys.maxsize, """interrupt""": 3, """insert""": 50, """delete""": 51, """pg_up""": 53, """pg_down""": 54, } a_ = KEYMAP["""up"""] a_ = KEYMAP["""left"""] if sys.platform == "win32": a_ = [] a_ = { b"""\xe0H""": KEYMAP["""up"""] - ARROW_KEY_FLAG, b"""\x00H""": KEYMAP["""up"""] - ARROW_KEY_FLAG, b"""\xe0P""": KEYMAP["""down"""] - ARROW_KEY_FLAG, b"""\x00P""": KEYMAP["""down"""] - ARROW_KEY_FLAG, b"""\xe0M""": KEYMAP["""right"""] - ARROW_KEY_FLAG, b"""\x00M""": KEYMAP["""right"""] - ARROW_KEY_FLAG, b"""\xe0K""": KEYMAP["""left"""] - ARROW_KEY_FLAG, b"""\x00K""": KEYMAP["""left"""] - ARROW_KEY_FLAG, } for i in range(10): a_ = ord(str(i)) def a__ ( ): if os.name == "nt": import msvcrt __lowerCamelCase = '''mbcs''' # Flush the keyboard buffer while msvcrt.kbhit(): msvcrt.getch() if len(_UpperCamelCase ) == 0: # Read the keystroke __lowerCamelCase = msvcrt.getch() # If it is a prefix char, get second part if ch in (b"\x00", b"\xe0"): __lowerCamelCase = ch + msvcrt.getch() # Translate actual Win chars to bullet char types try: __lowerCamelCase = chr(WIN_KEYMAP[cha] ) WIN_CH_BUFFER.append(chr(KEYMAP['''mod_int'''] ) ) WIN_CH_BUFFER.append(_UpperCamelCase ) if ord(_UpperCamelCase ) in ( KEYMAP["insert"] - 1 << 9, KEYMAP["delete"] - 1 << 9, KEYMAP["pg_up"] - 1 << 9, KEYMAP["pg_down"] - 1 << 9, ): WIN_CH_BUFFER.append(chr(1_26 ) ) __lowerCamelCase = chr(KEYMAP['''esc'''] ) except KeyError: __lowerCamelCase = cha[1] else: __lowerCamelCase = ch.decode(_UpperCamelCase ) else: __lowerCamelCase = WIN_CH_BUFFER.pop(0 ) elif os.name == "posix": import termios import tty __lowerCamelCase = sys.stdin.fileno() __lowerCamelCase = termios.tcgetattr(_UpperCamelCase ) try: tty.setraw(_UpperCamelCase ) __lowerCamelCase = sys.stdin.read(1 ) finally: termios.tcsetattr(_UpperCamelCase ,termios.TCSADRAIN ,_UpperCamelCase ) return ch def a__ ( ): __lowerCamelCase = get_raw_chars() if ord(_UpperCamelCase ) in [KEYMAP["interrupt"], KEYMAP["newline"]]: return char elif ord(_UpperCamelCase ) == KEYMAP["esc"]: __lowerCamelCase = get_raw_chars() if ord(_UpperCamelCase ) == KEYMAP["mod_int"]: __lowerCamelCase = get_raw_chars() if ord(_UpperCamelCase ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(_UpperCamelCase ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: return chr(ord(_UpperCamelCase ) + ARROW_KEY_FLAG ) else: return KEYMAP["undefined"] else: return get_raw_chars() else: if char in string.printable: return char else: return KEYMAP["undefined"]
330
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Any = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Any = hf_hub_download( repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : List[Any] = VideoClassificationPipeline(model=__magic_name__ , image_processor=__magic_name__ , top_k=2 ) snake_case_ : str = [ example_video_filepath, '''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''', ] return video_classifier, examples def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' for example in examples: snake_case_ : Union[str, Any] = video_classifier(__magic_name__ ) self.assertEqual( __magic_name__ , [ {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, ] , ) @require_torch def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Any = '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification''' snake_case_ : str = VideoMAEFeatureExtractor( size={'''shortest_edge''': 10} , crop_size={'''height''': 10, '''width''': 10} ) snake_case_ : int = pipeline( '''video-classification''' , model=__magic_name__ , feature_extractor=__magic_name__ , frame_sampling_rate=4 ) snake_case_ : List[str] = hf_hub_download(repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : Union[str, Any] = video_classifier(__magic_name__ , top_k=2 ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}] , ) snake_case_ : int = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], ] , ) @require_tf def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' pass
279
0
'''simple docstring''' import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py a_ : Tuple = "\\n@INPROCEEDINGS{Papineni02bleu:a,\n author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n booktitle = {},\n year = {2002},\n pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n author = \"Lin, Chin-Yew and\n Och, Franz Josef\",\n booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n month = \"aug 23{--}aug 27\",\n year = \"2004\",\n address = \"Geneva, Switzerland\",\n publisher = \"COLING\",\n url = \"https://www.aclweb.org/anthology/C04-1072\",\n pages = \"501--507\",\n}\n" a_ : Optional[int] = "\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine\'s output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation\'s overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU\'s output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n" a_ : Optional[int] = "\nComputes BLEU score of translated segments against one or more references.\nArgs:\n predictions: list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n max_order: Maximum n-gram order to use when computing BLEU score.\n smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n \'bleu\': bleu score,\n \'precisions\': geometric mean of n-gram precisions,\n \'brevity_penalty\': brevity penalty,\n \'length_ratio\': ratio of lengths,\n \'translation_length\': translation_length,\n \'reference_length\': reference_length\nExamples:\n\n >>> predictions = [\n ... [\"hello\", \"there\", \"general\", \"kenobi\"], # tokenized prediction of the first sample\n ... [\"foo\", \"bar\", \"foobar\"] # tokenized prediction of the second sample\n ... ]\n >>> references = [\n ... [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]], # tokenized references for the first sample (2 references)\n ... [[\"foo\", \"bar\", \"foobar\"]] # tokenized references for the second sample (1 reference)\n ... ]\n >>> bleu = datasets.load_metric(\"bleu\")\n >>> results = bleu.compute(predictions=predictions, references=references)\n >>> print(results[\"bleu\"])\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a ( datasets.Metric ): def __UpperCAmelCase ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' , id='token' ) , id='sequence' ), 'references': datasets.Sequence( datasets.Sequence(datasets.Value('string' , id='token' ) , id='sequence' ) , id='references' ), } ) , codebase_urls=['https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'] , reference_urls=[ 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ] , ) def __UpperCAmelCase ( self , __magic_name__ , __magic_name__ , __magic_name__=4 , __magic_name__=False ) -> Optional[Any]: _a = compute_bleu( reference_corpus=__magic_name__ , translation_corpus=__magic_name__ , max_order=__magic_name__ , smooth=__magic_name__ ) (_a) = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
168
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" return "\n".join( f'''{number} * {i} = {number * i}''' for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=1_0))
279
0
from numpy import exp, pi, sqrt def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Dict = 0.0 , _SCREAMING_SNAKE_CASE : str = 1.0 ): """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
302
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCAmelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" snake_case_ : List[str] = ['''layers''', '''blocks'''] for k in ignore_keys: state_dict.pop(_UpperCamelCase , _UpperCamelCase ) lowerCAmelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" snake_case_ : str = list(s_dict.keys() ) for key in keys: snake_case_ : Optional[int] = key for k, v in WHISPER_MAPPING.items(): if k in key: snake_case_ : List[str] = new_key.replace(_UpperCamelCase , _UpperCamelCase ) print(f'''{key} -> {new_key}''' ) snake_case_ : Tuple = s_dict.pop(_UpperCamelCase ) return s_dict def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" snake_case_ , snake_case_ : Dict = emb.weight.shape snake_case_ : Tuple = nn.Linear(_UpperCamelCase , _UpperCamelCase , bias=_UpperCamelCase ) snake_case_ : Any = emb.weight.data return lin_layer def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> bytes: """simple docstring""" os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase ) snake_case_ : List[Any] = os.path.basename(_UpperCamelCase ) snake_case_ : Any = url.split('''/''' )[-2] snake_case_ : str = os.path.join(_UpperCamelCase , _UpperCamelCase ) if os.path.exists(_UpperCamelCase ) and not os.path.isfile(_UpperCamelCase ): raise RuntimeError(f'''{download_target} exists and is not a regular file''' ) if os.path.isfile(_UpperCamelCase ): snake_case_ : Union[str, Any] = open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file''' ) with urllib.request.urlopen(_UpperCamelCase ) as source, open(_UpperCamelCase , '''wb''' ) as output: with tqdm( total=int(source.info().get('''Content-Length''' ) ) , ncols=80 , unit='''iB''' , unit_scale=_UpperCamelCase , unit_divisor=1_024 ) as loop: while True: snake_case_ : Dict = source.read(8_192 ) if not buffer: break output.write(_UpperCamelCase ) loop.update(len(_UpperCamelCase ) ) snake_case_ : Any = open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() != expected_shaaaa: raise RuntimeError( '''Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.''' ) return model_bytes def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" if ".pt" not in checkpoint_path: snake_case_ : str = _download(_MODELS[checkpoint_path] ) else: snake_case_ : Union[str, Any] = torch.load(_UpperCamelCase , map_location='''cpu''' ) snake_case_ : int = original_checkpoint['''dims'''] snake_case_ : List[str] = original_checkpoint['''model_state_dict'''] snake_case_ : str = state_dict['''decoder.token_embedding.weight'''] remove_ignore_keys_(_UpperCamelCase ) rename_keys(_UpperCamelCase ) snake_case_ : Optional[int] = True snake_case_ : int = state_dict['''decoder.layers.0.fc1.weight'''].shape[0] snake_case_ : List[str] = WhisperConfig( vocab_size=dimensions['''n_vocab'''] , encoder_ffn_dim=_UpperCamelCase , decoder_ffn_dim=_UpperCamelCase , num_mel_bins=dimensions['''n_mels'''] , d_model=dimensions['''n_audio_state'''] , max_target_positions=dimensions['''n_text_ctx'''] , encoder_layers=dimensions['''n_audio_layer'''] , encoder_attention_heads=dimensions['''n_audio_head'''] , decoder_layers=dimensions['''n_text_layer'''] , decoder_attention_heads=dimensions['''n_text_state'''] , max_source_positions=dimensions['''n_audio_ctx'''] , ) snake_case_ : Union[str, Any] = WhisperForConditionalGeneration(_UpperCamelCase ) snake_case_ , snake_case_ : List[Any] = model.model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) if len(_UpperCamelCase ) > 0 and not set(_UpperCamelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' f''' but all the following weights are missing {missing}''' ) if tie_embeds: snake_case_ : List[str] = make_linear_from_emb(model.model.decoder.embed_tokens ) else: snake_case_ : Any = proj_out_weights model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCAmelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
279
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( __a ): if "resnet-50" in model_name: snake_case_ : List[str] = ResNetConfig.from_pretrained('microsoft/resnet-50' ) elif "resnet-101" in model_name: snake_case_ : List[Any] = ResNetConfig.from_pretrained('microsoft/resnet-101' ) else: raise ValueError('Model name should include either resnet50 or resnet101' ) snake_case_ : Union[str, Any] = DetrConfig(use_timm_backbone=_UpperCamelCase , backbone_config=_UpperCamelCase ) # set label attributes snake_case_ : List[Any] = '''panoptic''' in model_name if is_panoptic: snake_case_ : Any = 2_50 else: snake_case_ : Any = 91 snake_case_ : Dict = '''huggingface/label-files''' snake_case_ : Any = '''coco-detection-id2label.json''' snake_case_ : Optional[Any] = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type='dataset' ) , 'r' ) ) snake_case_ : List[str] = {int(_UpperCamelCase ): v for k, v in idalabel.items()} snake_case_ : Tuple = idalabel snake_case_ : Optional[int] = {v: k for k, v in idalabel.items()} return config, is_panoptic def SCREAMING_SNAKE_CASE__ ( __a ): snake_case_ : Any = [] # stem # fmt: off rename_keys.append(('backbone.0.body.conv1.weight', 'backbone.conv_encoder.model.embedder.embedder.convolution.weight') ) rename_keys.append(('backbone.0.body.bn1.weight', 'backbone.conv_encoder.model.embedder.embedder.normalization.weight') ) rename_keys.append(('backbone.0.body.bn1.bias', 'backbone.conv_encoder.model.embedder.embedder.normalization.bias') ) rename_keys.append(('backbone.0.body.bn1.running_mean', 'backbone.conv_encoder.model.embedder.embedder.normalization.running_mean') ) rename_keys.append(('backbone.0.body.bn1.running_var', 'backbone.conv_encoder.model.embedder.embedder.normalization.running_var') ) # stages for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): # shortcut if layer_idx == 0: rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var""", ) ) # 3 convs for i in range(3 ): rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean""", ) ) rename_keys.append( ( f"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var""", f"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var""", ) ) # fmt: on for i in range(config.encoder_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( f"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", f"""encoder.layers.{i}.self_attn.out_proj.weight""", ) ) rename_keys.append( (f"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", f"""encoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.weight""", f"""encoder.layers.{i}.fc1.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear1.bias""", f"""encoder.layers.{i}.fc1.bias""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.weight""", f"""encoder.layers.{i}.fc2.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.linear2.bias""", f"""encoder.layers.{i}.fc2.bias""") ) rename_keys.append( (f"""transformer.encoder.layers.{i}.norm1.weight""", f"""encoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append( (f"""transformer.encoder.layers.{i}.norm1.bias""", f"""encoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append( (f"""transformer.encoder.layers.{i}.norm2.weight""", f"""encoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((f"""transformer.encoder.layers.{i}.norm2.bias""", f"""encoder.layers.{i}.final_layer_norm.bias""") ) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( f"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", f"""decoder.layers.{i}.self_attn.out_proj.weight""", ) ) rename_keys.append( (f"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", f"""decoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append( ( f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""", f"""decoder.layers.{i}.encoder_attn.out_proj.weight""", ) ) rename_keys.append( ( f"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""", f"""decoder.layers.{i}.encoder_attn.out_proj.bias""", ) ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.weight""", f"""decoder.layers.{i}.fc1.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear1.bias""", f"""decoder.layers.{i}.fc1.bias""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.weight""", f"""decoder.layers.{i}.fc2.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.linear2.bias""", f"""decoder.layers.{i}.fc2.bias""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm1.weight""", f"""decoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm1.bias""", f"""decoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm2.weight""", f"""decoder.layers.{i}.encoder_attn_layer_norm.weight""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm2.bias""", f"""decoder.layers.{i}.encoder_attn_layer_norm.bias""") ) rename_keys.append( (f"""transformer.decoder.layers.{i}.norm3.weight""", f"""decoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((f"""transformer.decoder.layers.{i}.norm3.bias""", f"""decoder.layers.{i}.final_layer_norm.bias""") ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ('input_proj.weight', 'input_projection.weight'), ('input_proj.bias', 'input_projection.bias'), ('query_embed.weight', 'query_position_embeddings.weight'), ('transformer.decoder.norm.weight', 'decoder.layernorm.weight'), ('transformer.decoder.norm.bias', 'decoder.layernorm.bias'), ('class_embed.weight', 'class_labels_classifier.weight'), ('class_embed.bias', 'class_labels_classifier.bias'), ('bbox_embed.layers.0.weight', 'bbox_predictor.layers.0.weight'), ('bbox_embed.layers.0.bias', 'bbox_predictor.layers.0.bias'), ('bbox_embed.layers.1.weight', 'bbox_predictor.layers.1.weight'), ('bbox_embed.layers.1.bias', 'bbox_predictor.layers.1.bias'), ('bbox_embed.layers.2.weight', 'bbox_predictor.layers.2.weight'), ('bbox_embed.layers.2.bias', 'bbox_predictor.layers.2.bias'), ] ) return rename_keys def SCREAMING_SNAKE_CASE__ ( __a , __a , __a ): snake_case_ : Optional[int] = state_dict.pop(_UpperCamelCase ) snake_case_ : List[str] = val def SCREAMING_SNAKE_CASE__ ( __a , __a=False ): snake_case_ : List[Any] = '''''' if is_panoptic: snake_case_ : Optional[int] = '''detr.''' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) snake_case_ : Optional[Any] = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight""" ) snake_case_ : Tuple = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case_ : List[str] = in_proj_weight[:2_56, :] snake_case_ : Dict = in_proj_bias[:2_56] snake_case_ : Dict = in_proj_weight[2_56:5_12, :] snake_case_ : Union[str, Any] = in_proj_bias[2_56:5_12] snake_case_ : int = in_proj_weight[-2_56:, :] snake_case_ : Tuple = in_proj_bias[-2_56:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention snake_case_ : List[str] = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight""" ) snake_case_ : Optional[Any] = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case_ : List[str] = in_proj_weight[:2_56, :] snake_case_ : str = in_proj_bias[:2_56] snake_case_ : int = in_proj_weight[2_56:5_12, :] snake_case_ : str = in_proj_bias[2_56:5_12] snake_case_ : List[str] = in_proj_weight[-2_56:, :] snake_case_ : List[str] = in_proj_bias[-2_56:] # read in weights + bias of input projection layer of cross-attention snake_case_ : str = state_dict.pop( f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight""" ) snake_case_ : Optional[int] = state_dict.pop(f"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) of cross-attention to the state dict snake_case_ : Optional[int] = in_proj_weight_cross_attn[:2_56, :] snake_case_ : List[str] = in_proj_bias_cross_attn[:2_56] snake_case_ : List[Any] = in_proj_weight_cross_attn[2_56:5_12, :] snake_case_ : Union[str, Any] = in_proj_bias_cross_attn[2_56:5_12] snake_case_ : Optional[int] = in_proj_weight_cross_attn[-2_56:, :] snake_case_ : Optional[Any] = in_proj_bias_cross_attn[-2_56:] def SCREAMING_SNAKE_CASE__ ( ): snake_case_ : str = '''http://images.cocodataset.org/val2017/000000039769.jpg''' snake_case_ : Union[str, Any] = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( __a , __a=None , __a=False ): snake_case_ : int = get_detr_config(_UpperCamelCase ) # load original model from torch hub snake_case_ : Tuple = { '''detr-resnet-50''': '''detr_resnet50''', '''detr-resnet-101''': '''detr_resnet101''', } logger.info(f"""Converting model {model_name}...""" ) snake_case_ : Optional[int] = torch.hub.load('facebookresearch/detr' , model_name_to_original_name[model_name] , pretrained=_UpperCamelCase ).eval() snake_case_ : Union[str, Any] = detr.state_dict() # rename keys for src, dest in create_rename_keys(_UpperCamelCase ): if is_panoptic: snake_case_ : List[Any] = '''detr.''' + src rename_key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # query, key and value matrices need special treatment read_in_q_k_v(_UpperCamelCase , is_panoptic=_UpperCamelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them snake_case_ : Tuple = '''detr.model.''' if is_panoptic else '''model.''' for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith('detr' ) and not key.startswith('class_labels_classifier' ) and not key.startswith('bbox_predictor' ) ): snake_case_ : List[str] = state_dict.pop(_UpperCamelCase ) snake_case_ : List[Any] = val elif "class_labels_classifier" in key or "bbox_predictor" in key: snake_case_ : int = state_dict.pop(_UpperCamelCase ) snake_case_ : List[Any] = val elif key.startswith('bbox_attention' ) or key.startswith('mask_head' ): continue else: snake_case_ : Tuple = state_dict.pop(_UpperCamelCase ) snake_case_ : Optional[int] = val else: if not key.startswith('class_labels_classifier' ) and not key.startswith('bbox_predictor' ): snake_case_ : str = state_dict.pop(_UpperCamelCase ) snake_case_ : Tuple = val # finally, create HuggingFace model and load state dict snake_case_ : List[str] = DetrForSegmentation(_UpperCamelCase ) if is_panoptic else DetrForObjectDetection(_UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) model.eval() # verify our conversion on an image snake_case_ : Optional[Any] = '''coco_panoptic''' if is_panoptic else '''coco_detection''' snake_case_ : Tuple = DetrImageProcessor(format=_UpperCamelCase ) snake_case_ : int = processor(images=prepare_img() , return_tensors='pt' ) snake_case_ : Dict = encoding['''pixel_values'''] snake_case_ : Optional[Any] = detr(_UpperCamelCase ) snake_case_ : List[str] = model(_UpperCamelCase ) assert torch.allclose(outputs.logits , original_outputs['pred_logits'] , atol=1E-3 ) assert torch.allclose(outputs.pred_boxes , original_outputs['pred_boxes'] , atol=1E-3 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs['pred_masks'] , atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) model.save_pretrained(_UpperCamelCase ) processor.save_pretrained(_UpperCamelCase ) if push_to_hub: # Upload model and image processor to the hub logger.info('Uploading PyTorch model and image processor to the hub...' ) model.push_to_hub(f"""nielsr/{model_name}""" ) processor.push_to_hub(f"""nielsr/{model_name}""" ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( """--model_name""", default="""detr-resnet-50""", type=str, choices=["""detr-resnet-50""", """detr-resnet-101"""], help="""Name of the DETR model you\'d like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) parser.add_argument("""--push_to_hub""", action="""store_true""", help="""Whether to push the model to the hub or not.""") _SCREAMING_SNAKE_CASE = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
327
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCAmelCase_ = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) lowerCAmelCase_ = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 1_4]), ('''2H 5D 3C AS 5S''', False, [1_4, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [1_4, 1_3, 1_2, 1_1, 1_0]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 2_3), ('''JH 9H TH KH QH''', 2_2), ('''JC KH JS JD JH''', 2_1), ('''KH KC 3S 3H 3D''', 2_0), ('''8C 9C 5C 3C TC''', 1_9), ('''JS QS 9H TS KH''', 1_8), ('''7C 7S KH 2H 7H''', 1_7), ('''3C KH 5D 5S KH''', 1_6), ('''QH 8H KD JH 8S''', 1_5), ('''2D 6D 9D TH 7D''', 1_4), ) def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ , snake_case_ : Any = randrange(len(_UpperCamelCase ) ), randrange(len(_UpperCamelCase ) ) snake_case_ : Any = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] snake_case_ , snake_case_ : Tuple = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def lowerCamelCase_ ( _UpperCamelCase = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(_UpperCamelCase )) @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : str = PokerHand(_UpperCamelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[Any]: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = [PokerHand(_UpperCamelCase ) for hand in SORTED_HANDS] snake_case_ : str = poker_hands.copy() shuffle(_UpperCamelCase ) snake_case_ : List[str] = chain(sorted(_UpperCamelCase ) ) for index, hand in enumerate(_UpperCamelCase ): assert hand == poker_hands[index] def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ : Union[str, Any] = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=_UpperCamelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = PokerHand('''2C 4S AS 3D 5C''' ) snake_case_ : str = True snake_case_ : Tuple = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def lowerCamelCase_ ( ) -> List[str]: """simple docstring""" snake_case_ : List[str] = 0 snake_case_ : Union[str, Any] = os.path.abspath(os.path.dirname(_UpperCamelCase ) ) snake_case_ : Dict = os.path.join(_UpperCamelCase , '''poker_hands.txt''' ) with open(_UpperCamelCase ) as file_hand: for line in file_hand: snake_case_ : Dict = line[:14].strip() snake_case_ : List[str] = line[15:].strip() snake_case_ , snake_case_ : str = PokerHand(_UpperCamelCase ), PokerHand(_UpperCamelCase ) snake_case_ : int = player.compare_with(_UpperCamelCase ) if output == "Win": answer += 1 assert answer == 376
279
0
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class A__ ( _a , _a , unittest.TestCase ): __UpperCamelCase : Any = IFInpaintingSuperResolutionPipeline __UpperCamelCase : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''} __UpperCamelCase : Tuple = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"original_image"} ) __UpperCamelCase : Any = PipelineTesterMixin.required_optional_params - {'''latents'''} def __UpperCAmelCase ( self :Union[str, Any] ) -> int: '''simple docstring''' return self._get_superresolution_dummy_components() def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Tuple=0 ) -> List[str]: '''simple docstring''' if str(SCREAMING_SNAKE_CASE ).startswith("""mps""" ): _a : Dict =torch.manual_seed(SCREAMING_SNAKE_CASE ) else: _a : List[str] =torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =floats_tensor((1, 3, 1_6, 1_6) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) _a : str =floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) _a : Tuple =floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) _a : Optional[Any] ={ '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''original_image''': original_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __UpperCAmelCase ( self :Optional[Any] ) -> List[str]: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def __UpperCAmelCase ( self :Optional[int] ) -> List[Any]: '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def __UpperCAmelCase ( self :Optional[Any] ) -> Optional[Any]: '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1e-1 ) def __UpperCAmelCase ( self :Dict ) -> Optional[Any]: '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __UpperCAmelCase ( self :int ) -> Dict: '''simple docstring''' self._test_save_load_local() def __UpperCAmelCase ( self :Tuple ) -> Union[str, Any]: '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
276
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available lowerCAmelCase_ = logging.getLogger(__name__) @dataclass class __lowerCAmelCase : lowerCamelCase_ : str lowerCamelCase_ : List[str] lowerCamelCase_ : Optional[List[str]] @dataclass class __lowerCAmelCase : lowerCamelCase_ : List[int] lowerCamelCase_ : List[int] lowerCamelCase_ : Optional[List[int]] = None lowerCamelCase_ : Optional[List[int]] = None class __lowerCAmelCase ( _a ): lowerCamelCase_ : str = '''train''' lowerCamelCase_ : List[str] = '''dev''' lowerCamelCase_ : List[Any] = '''test''' class __lowerCAmelCase : @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def lowerCamelCase (__magic_name__ ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=False , __magic_name__="[CLS]" , __magic_name__=1 , __magic_name__="[SEP]" , __magic_name__=False , __magic_name__=False , __magic_name__=0 , __magic_name__=0 , __magic_name__=-100 , __magic_name__=0 , __magic_name__=True , ) -> List[InputFeatures]: '''simple docstring''' snake_case_ : Optional[int] = {label: i for i, label in enumerate(__magic_name__ )} snake_case_ : Dict = [] for ex_index, example in enumerate(__magic_name__ ): if ex_index % 1_0000 == 0: logger.info('''Writing example %d of %d''' , __magic_name__ , len(__magic_name__ ) ) snake_case_ : List[str] = [] snake_case_ : List[str] = [] for word, label in zip(example.words , example.labels ): snake_case_ : Optional[Any] = tokenizer.tokenize(__magic_name__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(__magic_name__ ) > 0: tokens.extend(__magic_name__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__magic_name__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. snake_case_ : Union[str, Any] = tokenizer.num_special_tokens_to_add() if len(__magic_name__ ) > max_seq_length - special_tokens_count: snake_case_ : str = tokens[: (max_seq_length - special_tokens_count)] snake_case_ : Any = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] snake_case_ : Union[str, Any] = [sequence_a_segment_id] * len(__magic_name__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: snake_case_ : Union[str, Any] = [cls_token] + tokens snake_case_ : List[Any] = [pad_token_label_id] + label_ids snake_case_ : Optional[Any] = [cls_token_segment_id] + segment_ids snake_case_ : Optional[Any] = tokenizer.convert_tokens_to_ids(__magic_name__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. snake_case_ : int = [1 if mask_padding_with_zero else 0] * len(__magic_name__ ) # Zero-pad up to the sequence length. snake_case_ : Optional[int] = max_seq_length - len(__magic_name__ ) if pad_on_left: snake_case_ : Optional[Any] = ([pad_token] * padding_length) + input_ids snake_case_ : Optional[int] = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask snake_case_ : Optional[Any] = ([pad_token_segment_id] * padding_length) + segment_ids snake_case_ : Dict = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(__magic_name__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(__magic_name__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: snake_case_ : int = None features.append( InputFeatures( input_ids=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , label_ids=__magic_name__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[InputFeatures] lowerCamelCase_ : int = nn.CrossEntropyLoss().ignore_index def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=False , __magic_name__ = Split.train , ) -> Union[str, Any]: '''simple docstring''' snake_case_ : List[str] = os.path.join( __magic_name__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(__magic_name__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case_ : Dict = cached_features_file + '''.lock''' with FileLock(__magic_name__ ): if os.path.exists(__magic_name__ ) and not overwrite_cache: logger.info(F'''Loading features from cached file {cached_features_file}''' ) snake_case_ : Dict = torch.load(__magic_name__ ) else: logger.info(F'''Creating features from dataset file at {data_dir}''' ) snake_case_ : Any = token_classification_task.read_examples_from_file(__magic_name__ , __magic_name__ ) # TODO clean up all this to leverage built-in features of tokenizers snake_case_ : int = token_classification_task.convert_examples_to_features( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , __magic_name__ ) def __len__(self ) -> Optional[Any]: '''simple docstring''' return len(self.features ) def __getitem__(self , __magic_name__ ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class __lowerCAmelCase : lowerCamelCase_ : List[InputFeatures] lowerCamelCase_ : int = -100 def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=False , __magic_name__ = Split.train , ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[int] = token_classification_task.read_examples_from_file(__magic_name__ , __magic_name__ ) # TODO clean up all this to leverage built-in features of tokenizers snake_case_ : int = token_classification_task.convert_examples_to_features( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: snake_case_ : Optional[Any] = tf.data.Dataset.from_generator( __magic_name__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: snake_case_ : int = tf.data.Dataset.from_generator( __magic_name__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__(self ) -> str: '''simple docstring''' return len(self.features ) def __getitem__(self , __magic_name__ ) -> InputFeatures: '''simple docstring''' return self.features[i]
279
0
"""simple docstring""" import argparse import torch from transformers import LxmertConfig, LxmertForPreTraining, load_tf_weights_in_lxmert from transformers.utils import logging logging.set_verbosity_info() def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase = LxmertConfig.from_json_file(_UpperCamelCase ) print(f"""Building PyTorch model from configuration: {config}""" ) __lowerCAmelCase = LxmertForPreTraining(_UpperCamelCase ) # Load weights from tf checkpoint load_tf_weights_in_lxmert(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , _UpperCamelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
301
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir('''fixtures/test_sentencepiece_bpe_char.model''') @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[int] = SpeechTaTokenizer lowerCamelCase_ : int = False lowerCamelCase_ : Dict = True def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing snake_case_ : Tuple = SpeechTaTokenizer(__magic_name__ ) snake_case_ : Any = AddedToken('''<mask>''' , lstrip=__magic_name__ , rstrip=__magic_name__ ) snake_case_ : int = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Dict = '''this is a test''' snake_case_ : int = '''this is a test''' return input_text, output_text def lowerCamelCase (self , __magic_name__ , __magic_name__=False , __magic_name__=20 , __magic_name__=5 ) -> List[Any]: '''simple docstring''' snake_case_ , snake_case_ : int = self.get_input_output_texts(__magic_name__ ) snake_case_ : Optional[Any] = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) snake_case_ : Any = tokenizer.decode(__magic_name__ , clean_up_tokenization_spaces=__magic_name__ ) return text, ids def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[str] = '''<pad>''' snake_case_ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__magic_name__ ) , 81 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : int = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): snake_case_ : int = tokenizer.vocab_size snake_case_ : Optional[Any] = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case_ : List[Any] = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] snake_case_ : List[Any] = tokenizer.add_tokens(__magic_name__ ) snake_case_ : Dict = tokenizer.vocab_size snake_case_ : Optional[Any] = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size + len(__magic_name__ ) ) snake_case_ : Union[str, Any] = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case_ : Union[str, Any] = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} snake_case_ : List[str] = tokenizer.add_special_tokens(__magic_name__ ) snake_case_ : Dict = tokenizer.vocab_size snake_case_ : Dict = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size_a + len(__magic_name__ ) ) snake_case_ : Tuple = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> List[str]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.get_tokenizer() snake_case_ : Optional[Any] = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__magic_name__ , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case_ : List[Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) snake_case_ : List[str] = tokenizer.convert_tokens_to_ids(__magic_name__ ) # fmt: off self.assertListEqual(__magic_name__ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case_ : int = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Tuple = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off snake_case_ : List[Any] = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__magic_name__ , )
279
0
'''simple docstring''' from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = HfArgumentParser(_UpperCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args_into_dataclasses()[0] SCREAMING_SNAKE_CASE : int = TensorFlowBenchmark(args=_UpperCamelCase ) try: SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args_into_dataclasses()[0] except ValueError as e: SCREAMING_SNAKE_CASE : int = '''Arg --no_{0} is no longer used, please use --no-{0} instead.''' SCREAMING_SNAKE_CASE : Any = ''' '''.join(str(_UpperCamelCase ).split(""" """ )[:-1] ) SCREAMING_SNAKE_CASE : Union[str, Any] = '''''' SCREAMING_SNAKE_CASE : Any = eval(str(_UpperCamelCase ).split(""" """ )[-1] ) SCREAMING_SNAKE_CASE : Optional[Any] = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(_UpperCamelCase ) if len(_UpperCamelCase ) > 0: SCREAMING_SNAKE_CASE : List[str] = full_error_msg + begin_error_msg + str(_UpperCamelCase ) raise ValueError(_UpperCamelCase ) benchmark.run() if __name__ == "__main__": main()
323
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' ) for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): if dist[i][j] != float('''inf''' ): print(int(dist[i][j] ) , end='''\t''' ) else: print('''INF''' , end='''\t''' ) print() def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : int = [[float('''inf''' ) for _ in range(_UpperCamelCase )] for _ in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): snake_case_ : Dict = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(_UpperCamelCase ): # looping through rows of graph array for i in range(_UpperCamelCase ): # looping through columns of graph array for j in range(_UpperCamelCase ): if ( dist[i][k] != float('''inf''' ) and dist[k][j] != float('''inf''' ) and dist[i][k] + dist[k][j] < dist[i][j] ): snake_case_ : List[Any] = dist[i][k] + dist[k][j] _print_dist(_UpperCamelCase , _UpperCamelCase ) return dist, v if __name__ == "__main__": lowerCAmelCase_ = int(input('''Enter number of vertices: ''')) lowerCAmelCase_ = int(input('''Enter number of edges: ''')) lowerCAmelCase_ = [[float('''inf''') for i in range(v)] for j in range(v)] for i in range(v): lowerCAmelCase_ = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print('''\nEdge ''', i + 1) lowerCAmelCase_ = int(input('''Enter source:''')) lowerCAmelCase_ = int(input('''Enter destination:''')) lowerCAmelCase_ = float(input('''Enter weight:''')) lowerCAmelCase_ = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
279
0
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class UpperCamelCase : lowercase = 42 # setable values lowercase = 42 lowercase = 42 lowercase = None @classmethod def _UpperCAmelCase ( cls ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Dict: '''simple docstring''' return cls(common=__UpperCamelCase ,init_noise_sigma=__UpperCamelCase ,timesteps=__UpperCamelCase ) @dataclass class UpperCamelCase ( _a ): lowercase = 42 class UpperCamelCase ( _a , _a ): lowercase = [e.name for e in FlaxKarrasDiffusionSchedulers] lowercase = 42 @property def _UpperCAmelCase ( self ) -> Dict: '''simple docstring''' return True @register_to_config def __init__( self ,__UpperCamelCase = 1000 ,__UpperCamelCase = 0.0001 ,__UpperCamelCase = 0.02 ,__UpperCamelCase = "linear" ,__UpperCamelCase = None ,__UpperCamelCase = "fixed_small" ,__UpperCamelCase = True ,__UpperCamelCase = "epsilon" ,__UpperCamelCase = jnp.floataa ,) -> Tuple: '''simple docstring''' lowercase_ : Union[str, Any] = dtype def _UpperCAmelCase ( self ,__UpperCamelCase = None ) -> DDPMSchedulerState: '''simple docstring''' if common is None: lowercase_ : str = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution lowercase_ : str = jnp.array(1.0 ,dtype=self.dtype ) lowercase_ : Any = jnp.arange(0 ,self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=__UpperCamelCase ,init_noise_sigma=__UpperCamelCase ,timesteps=__UpperCamelCase ,) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase = None ) -> jnp.ndarray: '''simple docstring''' return sample def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase = () ) -> DDPMSchedulerState: '''simple docstring''' lowercase_ : Dict = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 lowercase_ : int = (jnp.arange(0 ,__UpperCamelCase ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=__UpperCamelCase ,timesteps=__UpperCamelCase ,) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=None ,__UpperCamelCase=None ) -> Any: '''simple docstring''' lowercase_ : List[str] = state.common.alphas_cumprod[t] lowercase_ : Tuple = jnp.where(t > 0 ,state.common.alphas_cumprod[t - 1] ,jnp.array(1.0 ,dtype=self.dtype ) ) # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowercase_ : Tuple = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: lowercase_ : int = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": lowercase_ : List[Any] = jnp.clip(__UpperCamelCase ,a_min=1e-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": lowercase_ : Dict = jnp.log(jnp.clip(__UpperCamelCase ,a_min=1e-20 ) ) elif variance_type == "fixed_large": lowercase_ : Any = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log lowercase_ : str = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": lowercase_ : List[str] = variance lowercase_ : Any = state.common.betas[t] lowercase_ : Optional[Any] = (predicted_variance + 1) / 2 lowercase_ : Dict = frac * max_log + (1 - frac) * min_log return variance def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase = None ,__UpperCamelCase = True ,) -> Union[FlaxDDPMSchedulerOutput, Tuple]: '''simple docstring''' lowercase_ : Optional[int] = timestep if key is None: lowercase_ : List[str] = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: lowercase_ : Union[str, Any] = jnp.split(__UpperCamelCase ,sample.shape[1] ,axis=1 ) else: lowercase_ : Any = None # 1. compute alphas, betas lowercase_ : List[Any] = state.common.alphas_cumprod[t] lowercase_ : List[Any] = jnp.where(t > 0 ,state.common.alphas_cumprod[t - 1] ,jnp.array(1.0 ,dtype=self.dtype ) ) lowercase_ : Union[str, Any] = 1 - alpha_prod_t lowercase_ : Union[str, Any] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowercase_ : str = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowercase_ : List[Any] = model_output elif self.config.prediction_type == "v_prediction": lowercase_ : str = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ''' ' for the FlaxDDPMScheduler.' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowercase_ : Any = jnp.clip(__UpperCamelCase ,-1 ,1 ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Tuple = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t lowercase_ : Dict = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowercase_ : Tuple = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): lowercase_ : List[str] = jax.random.split(__UpperCamelCase ,num=1 ) lowercase_ : Tuple = jax.random.normal(__UpperCamelCase ,shape=model_output.shape ,dtype=self.dtype ) return (self._get_variance(__UpperCamelCase ,__UpperCamelCase ,predicted_variance=__UpperCamelCase ) ** 0.5) * noise lowercase_ : Tuple = jnp.where(t > 0 ,random_variance() ,jnp.zeros(model_output.shape ,dtype=self.dtype ) ) lowercase_ : int = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=__UpperCamelCase ,state=__UpperCamelCase ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,) -> jnp.ndarray: '''simple docstring''' return add_noise_common(state.common ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,) -> jnp.ndarray: '''simple docstring''' return get_velocity_common(state.common ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) def __len__( self ) -> Union[str, Any]: '''simple docstring''' return self.config.num_train_timesteps
213
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class __lowerCAmelCase : def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' return None class __lowerCAmelCase : def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' return None class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Dict = [ # (model_name, model_kwargs) ('''bert-base-cased''', {}), ('''gpt2''', {'''use_cache''': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__magic_name__ , '''tf''' , 12 , **__magic_name__ ) @require_torch @slow def lowerCamelCase (self ) -> int: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__magic_name__ , '''pt''' , 12 , **__magic_name__ ) @require_torch @slow def lowerCamelCase (self ) -> int: '''simple docstring''' from transformers import BertModel snake_case_ : str = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(__magic_name__ ) ) vocab_file.flush() snake_case_ : Optional[Any] = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: snake_case_ : str = BertModel(BertConfig(vocab_size=len(__magic_name__ ) ) ) model.save_pretrained(__magic_name__ ) self._test_export(__magic_name__ , '''pt''' , 12 , __magic_name__ ) @require_tf @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ : Tuple = self._test_export(__magic_name__ , '''tf''' , 12 , **__magic_name__ ) snake_case_ : List[str] = quantize(Path(__magic_name__ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__magic_name__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ : Any = self._test_export(__magic_name__ , '''pt''' , 12 , **__magic_name__ ) snake_case_ : Any = quantize(__magic_name__ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__magic_name__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None , **__magic_name__ ) -> Tuple: '''simple docstring''' try: # Compute path with TemporaryDirectory() as tempdir: snake_case_ : List[str] = Path(__magic_name__ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) return path except Exception as e: self.fail(__magic_name__ ) @require_torch @require_tokenizers @slow def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' from transformers import BertModel snake_case_ : Optional[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case_ : int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(__magic_name__ , __magic_name__ , '''pt''' ) @require_tf @require_tokenizers @slow def lowerCamelCase (self ) -> List[str]: '''simple docstring''' from transformers import TFBertModel snake_case_ : Any = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case_ : str = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(__magic_name__ , __magic_name__ , '''tf''' ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : Tuple = FeatureExtractionPipeline(__magic_name__ , __magic_name__ ) snake_case_ : Optional[int] = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] snake_case_ , snake_case_ , snake_case_ , snake_case_ : Optional[int] = infer_shapes(__magic_name__ , __magic_name__ ) # Assert all variables are present self.assertEqual(len(__magic_name__ ) , len(__magic_name__ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __magic_name__ ) self.assertSequenceEqual(variable_names[3:] , __magic_name__ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Tuple = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] snake_case_ : List[str] = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} snake_case_ , snake_case_ : Tuple = ensure_valid_input(FuncContiguousArgs() , __magic_name__ , __magic_name__ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__magic_name__ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__magic_name__ ) , set(__magic_name__ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__magic_name__ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) snake_case_ , snake_case_ : Dict = ensure_valid_input(FuncNonContiguousArgs() , __magic_name__ , __magic_name__ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Optional[int] = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
279
0
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL __snake_case = logging.get_logger(__name__) def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> Tuple[int, int]: '''simple docstring''' def constraint_to_multiple_of(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=0 , __lowerCAmelCase=None ): UpperCAmelCase : List[Any] =round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCAmelCase : Tuple =math.floor(val / multiple ) * multiple if x < min_val: UpperCAmelCase : Union[str, Any] =math.ceil(val / multiple ) * multiple return x UpperCAmelCase : Optional[int] =(output_size, output_size) if isinstance(_UpperCamelCase , _UpperCamelCase ) else output_size UpperCAmelCase : List[str] =get_image_size(_UpperCamelCase ) UpperCAmelCase : Dict =output_size # determine new height and width UpperCAmelCase : Any =output_height / input_height UpperCAmelCase : Any =output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCAmelCase : str =scale_width else: # fit height UpperCAmelCase : int =scale_height UpperCAmelCase : Any =constraint_to_multiple_of(scale_height * input_height , multiple=_UpperCamelCase ) UpperCAmelCase : str =constraint_to_multiple_of(scale_width * input_width , multiple=_UpperCamelCase ) return (new_height, new_width) class __snake_case ( _a ): __lowerCamelCase : Any = ['''pixel_values'''] def __init__( self , snake_case__ = True , snake_case__ = None , snake_case__ = PILImageResampling.BILINEAR , snake_case__ = False , snake_case__ = 1 , snake_case__ = True , snake_case__ = 1 / 255 , snake_case__ = True , snake_case__ = None , snake_case__ = None , **snake_case__ , ) -> None: '''simple docstring''' super().__init__(**snake_case__ ) UpperCAmelCase : List[Any] =size if size is not None else {'''height''': 384, '''width''': 384} UpperCAmelCase : List[str] =get_size_dict(snake_case__ ) UpperCAmelCase : Dict =do_resize UpperCAmelCase : Optional[int] =size UpperCAmelCase : int =keep_aspect_ratio UpperCAmelCase : Optional[Any] =ensure_multiple_of UpperCAmelCase : str =resample UpperCAmelCase : Union[str, Any] =do_rescale UpperCAmelCase : List[Any] =rescale_factor UpperCAmelCase : List[str] =do_normalize UpperCAmelCase : Optional[int] =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCAmelCase : Optional[int] =image_std if image_std is not None else IMAGENET_STANDARD_STD def UpperCAmelCase__ ( self , snake_case__ , snake_case__ , snake_case__ = False , snake_case__ = 1 , snake_case__ = PILImageResampling.BICUBIC , snake_case__ = None , **snake_case__ , ) -> np.ndarray: '''simple docstring''' UpperCAmelCase : Optional[int] =get_size_dict(snake_case__ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) UpperCAmelCase : int =get_resize_output_image_size( snake_case__ , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=snake_case__ , multiple=snake_case__ , ) return resize(snake_case__ , size=snake_case__ , resample=snake_case__ , data_format=snake_case__ , **snake_case__ ) def UpperCAmelCase__ ( self , snake_case__ , snake_case__ , snake_case__ = None , **snake_case__ , ) -> Optional[Any]: '''simple docstring''' return rescale(snake_case__ , scale=snake_case__ , data_format=snake_case__ , **snake_case__ ) def UpperCAmelCase__ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ = None , **snake_case__ , ) -> np.ndarray: '''simple docstring''' return normalize(snake_case__ , mean=snake_case__ , std=snake_case__ , data_format=snake_case__ , **snake_case__ ) def UpperCAmelCase__ ( self , snake_case__ , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = None , snake_case__ = ChannelDimension.FIRST , **snake_case__ , ) -> PIL.Image.Image: '''simple docstring''' UpperCAmelCase : Dict =do_resize if do_resize is not None else self.do_resize UpperCAmelCase : int =size if size is not None else self.size UpperCAmelCase : List[str] =get_size_dict(snake_case__ ) UpperCAmelCase : str =keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCAmelCase : Any =ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCAmelCase : int =resample if resample is not None else self.resample UpperCAmelCase : str =do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase : List[Any] =rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase : Optional[int] =do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase : List[str] =image_mean if image_mean is not None else self.image_mean UpperCAmelCase : Dict =image_std if image_std is not None else self.image_std UpperCAmelCase : int =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 or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. UpperCAmelCase : Optional[int] =[to_numpy_array(snake_case__ ) for image in images] if do_resize: UpperCAmelCase : Any =[self.resize(image=snake_case__ , size=snake_case__ , resample=snake_case__ ) for image in images] if do_rescale: UpperCAmelCase : Tuple =[self.rescale(image=snake_case__ , scale=snake_case__ ) for image in images] if do_normalize: UpperCAmelCase : Optional[int] =[self.normalize(image=snake_case__ , mean=snake_case__ , std=snake_case__ ) for image in images] UpperCAmelCase : List[str] =[to_channel_dimension_format(snake_case__ , snake_case__ ) for image in images] UpperCAmelCase : Dict ={'''pixel_values''': images} return BatchFeature(data=snake_case__ , tensor_type=snake_case__ ) def UpperCAmelCase__ ( self , snake_case__ , snake_case__ = None ) -> Any: '''simple docstring''' UpperCAmelCase : Optional[int] =outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(snake_case__ ) != len(snake_case__ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(snake_case__ ): UpperCAmelCase : List[Any] =target_sizes.numpy() UpperCAmelCase : Union[str, Any] =[] for idx in range(len(snake_case__ ) ): UpperCAmelCase : int =torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=snake_case__ ) UpperCAmelCase : Any =resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(snake_case__ ) else: UpperCAmelCase : str =logits.argmax(dim=1 ) UpperCAmelCase : int =[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
348
lowerCAmelCase_ = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.602_176_634e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.355_818, } def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: snake_case_ : str = ( f'''Incorrect \'from_type\' or \'to_type\' value: {from_type!r}, {to_type!r}\n''' f'''Valid values are: {", ".join(_UpperCamelCase )}''' ) raise ValueError(_UpperCamelCase ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
279
0
'''simple docstring''' import os from collections.abc import Iterator def snake_case ( UpperCAmelCase = "." )-> Iterator[str]: """simple docstring""" for dir_path, dir_names, filenames in os.walk(_UpperCamelCase ): __A = [d for d in dir_names if d != '''scripts''' and d[0] not in '''._'''] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(_UpperCamelCase )[1] in (".py", ".ipynb"): yield os.path.join(_UpperCamelCase , _UpperCamelCase ).lstrip('./' ) def snake_case ( UpperCAmelCase )-> List[str]: """simple docstring""" return f'{i * " "}*' if i else "\n##" def snake_case ( UpperCAmelCase , UpperCAmelCase )-> str: """simple docstring""" __A = old_path.split(os.sep ) for i, new_part in enumerate(new_path.split(os.sep ) ): if (i + 1 > len(_UpperCamelCase ) or old_parts[i] != new_part) and new_part: print(f'{md_prefix(_UpperCamelCase )} {new_part.replace("_" , " " ).title()}' ) return new_path def snake_case ( UpperCAmelCase = "." )-> None: """simple docstring""" __A = '''''' for filepath in sorted(good_file_paths(_UpperCamelCase ) ): __A = os.path.split(_UpperCamelCase ) if filepath != old_path: __A = print_path(_UpperCamelCase , _UpperCamelCase ) __A = (filepath.count(os.sep ) + 1) if filepath else 0 __A = f'{filepath}/{filename}'.replace(' ' , '%20' ) __A = os.path.splitext(filename.replace('_' , ' ' ).title() )[0] print(f'{md_prefix(_UpperCamelCase )} [{filename}]({url})' ) if __name__ == "__main__": print_directory_md(".")
161
import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets lowerCAmelCase_ = datasets.logging.get_logger(__name__) lowerCAmelCase_ = '''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } ''' lowerCAmelCase_ = '''\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project\'s README at https://github.com/google-research/bleurt#readme for more information. ''' lowerCAmelCase_ = ''' BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: \'scores\': List of scores. Examples: >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> bleurt = datasets.load_metric("bleurt") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results["scores"]]) [1.03, 1.04] ''' lowerCAmelCase_ = { '''bleurt-tiny-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip''', '''bleurt-tiny-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip''', '''bleurt-base-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip''', '''bleurt-base-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip''', '''bleurt-large-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip''', '''bleurt-large-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip''', '''BLEURT-20-D3''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip''', '''BLEURT-20-D6''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip''', '''BLEURT-20-D12''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip''', '''BLEURT-20''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip''', } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/google-research/bleurt''' , 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/bleurt'''] , reference_urls=['''https://github.com/google-research/bleurt''', '''https://arxiv.org/abs/2004.04696'''] , ) def lowerCamelCase (self , __magic_name__ ) -> List[Any]: '''simple docstring''' if self.config_name == "default": logger.warning( '''Using default BLEURT-Base checkpoint for sequence maximum length 128. ''' '''You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').''' ) snake_case_ : Dict = '''bleurt-base-128''' if self.config_name.lower() in CHECKPOINT_URLS: snake_case_ : Optional[int] = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: snake_case_ : Union[str, Any] = self.config_name.upper() else: raise KeyError( F'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}''' ) # download the model checkpoint specified by self.config_name and set up the scorer snake_case_ : Any = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) snake_case_ : Dict = score.BleurtScorer(os.path.join(__magic_name__ , __magic_name__ ) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Dict = self.scorer.score(references=__magic_name__ , candidates=__magic_name__ ) return {"scores": scores}
279
0
from __future__ import annotations from decimal import Decimal from numpy import array def a ( snake_case__: Any ): '''simple docstring''' lowercase_ = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(_UpperCamelCase ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix lowercase_ = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements lowercase_ = [[0.0, 0.0], [0.0, 0.0]] lowercase_ = matrix[1][1], matrix[0][0] lowercase_ = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(_UpperCamelCase ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(_UpperCamelCase ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule lowercase_ = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix lowercase_ = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] lowercase_ = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) lowercase_ = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) lowercase_ = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) lowercase_ = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) lowercase_ = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) lowercase_ = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) lowercase_ = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) lowercase_ = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) lowercase_ = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) lowercase_ = array(_UpperCamelCase ) for i in range(3 ): for j in range(3 ): lowercase_ = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix lowercase_ = array(_UpperCamelCase ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(_UpperCamelCase ) # Calculate the inverse of the matrix return [[float(d(_UpperCamelCase ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
30
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''): lowerCAmelCase_ = { '''linear''': PIL.Image.Resampling.BILINEAR, '''bilinear''': PIL.Image.Resampling.BILINEAR, '''bicubic''': PIL.Image.Resampling.BICUBIC, '''lanczos''': PIL.Image.Resampling.LANCZOS, '''nearest''': PIL.Image.Resampling.NEAREST, } else: lowerCAmelCase_ = { '''linear''': PIL.Image.LINEAR, '''bilinear''': PIL.Image.BILINEAR, '''bicubic''': PIL.Image.BICUBIC, '''lanczos''': PIL.Image.LANCZOS, '''nearest''': PIL.Image.NEAREST, } def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : Dict = (images / 2 + 0.5).clamp(0 , 1 ) snake_case_ : Dict = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() snake_case_ : int = numpy_to_pil(_UpperCamelCase ) return images def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" if images.ndim == 3: snake_case_ : Optional[Any] = images[None, ...] snake_case_ : Any = (images * 255).round().astype('''uint8''' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images snake_case_ : str = [Image.fromarray(image.squeeze() , mode='''L''' ) for image in images] else: snake_case_ : List[Any] = [Image.fromarray(_UpperCamelCase ) for image in images] return pil_images
279
0
class __lowerCAmelCase : def __init__( self ): '''simple docstring''' __lowerCamelCase = {} def lowerCamelCase ( self ): '''simple docstring''' print(self.vertex ) for i in self.vertex: print(__UpperCAmelCase , ''' -> ''' , ''' -> '''.join([str(__UpperCAmelCase ) for j in self.vertex[i]] ) ) def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(__UpperCAmelCase ) else: # else make a new vertex __lowerCamelCase = [to_vertex] def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(__UpperCAmelCase , __UpperCAmelCase ) def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = True print(__UpperCAmelCase , end=''' ''' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(__UpperCAmelCase , __UpperCAmelCase ) if __name__ == "__main__": a_ = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
330
import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Any = BioGptTokenizer lowerCamelCase_ : Optional[Any] = False def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case_ : Optional[Any] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] snake_case_ : Union[str, Any] = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) snake_case_ : Union[str, Any] = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] snake_case_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(__magic_name__ ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(__magic_name__ ) ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : str = '''lower newer''' snake_case_ : Dict = '''lower newer''' return input_text, output_text def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Optional[int] = BioGptTokenizer(self.vocab_file , self.merges_file ) snake_case_ : Union[str, Any] = '''lower''' snake_case_ : Optional[int] = ['''low''', '''er</w>'''] snake_case_ : Any = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) snake_case_ : Optional[int] = tokens + ['''<unk>'''] snake_case_ : List[str] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) @slow def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) snake_case_ : List[Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=__magic_name__ ) snake_case_ : str = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__magic_name__ ) snake_case_ : str = tokenizer.build_inputs_with_special_tokens(__magic_name__ ) snake_case_ : List[str] = tokenizer.build_inputs_with_special_tokens(__magic_name__ , __magic_name__ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
279
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) a_ : Union[str, Any] = { "configuration_falcon": ["FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP", "FalconConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = [ "FALCON_PRETRAINED_MODEL_ARCHIVE_LIST", "FalconForCausalLM", "FalconModel", "FalconPreTrainedModel", "FalconForSequenceClassification", "FalconForTokenClassification", "FalconForQuestionAnswering", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys a_ : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
168
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> tuple[float, list[float]]: """simple docstring""" snake_case_ : Dict = list(range(len(_UpperCamelCase ) ) ) snake_case_ : Dict = [v / w for v, w in zip(_UpperCamelCase , _UpperCamelCase )] index.sort(key=lambda _UpperCamelCase : ratio[i] , reverse=_UpperCamelCase ) snake_case_ : float = 0 snake_case_ : list[float] = [0] * len(_UpperCamelCase ) for i in index: if weight[i] <= capacity: snake_case_ : Dict = 1 max_value += value[i] capacity -= weight[i] else: snake_case_ : Union[str, Any] = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
279
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = """▁""" lowerCamelCase__ = {"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""} lowerCamelCase__ = { """vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""", }, """monolingual_vocab_file""": { """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""", }, } lowerCamelCase__ = {"""vinai/bartpho-syllable""": 1024} class SCREAMING_SNAKE_CASE ( _a ): __lowerCamelCase : Any =VOCAB_FILES_NAMES __lowerCamelCase : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : Tuple =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : Any =['''input_ids''', '''attention_mask'''] def __init__( self : Optional[int] , __lowercase : Tuple , __lowercase : Tuple , __lowercase : Union[str, Any]="<s>" , __lowercase : str="</s>" , __lowercase : Optional[int]="</s>" , __lowercase : Optional[Any]="<s>" , __lowercase : List[str]="<unk>" , __lowercase : Optional[Any]="<pad>" , __lowercase : Dict="<mask>" , __lowercase : List[Any] = None , **__lowercase : List[str] , ): '''simple docstring''' __a = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token __a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , cls_token=__lowercase , pad_token=__lowercase , mask_token=__lowercase , sp_model_kwargs=self.sp_model_kwargs , **__lowercase , ) __a = vocab_file __a = monolingual_vocab_file __a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__lowercase ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __a = {} __a = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(__lowercase ) not in self.fairseq_tokens_to_ids: __a = cnt cnt += 1 with open(__lowercase , """r""" , encoding="""utf-8""" ) as f: for line in f.readlines(): __a = line.strip().split()[0] __a = len(self.fairseq_tokens_to_ids ) if str(__lowercase ) not in self.fairseq_tokens_to_ids: __a = len(self.fairseq_tokens_to_ids ) __a = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Optional[int] ): '''simple docstring''' __a = self.__dict__.copy() __a = None __a = self.sp_model.serialized_model_proto() return state def __setstate__( self : Any , __lowercase : List[str] ): '''simple docstring''' __a = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __a = {} __a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def UpperCamelCase_ ( self : Union[str, Any] , __lowercase : Dict , __lowercase : List[str] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __a = [self.cls_token_id] __a = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self : Dict , __lowercase : Dict , __lowercase : str = None , __lowercase : str = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowercase , token_ids_a=__lowercase , already_has_special_tokens=__lowercase ) if token_ids_a is None: return [1] + ([0] * len(__lowercase )) + [1] return [1] + ([0] * len(__lowercase )) + [1, 1] + ([0] * len(__lowercase )) + [1] def UpperCamelCase_ ( self : int , __lowercase : int , __lowercase : int = None ): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase_ ( self : int ): '''simple docstring''' return len(self.fairseq_ids_to_tokens ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' __a = {self.convert_ids_to_tokens(__lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Optional[Any] ): '''simple docstring''' return self.sp_model.encode(__lowercase , out_type=__lowercase ) def UpperCamelCase_ ( self : Tuple , __lowercase : Dict ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def UpperCamelCase_ ( self : List[str] , __lowercase : Any ): '''simple docstring''' return self.fairseq_ids_to_tokens[index] def UpperCamelCase_ ( self : Optional[int] , __lowercase : int ): '''simple docstring''' __a = ''''''.join(__lowercase ).replace(__lowercase , """ """ ).strip() return out_string def UpperCamelCase_ ( self : List[str] , __lowercase : Dict , __lowercase : Union[str, Any] = None ): '''simple docstring''' if not os.path.isdir(__lowercase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return __a = os.path.join( __lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) __a = os.path.join( __lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""monolingual_vocab_file"""] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowercase ) elif not os.path.isfile(self.vocab_file ): with open(__lowercase , """wb""" ) as fi: __a = self.sp_model.serialized_model_proto() fi.write(__lowercase ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( __lowercase ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , __lowercase ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(__lowercase , """w""" , encoding="""utf-8""" ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"{str(__lowercase )} \n" ) return out_vocab_file, out_monolingual_vocab_file
302
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=3 , __magic_name__=18 , __magic_name__=30 , __magic_name__=400 , __magic_name__=True , __magic_name__=32 , __magic_name__=True , ) -> Dict: '''simple docstring''' snake_case_ : Tuple = parent snake_case_ : Union[str, Any] = batch_size snake_case_ : Union[str, Any] = num_channels snake_case_ : Optional[Any] = image_size snake_case_ : int = min_resolution snake_case_ : Any = max_resolution snake_case_ : Tuple = do_resize snake_case_ : str = size_divisor snake_case_ : Optional[Any] = do_rescale def lowerCamelCase (self ) -> Dict: '''simple docstring''' return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[Any] = GLPNImageProcessor if is_vision_available() else None def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : str = GLPNImageProcessingTester(self ) @property def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , '''do_resize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''size_divisor''' ) ) self.assertTrue(hasattr(__magic_name__ , '''resample''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_rescale''' ) ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
279
0
import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class SCREAMING_SNAKE_CASE_ : def __init__( self : Any , _A : List[Any] , _A : Any=13 , _A : Any=7 , _A : str=True , _A : str=True , _A : str=True , _A : Optional[Any]=True , _A : Union[str, Any]=99 , _A : Optional[int]=64 , _A : List[str]=32 , _A : Optional[int]=5 , _A : Optional[Any]=4 , _A : List[str]=37 , _A : Optional[int]="gelu" , _A : Optional[Any]=0.1 , _A : str=0.1 , _A : Tuple=512 , _A : Tuple=16 , _A : Any=2 , _A : Optional[Any]=0.0_2 , _A : Optional[int]=3 , _A : Optional[int]=4 , _A : Any=None , ) -> str: """simple docstring""" snake_case_ : List[str] = parent snake_case_ : Tuple = batch_size snake_case_ : str = seq_length snake_case_ : Optional[Any] = is_training snake_case_ : Optional[Any] = use_input_mask snake_case_ : Optional[int] = use_token_type_ids snake_case_ : Optional[Any] = use_labels snake_case_ : List[str] = vocab_size snake_case_ : Union[str, Any] = hidden_size snake_case_ : Tuple = embedding_size snake_case_ : Optional[int] = num_hidden_layers snake_case_ : List[str] = num_attention_heads snake_case_ : Optional[Any] = intermediate_size snake_case_ : Optional[Any] = hidden_act snake_case_ : Optional[int] = hidden_dropout_prob snake_case_ : Optional[int] = attention_probs_dropout_prob snake_case_ : str = max_position_embeddings snake_case_ : List[str] = type_vocab_size snake_case_ : int = type_sequence_label_size snake_case_ : Tuple = initializer_range snake_case_ : Tuple = num_labels snake_case_ : Tuple = num_choices snake_case_ : Tuple = scope def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" snake_case_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ : Dict = None if self.use_input_mask: snake_case_ : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ : Dict = None if self.use_token_type_ids: snake_case_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ : List[Any] = None snake_case_ : Dict = None snake_case_ : Tuple = None if self.use_labels: snake_case_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Any ) -> str: """simple docstring""" return MobileBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[str] , _A : Dict , _A : List[str] , _A : Any , _A : Tuple , _A : str , _A : Optional[Any] , _A : str ) -> Dict: """simple docstring""" snake_case_ : List[str] = MobileBertModel(config=_A ) model.to(_A ) model.eval() snake_case_ : Tuple = model(_A , attention_mask=_A , token_type_ids=_A ) snake_case_ : Optional[int] = model(_A , token_type_ids=_A ) snake_case_ : Optional[Any] = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : Optional[int] , _A : List[str] , _A : List[str] , _A : Any , _A : int , _A : Any , _A : str , _A : Optional[Any] ) -> int: """simple docstring""" snake_case_ : Any = MobileBertForMaskedLM(config=_A ) model.to(_A ) model.eval() snake_case_ : Dict = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , _A : str , _A : Union[str, Any] , _A : Optional[int] , _A : List[str] , _A : List[Any] , _A : Tuple , _A : int ) -> List[str]: """simple docstring""" snake_case_ : int = MobileBertForNextSentencePrediction(config=_A ) model.to(_A ) model.eval() snake_case_ : str = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[str] , _A : str , _A : int , _A : Any , _A : str , _A : Optional[Any] , _A : List[Any] , _A : int ) -> str: """simple docstring""" snake_case_ : Any = MobileBertForPreTraining(config=_A ) model.to(_A ) model.eval() snake_case_ : List[str] = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , next_sentence_label=_A , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : Optional[Any] , _A : Any , _A : str , _A : str , _A : Optional[int] , _A : Dict , _A : Any , _A : str ) -> List[str]: """simple docstring""" snake_case_ : Tuple = MobileBertForQuestionAnswering(config=_A ) model.to(_A ) model.eval() snake_case_ : Any = model( _A , attention_mask=_A , token_type_ids=_A , start_positions=_A , end_positions=_A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase_ ( self : Tuple , _A : List[Any] , _A : Tuple , _A : Any , _A : Dict , _A : Union[str, Any] , _A : Optional[Any] , _A : List[str] ) -> str: """simple docstring""" snake_case_ : Optional[int] = self.num_labels snake_case_ : Tuple = MobileBertForSequenceClassification(_A ) model.to(_A ) model.eval() snake_case_ : List[Any] = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Any , _A : List[str] , _A : List[str] , _A : Any , _A : int , _A : Dict , _A : Optional[Any] , _A : str ) -> Optional[Any]: """simple docstring""" snake_case_ : int = self.num_labels snake_case_ : Dict = MobileBertForTokenClassification(config=_A ) model.to(_A ) model.eval() snake_case_ : List[str] = model(_A , attention_mask=_A , token_type_ids=_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] , _A : List[str] , _A : Optional[int] , _A : str , _A : int , _A : Dict , _A : str , _A : List[Any] ) -> Any: """simple docstring""" snake_case_ : Tuple = self.num_choices snake_case_ : str = MobileBertForMultipleChoice(config=_A ) model.to(_A ) model.eval() snake_case_ : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : Tuple = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : int = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ : List[Any] = model( _A , attention_mask=_A , token_type_ids=_A , labels=_A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" snake_case_ : Optional[int] = self.prepare_config_and_inputs() ( snake_case_ ) : List[Any] = config_and_inputs snake_case_ : List[str] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE_ ( _a , _a , unittest.TestCase ): __magic_name__: int = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) __magic_name__: Union[str, Any] = ( { '''feature-extraction''': MobileBertModel, '''fill-mask''': MobileBertForMaskedLM, '''question-answering''': MobileBertForQuestionAnswering, '''text-classification''': MobileBertForSequenceClassification, '''token-classification''': MobileBertForTokenClassification, '''zero-shot''': MobileBertForSequenceClassification, } if is_torch_available() else {} ) __magic_name__: Union[str, Any] = True def UpperCAmelCase_ ( self : List[Any] , _A : str , _A : Union[str, Any] , _A : Tuple=False ) -> List[str]: """simple docstring""" snake_case_ : Dict = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class in get_values(_A ): snake_case_ : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_A ) snake_case_ : int = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_A ) return inputs_dict def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" snake_case_ : Tuple = MobileBertModelTester(self ) snake_case_ : List[str] = ConfigTester(self , config_class=_A , hidden_size=37 ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Tuple: """simple docstring""" snake_case_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*_A ) def UpperCAmelCase_ ( self : str ) -> Any: """simple docstring""" snake_case_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*_A ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict: """simple docstring""" snake_case_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*_A ) def UpperCAmelCase_ ( self : Dict ) -> str: """simple docstring""" snake_case_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*_A ) def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: """simple docstring""" snake_case_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*_A ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: """simple docstring""" snake_case_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*_A ) def UpperCAmelCase_ ( self : Dict ) -> Dict: """simple docstring""" snake_case_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*_A ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" snake_case_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*_A ) def SCREAMING_SNAKE_CASE__ ( __a ): return torch.tensor( _UpperCamelCase , dtype=torch.long , device=_UpperCamelCase , ) _SCREAMING_SNAKE_CASE = 1e-3 @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): @slow def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: """simple docstring""" snake_case_ : Optional[Any] = MobileBertModel.from_pretrained('google/mobilebert-uncased' ).to(_A ) snake_case_ : Optional[Any] = _long_tensor([[101, 7110, 1005, 1056, 2023, 11333, 17413, 1029, 102]] ) with torch.no_grad(): snake_case_ : Optional[int] = model(_A )[0] snake_case_ : Union[str, Any] = torch.Size((1, 9, 512) ) self.assertEqual(output.shape , _A ) snake_case_ : List[str] = torch.tensor( [ [ [-2.473_6526E07, 8.269_1656E04, 1.652_1838E05], [-5.754_1704E-01, 3.905_6022E00, 4.401_1507E00], [2.604_7359E00, 1.567_7652E00, -1.732_4188E-01], ] ] , device=_A , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE snake_case_ : Any = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) snake_case_ : Union[str, Any] = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
327
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
279
0
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : str ,_UpperCAmelCase : Any ,) -> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative in a semiconductor""" ) elif hole_conc < 0: raise ValueError("""Hole concentration cannot be negative in a semiconductor""" ) elif intrinsic_conc < 0: raise ValueError( """Intrinsic concentration cannot be negative in a semiconductor""" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
276
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers lowerCAmelCase_ = float('''nan''') class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : List[Any] = sys.stdout snake_case_ : int = open(__magic_name__ , '''a''' ) def __getattr__(self , __magic_name__ ) -> Dict: '''simple docstring''' return getattr(self.stdout , __magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' self.stdout.write(__magic_name__ ) # strip tqdm codes self.file.write(re.sub(R'''^.*\r''' , '''''' , __magic_name__ , 0 , re.M ) ) def lowerCamelCase_ ( _UpperCamelCase=80 , _UpperCamelCase=False ) -> str: """simple docstring""" snake_case_ : str = [] # deal with critical env vars snake_case_ : int = ['''CUDA_VISIBLE_DEVICES'''] for key in env_keys: snake_case_ : Optional[int] = os.environ.get(_UpperCamelCase , _UpperCamelCase ) if val is not None: cmd.append(f'''{key}={val}''' ) # python executable (not always needed if the script is executable) snake_case_ : Optional[int] = sys.executable if full_python_path else sys.executable.split('''/''' )[-1] cmd.append(_UpperCamelCase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes snake_case_ : Dict = [] snake_case_ : Dict = '''''' while len(_UpperCamelCase ) > 0: current_line += f'''{cmd.pop(0 )} ''' if len(_UpperCamelCase ) == 0 or len(_UpperCamelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(_UpperCamelCase ) snake_case_ : List[Any] = '''''' return "\\\n".join(_UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" snake_case_ : str = re.sub(R'''[\\\n]+''' , ''' ''' , args.base_cmd ) # remove --output_dir if any and set our own snake_case_ : Optional[Any] = re.sub('''--output_dir\s+[^\s]+''' , '''''' , args.base_cmd ) args.base_cmd += f''' --output_dir {output_dir}''' # ensure we have --overwrite_output_dir snake_case_ : int = re.sub('''--overwrite_output_dir\s+''' , '''''' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6_666, 222.22_222_222] )} , ) snake_case_ : Tuple = subprocess.run(_UpperCamelCase , capture_output=_UpperCamelCase , text=_UpperCamelCase ) if verbose: print('''STDOUT''' , result.stdout ) print('''STDERR''' , result.stderr ) # save the streams snake_case_ : Any = variation.replace(''' ''' , '''-''' ) with open(Path(_UpperCamelCase ) / f'''log.{prefix}.stdout.txt''' , '''w''' ) as f: f.write(result.stdout ) with open(Path(_UpperCamelCase ) / f'''log.{prefix}.stderr.txt''' , '''w''' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('''failed''' ) return {target_metric_key: nan} with io.open(f'''{output_dir}/all_results.json''' , '''r''' , encoding='''utf-8''' ) as f: snake_case_ : str = json.load(_UpperCamelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) -> Tuple: """simple docstring""" snake_case_ : Tuple = [] snake_case_ : Any = [] snake_case_ : int = f'''{id}: {variation:<{longest_variation_len}}''' snake_case_ : Optional[Any] = f'''{preamble}: ''' snake_case_ : Optional[int] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(_UpperCamelCase ) , desc=_UpperCamelCase , leave=_UpperCamelCase ): snake_case_ : int = process_run_single( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) snake_case_ : List[str] = single_run_metrics[target_metric_key] if not math.isnan(_UpperCamelCase ): metrics.append(_UpperCamelCase ) results.append(_UpperCamelCase ) outcome += "✓" else: outcome += "✘" snake_case_ : Any = f'''\33[2K\r{outcome}''' if len(_UpperCamelCase ) > 0: snake_case_ : List[Any] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} snake_case_ : Any = round(mean_metrics[target_metric_key] , 2 ) snake_case_ : List[str] = f'''{outcome} {mean_target}''' if len(_UpperCamelCase ) > 1: results_str += f''' {tuple(round(_UpperCamelCase , 2 ) for x in results )}''' print(_UpperCamelCase ) snake_case_ : Optional[int] = variation return mean_metrics else: print(_UpperCamelCase ) return {variation_key: variation, target_metric_key: nan} def lowerCamelCase_ ( ) -> Optional[int]: """simple docstring""" snake_case_ : Any = torch.cuda.get_device_properties(torch.device('''cuda''' ) ) return f''' Datetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB ''' def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : str = pd.DataFrame(_UpperCamelCase ) snake_case_ : Optional[int] = '''variation''' snake_case_ : Union[str, Any] = '''diff_%''' snake_case_ : Optional[int] = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan snake_case_ : Optional[Any] = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(_UpperCamelCase ): # as a fallback, use the minimal value as the sentinel snake_case_ : Any = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(_UpperCamelCase ): snake_case_ : Dict = df.apply( lambda _UpperCamelCase : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='''columns''' , ) # re-order columns snake_case_ : Dict = [variation_key, target_metric_key, diff_key, *report_metric_keys] snake_case_ : int = df.reindex(_UpperCamelCase , axis='''columns''' ) # reorder cols # capitalize snake_case_ : Optional[int] = df.rename(str.capitalize , axis='''columns''' ) # make the cols as narrow as possible snake_case_ : Any = df.rename(lambda _UpperCamelCase : c.replace('''_''' , '''<br>''' ) , axis='''columns''' ) snake_case_ : int = df.rename(lambda _UpperCamelCase : c.replace('''_''' , '''\n''' ) , axis='''columns''' ) snake_case_ : Tuple = ['''''', '''Copy between the cut-here-lines and paste as is to github or a forum'''] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=_UpperCamelCase , floatfmt='''.2f''' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=_UpperCamelCase , floatfmt='''.2f''' )] print('''\n\n'''.join(_UpperCamelCase ) ) def lowerCamelCase_ ( ) -> Any: """simple docstring""" snake_case_ : Any = argparse.ArgumentParser() parser.add_argument( '''--base-cmd''' , default=_UpperCamelCase , type=_UpperCamelCase , required=_UpperCamelCase , help='''Base cmd''' , ) parser.add_argument( '''--variations''' , default=_UpperCamelCase , type=_UpperCamelCase , nargs='''+''' , required=_UpperCamelCase , help='''Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'''' , ) parser.add_argument( '''--base-variation''' , default=_UpperCamelCase , type=_UpperCamelCase , help='''Baseline variation to compare to. if None the minimal target value will be used to compare against''' , ) parser.add_argument( '''--target-metric-key''' , default=_UpperCamelCase , type=_UpperCamelCase , required=_UpperCamelCase , help='''Target metric key in output_dir/all_results.json, e.g., train_samples_per_second''' , ) parser.add_argument( '''--report-metric-keys''' , default='''''' , type=_UpperCamelCase , help='''Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples''' , ) parser.add_argument( '''--repeat-times''' , default=1 , type=_UpperCamelCase , help='''How many times to re-run each variation - an average will be reported''' , ) parser.add_argument( '''--output_dir''' , default='''output_benchmark''' , type=_UpperCamelCase , help='''The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked''' , ) parser.add_argument( '''--verbose''' , default=_UpperCamelCase , action='''store_true''' , help='''Whether to show the outputs of each run or just the benchmark progress''' , ) snake_case_ : Tuple = parser.parse_args() snake_case_ : Optional[Any] = args.output_dir Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) snake_case_ : Optional[int] = get_base_command(_UpperCamelCase , _UpperCamelCase ) # split each dimension into its --foo variations snake_case_ : Optional[int] = [list(map(str.strip , re.split(R'''\|''' , _UpperCamelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty snake_case_ : List[str] = list(map(str.strip , map(''' '''.join , itertools.product(*_UpperCamelCase ) ) ) ) snake_case_ : Optional[int] = max(len(_UpperCamelCase ) for x in variations ) # split wanted keys snake_case_ : int = args.report_metric_keys.split() # capture prints into a log file for convenience snake_case_ : str = f'''benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt''' print(f'''\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt''' ) print(f'''and this script\'s output is also piped into {report_fn}''' ) snake_case_ : Tuple = Tee(_UpperCamelCase ) print(f'''\n*** Running {len(_UpperCamelCase )} benchmarks:''' ) print(f'''Base command: {" ".join(_UpperCamelCase )}''' ) snake_case_ : List[Any] = '''variation''' snake_case_ : Tuple = [] for id, variation in enumerate(tqdm(_UpperCamelCase , desc='''Total completion: ''' , leave=_UpperCamelCase ) ): snake_case_ : Optional[Any] = base_cmd + variation.split() results.append( process_run( id + 1 , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , args.target_metric_key , _UpperCamelCase , args.repeat_times , _UpperCamelCase , args.verbose , ) ) process_results(_UpperCamelCase , args.target_metric_key , _UpperCamelCase , args.base_variation , _UpperCamelCase ) if __name__ == "__main__": main()
279
0
"""simple docstring""" import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand SCREAMING_SNAKE_CASE_ = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) SCREAMING_SNAKE_CASE_ = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) SCREAMING_SNAKE_CASE_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) SCREAMING_SNAKE_CASE_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) SCREAMING_SNAKE_CASE_ = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 14]), ('''2H 5D 3C AS 5S''', False, [14, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [14, 13, 12, 11, 10]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) SCREAMING_SNAKE_CASE_ = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) SCREAMING_SNAKE_CASE_ = ( ('''JH AH TH KH QH''', 23), ('''JH 9H TH KH QH''', 22), ('''JC KH JS JD JH''', 21), ('''KH KC 3S 3H 3D''', 20), ('''8C 9C 5C 3C TC''', 19), ('''JS QS 9H TS KH''', 18), ('''7C 7S KH 2H 7H''', 17), ('''3C KH 5D 5S KH''', 16), ('''QH 8H KD JH 8S''', 15), ('''2D 6D 9D TH 7D''', 14), ) def lowercase (): __lowerCAmelCase = randrange(len(_UpperCamelCase ) ), randrange(len(_UpperCamelCase ) ) __lowerCAmelCase = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] __lowerCAmelCase = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def lowercase (_lowerCAmelCase = 100 ): return (generate_random_hand() for _ in range(_UpperCamelCase )) @pytest.mark.parametrize("""hand, expected""" , _UpperCamelCase ) def lowercase (_lowerCAmelCase , _lowerCAmelCase ): assert PokerHand(_UpperCamelCase )._is_flush() == expected @pytest.mark.parametrize("""hand, expected""" , _UpperCamelCase ) def lowercase (_lowerCAmelCase , _lowerCAmelCase ): assert PokerHand(_UpperCamelCase )._is_straight() == expected @pytest.mark.parametrize("""hand, expected, card_values""" , _UpperCamelCase ) def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): __lowerCAmelCase = PokerHand(_UpperCamelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("""hand, expected""" , _UpperCamelCase ) def lowercase (_lowerCAmelCase , _lowerCAmelCase ): assert PokerHand(_UpperCamelCase )._is_same_kind() == expected @pytest.mark.parametrize("""hand, expected""" , _UpperCamelCase ) def lowercase (_lowerCAmelCase , _lowerCAmelCase ): assert PokerHand(_UpperCamelCase )._hand_type == expected @pytest.mark.parametrize("""hand, other, expected""" , _UpperCamelCase ) def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected @pytest.mark.parametrize("""hand, other, expected""" , generate_random_hands() ) def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected def lowercase (): __lowerCAmelCase = [PokerHand(_UpperCamelCase ) for hand in SORTED_HANDS] __lowerCAmelCase = poker_hands.copy() shuffle(_UpperCamelCase ) __lowerCAmelCase = chain(sorted(_UpperCamelCase ) ) for index, hand in enumerate(_UpperCamelCase ): assert hand == poker_hands[index] def lowercase (): __lowerCAmelCase = [PokerHand("""2D AC 3H 4H 5S""" ), PokerHand("""2S 3H 4H 5S 6C""" )] pokerhands.sort(reverse=_UpperCamelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def lowercase (): __lowerCAmelCase = PokerHand("""2C 4S AS 3D 5C""" ) __lowerCAmelCase = True __lowerCAmelCase = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def lowercase (): __lowerCAmelCase = 0 __lowerCAmelCase = os.path.abspath(os.path.dirname(_UpperCamelCase ) ) __lowerCAmelCase = os.path.join(_UpperCamelCase , """poker_hands.txt""" ) with open(_UpperCamelCase ) as file_hand: for line in file_hand: __lowerCAmelCase = line[:14].strip() __lowerCAmelCase = line[15:].strip() __lowerCAmelCase = PokerHand(_UpperCamelCase ), PokerHand(_UpperCamelCase ) __lowerCAmelCase = player.compare_with(_UpperCamelCase ) if output == "Win": answer += 1 assert answer == 376
301
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--txt2img_unclip''', default='''kakaobrain/karlo-v1-alpha''', type=str, required=False, help='''The pretrained txt2img unclip.''', ) lowerCAmelCase_ = parser.parse_args() lowerCAmelCase_ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) lowerCAmelCase_ = CLIPImageProcessor() lowerCAmelCase_ = CLIPVisionModelWithProjection.from_pretrained('''openai/clip-vit-large-patch14''') lowerCAmelCase_ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
279
0
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black __UpperCAmelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. __UpperCAmelCase = """ def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states """ class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , """models/bert/""" ) ) SCREAMING_SNAKE_CASE : Any = self.transformer_dir shutil.copy( os.path.join(lowerCamelCase_ , """src/transformers/models/bert/modeling_bert.py""" ) , os.path.join(self.transformer_dir , """models/bert/modeling_bert.py""" ) , ) def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = '''src/transformers''' shutil.rmtree(self.transformer_dir ) def lowerCamelCase_ ( self : Tuple , lowerCamelCase_ : int , lowerCamelCase_ : List[Any] , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Optional[int]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = comment + f'''\nclass {class_name}(nn.Module):\n''' + class_code if overwrite_result is not None: SCREAMING_SNAKE_CASE : List[Any] = comment + f'''\nclass {class_name}(nn.Module):\n''' + overwrite_result SCREAMING_SNAKE_CASE : List[str] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 ) SCREAMING_SNAKE_CASE : Tuple = black.format_str(lowerCamelCase_ , mode=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.transformer_dir , """new_code.py""" ) with open(lowerCamelCase_ , """w""" , newline="""\n""" ) as f: f.write(lowerCamelCase_ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(lowerCamelCase_ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=lowerCamelCase_ ) with open(lowerCamelCase_ , """r""" ) as f: self.assertTrue(f.read() , lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead""" ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , lowerCamelCase_ , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , re.sub("""Bert""" , """TestModel""" , lowerCamelCase_ ) , ) # Copy consistency with a really long name SCREAMING_SNAKE_CASE : Union[str, Any] = '''TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason''' self.check_copy_consistency( f'''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}''' , f'''{long_class_name}LMPredictionHead''' , re.sub("""Bert""" , lowerCamelCase_ , lowerCamelCase_ ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , lowerCamelCase_ , overwrite_result=re.sub("""Bert""" , """TestModel""" , lowerCamelCase_ ) , ) def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = check_copies.LOCALIZED_READMES['''README_zh-hans.md'''] SCREAMING_SNAKE_CASE : Dict = ( '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the''' ''' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for''' ''' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong''' ''' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.''' ''' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),''' ''' released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and''' ''' lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same''' ''' method has been applied to compress GPT2 into''' ''' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into''' ''' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),''' ''' Multilingual BERT into''' ''' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German''' ''' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**''' ''' (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders''' ''' as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang''' ''' Luong, Quoc V. Le, Christopher D. Manning.''' ) SCREAMING_SNAKE_CASE : Optional[Any] = ( '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the''' ''' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of''' ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian''' ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n''' ) SCREAMING_SNAKE_CASE : int = ( '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the''' ''' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of''' ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian''' ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.''' ''' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文''' ''' [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and''' ''' lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same''' ''' method has been applied to compress GPT2 into''' ''' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into''' ''' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),''' ''' Multilingual BERT into''' ''' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German''' ''' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自''' ''' Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather''' ''' than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,''' ''' Christopher D. Manning 发布。\n''' ) SCREAMING_SNAKE_CASE : str = check_copies.convert_to_localized_md( lowerCamelCase_ , lowerCamelCase_ , localized_readme["""format_model_list"""] ) self.assertFalse(lowerCamelCase_ ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = check_copies.convert_to_localized_md( lowerCamelCase_ , lowerCamelCase_ , localized_readme["""format_model_list"""] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = ( '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the''' ''' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for''' ''' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong''' ''' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.''' ) SCREAMING_SNAKE_CASE : Optional[int] = ( '''1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and''' ''' the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of''' ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian''' ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = ( '''1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the''' ''' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of''' ''' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian''' ''' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n''' ) SCREAMING_SNAKE_CASE : Tuple = check_copies.convert_to_localized_md( lowerCamelCase_ , lowerCamelCase_ , localized_readme["""format_model_list"""] ) # Check if the model link is synchronized. self.assertEqual(lowerCamelCase_ , lowerCamelCase_ )
323
from math import factorial lowerCAmelCase_ = {str(digit): factorial(digit) for digit in range(1_0)} def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError('''Parameter number must be int''' ) if number < 0: raise ValueError('''Parameter number must be greater than or equal to 0''' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCamelCase ) ) def lowerCamelCase_ ( _UpperCamelCase = 60 , _UpperCamelCase = 1_000_000 ) -> int: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ) or not isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError('''Parameters chain_length and number_limit must be int''' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( '''Parameters chain_length and number_limit must be greater than 0''' ) # the counter for the chains with the exact desired length snake_case_ : Optional[Any] = 0 # the cached sizes of the previous chains snake_case_ : dict[int, int] = {} for start_chain_element in range(1 , _UpperCamelCase ): # The temporary set will contain the elements of the chain snake_case_ : List[str] = set() snake_case_ : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. snake_case_ : Any = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCamelCase ) chain_set_length += 1 snake_case_ : List[Any] = digit_factorial_sum(_UpperCamelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] snake_case_ : List[str] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F'''{solution()}''')
279
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) def lowercase__( __SCREAMING_SNAKE_CASE : str ): lowercase_ : Dict = DPTConfig(embedding_type='hybrid' ) if "large" in checkpoint_url: lowercase_ : str = 10_24 lowercase_ : List[str] = 40_96 lowercase_ : List[str] = 24 lowercase_ : Union[str, Any] = 16 lowercase_ : Union[str, Any] = [5, 11, 17, 23] lowercase_ : List[str] = [2_56, 5_12, 10_24, 10_24] lowercase_ : List[Any] = (1, 3_84, 3_84) if "nyu" or "midas" in checkpoint_url: lowercase_ : str = 7_68 lowercase_ : Optional[Any] = [1, 1, 1, 0.5] lowercase_ : Optional[int] = [2_56, 5_12, 7_68, 7_68] lowercase_ : List[Any] = 1_50 lowercase_ : Dict = 16 lowercase_ : List[str] = (1, 3_84, 3_84) lowercase_ : Tuple = False lowercase_ : Any = '''project''' if "ade" in checkpoint_url: lowercase_ : Any = True lowercase_ : Optional[Any] = 7_68 lowercase_ : List[str] = [1, 1, 1, 0.5] lowercase_ : Dict = 1_50 lowercase_ : Optional[int] = 16 lowercase_ : int = '''huggingface/label-files''' lowercase_ : Dict = '''ade20k-id2label.json''' lowercase_ : Any = json.load(open(cached_download(hf_hub_url(_UpperCamelCase , _UpperCamelCase , repo_type='dataset' ) ) , 'r' ) ) lowercase_ : List[str] = {int(_UpperCamelCase ): v for k, v in idalabel.items()} lowercase_ : List[str] = idalabel lowercase_ : List[Any] = {v: k for k, v in idalabel.items()} lowercase_ : int = [1, 1_50, 4_80, 4_80] return config, expected_shape def lowercase__( __SCREAMING_SNAKE_CASE : List[Any] ): lowercase_ : Tuple = ['''pretrained.model.head.weight''', '''pretrained.model.head.bias'''] for k in ignore_keys: state_dict.pop(_UpperCamelCase , _UpperCamelCase ) def lowercase__( __SCREAMING_SNAKE_CASE : int ): if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): lowercase_ : Union[str, Any] = name.replace('pretrained.model' , 'dpt.encoder' ) if "pretrained.model" in name: lowercase_ : Any = name.replace('pretrained.model' , 'dpt.embeddings' ) if "patch_embed" in name: lowercase_ : str = name.replace('patch_embed' , '' ) if "pos_embed" in name: lowercase_ : Dict = name.replace('pos_embed' , 'position_embeddings' ) if "attn.proj" in name: lowercase_ : Dict = name.replace('attn.proj' , 'attention.output.dense' ) if "proj" in name and "project" not in name: lowercase_ : Tuple = name.replace('proj' , 'projection' ) if "blocks" in name: lowercase_ : Any = name.replace('blocks' , 'layer' ) if "mlp.fc1" in name: lowercase_ : Any = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: lowercase_ : Dict = name.replace('mlp.fc2' , 'output.dense' ) if "norm1" in name and "backbone" not in name: lowercase_ : List[Any] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name and "backbone" not in name: lowercase_ : Optional[int] = name.replace('norm2' , 'layernorm_after' ) if "scratch.output_conv" in name: lowercase_ : str = name.replace('scratch.output_conv' , 'head' ) if "scratch" in name: lowercase_ : List[Any] = name.replace('scratch' , 'neck' ) if "layer1_rn" in name: lowercase_ : List[Any] = name.replace('layer1_rn' , 'convs.0' ) if "layer2_rn" in name: lowercase_ : List[str] = name.replace('layer2_rn' , 'convs.1' ) if "layer3_rn" in name: lowercase_ : Dict = name.replace('layer3_rn' , 'convs.2' ) if "layer4_rn" in name: lowercase_ : List[Any] = name.replace('layer4_rn' , 'convs.3' ) if "refinenet" in name: lowercase_ : Dict = int(name[len('neck.refinenet' ) : len('neck.refinenet' ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 lowercase_ : str = name.replace(F'''refinenet{layer_idx}''' , F'''fusion_stage.layers.{abs(layer_idx-4 )}''' ) if "out_conv" in name: lowercase_ : List[str] = name.replace('out_conv' , 'projection' ) if "resConfUnit1" in name: lowercase_ : int = name.replace('resConfUnit1' , 'residual_layer1' ) if "resConfUnit2" in name: lowercase_ : Optional[int] = name.replace('resConfUnit2' , 'residual_layer2' ) if "conv1" in name: lowercase_ : Any = name.replace('conv1' , 'convolution1' ) if "conv2" in name: lowercase_ : Optional[Any] = name.replace('conv2' , 'convolution2' ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: lowercase_ : Union[str, Any] = name.replace('pretrained.act_postprocess1.0.project.0' , 'neck.reassemble_stage.readout_projects.0.0' ) if "pretrained.act_postprocess2.0.project.0" in name: lowercase_ : Union[str, Any] = name.replace('pretrained.act_postprocess2.0.project.0' , 'neck.reassemble_stage.readout_projects.1.0' ) if "pretrained.act_postprocess3.0.project.0" in name: lowercase_ : Any = name.replace('pretrained.act_postprocess3.0.project.0' , 'neck.reassemble_stage.readout_projects.2.0' ) if "pretrained.act_postprocess4.0.project.0" in name: lowercase_ : str = name.replace('pretrained.act_postprocess4.0.project.0' , 'neck.reassemble_stage.readout_projects.3.0' ) # resize blocks if "pretrained.act_postprocess1.3" in name: lowercase_ : Dict = name.replace('pretrained.act_postprocess1.3' , 'neck.reassemble_stage.layers.0.projection' ) if "pretrained.act_postprocess1.4" in name: lowercase_ : Dict = name.replace('pretrained.act_postprocess1.4' , 'neck.reassemble_stage.layers.0.resize' ) if "pretrained.act_postprocess2.3" in name: lowercase_ : Optional[Any] = name.replace('pretrained.act_postprocess2.3' , 'neck.reassemble_stage.layers.1.projection' ) if "pretrained.act_postprocess2.4" in name: lowercase_ : Optional[Any] = name.replace('pretrained.act_postprocess2.4' , 'neck.reassemble_stage.layers.1.resize' ) if "pretrained.act_postprocess3.3" in name: lowercase_ : Optional[int] = name.replace('pretrained.act_postprocess3.3' , 'neck.reassemble_stage.layers.2.projection' ) if "pretrained.act_postprocess4.3" in name: lowercase_ : Any = name.replace('pretrained.act_postprocess4.3' , 'neck.reassemble_stage.layers.3.projection' ) if "pretrained.act_postprocess4.4" in name: lowercase_ : str = name.replace('pretrained.act_postprocess4.4' , 'neck.reassemble_stage.layers.3.resize' ) if "pretrained" in name: lowercase_ : List[Any] = name.replace('pretrained' , 'dpt' ) if "bn" in name: lowercase_ : int = name.replace('bn' , 'batch_norm' ) if "head" in name: lowercase_ : str = name.replace('head' , 'head.head' ) if "encoder.norm" in name: lowercase_ : List[Any] = name.replace('encoder.norm' , 'layernorm' ) if "auxlayer" in name: lowercase_ : Any = name.replace('auxlayer' , 'auxiliary_head.head' ) if "backbone" in name: lowercase_ : List[str] = name.replace('backbone' , 'backbone.bit.encoder' ) if ".." in name: lowercase_ : int = name.replace('..' , '.' ) if "stem.conv" in name: lowercase_ : int = name.replace('stem.conv' , 'bit.embedder.convolution' ) if "blocks" in name: lowercase_ : List[str] = name.replace('blocks' , 'layers' ) if "convolution" in name and "backbone" in name: lowercase_ : str = name.replace('convolution' , 'conv' ) if "layer" in name and "backbone" in name: lowercase_ : List[Any] = name.replace('layer' , 'layers' ) if "backbone.bit.encoder.bit" in name: lowercase_ : Union[str, Any] = name.replace('backbone.bit.encoder.bit' , 'backbone.bit' ) if "embedder.conv" in name: lowercase_ : Optional[Any] = name.replace('embedder.conv' , 'embedder.convolution' ) if "backbone.bit.encoder.stem.norm" in name: lowercase_ : List[Any] = name.replace('backbone.bit.encoder.stem.norm' , 'backbone.bit.embedder.norm' ) return name def lowercase__( __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowercase_ : Dict = state_dict.pop(F'''dpt.encoder.layer.{i}.attn.qkv.weight''' ) lowercase_ : Any = state_dict.pop(F'''dpt.encoder.layer.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict lowercase_ : List[Any] = in_proj_weight[: config.hidden_size, :] lowercase_ : int = in_proj_bias[: config.hidden_size] lowercase_ : Dict = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowercase_ : str = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowercase_ : Tuple = in_proj_weight[ -config.hidden_size :, : ] lowercase_ : Dict = in_proj_bias[-config.hidden_size :] def lowercase__( ): lowercase_ : int = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowercase_ : Dict = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im @torch.no_grad() def lowercase__( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict ): lowercase_ : Dict = get_dpt_config(_UpperCamelCase ) # load original state_dict from URL # state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu") lowercase_ : Union[str, Any] = torch.load(_UpperCamelCase , map_location='cpu' ) # remove certain keys remove_ignore_keys_(_UpperCamelCase ) # rename keys for key in state_dict.copy().keys(): lowercase_ : Dict = state_dict.pop(_UpperCamelCase ) lowercase_ : Any = val # read in qkv matrices read_in_q_k_v(_UpperCamelCase , _UpperCamelCase ) # load HuggingFace model lowercase_ : str = DPTForSemanticSegmentation(_UpperCamelCase ) if '''ade''' in checkpoint_url else DPTForDepthEstimation(_UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) model.eval() # Check outputs on an image lowercase_ : Tuple = 4_80 if '''ade''' in checkpoint_url else 3_84 lowercase_ : List[Any] = DPTImageProcessor(size=_UpperCamelCase ) lowercase_ : Any = prepare_img() lowercase_ : Optional[int] = image_processor(_UpperCamelCase , return_tensors='pt' ) # forward pass lowercase_ : Optional[int] = model(**_UpperCamelCase ).logits if '''ade''' in checkpoint_url else model(**_UpperCamelCase ).predicted_depth if show_prediction: lowercase_ : Dict = ( torch.nn.functional.interpolate( outputs.unsqueeze(1 ) , size=(image.size[1], image.size[0]) , mode='bicubic' , align_corners=_UpperCamelCase , ) .squeeze() .cpu() .numpy() ) Image.fromarray((prediction / prediction.max()) * 2_55 ).show() if pytorch_dump_folder_path is not None: Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(_UpperCamelCase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(_UpperCamelCase ) if push_to_hub: model.push_to_hub('ybelkada/dpt-hybrid-midas' ) image_processor.push_to_hub('ybelkada/dpt-hybrid-midas' ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE =argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", type=str, help="URL of the original DPT checkpoint you\'d like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=False, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", ) parser.add_argument( "--model_name", default="dpt-large", type=str, help="Name of the model, in case you\'re pushing to the hub.", ) parser.add_argument( "--show_prediction", action="store_true", ) __SCREAMING_SNAKE_CASE =parser.parse_args() convert_dpt_checkpoint( args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction )
213
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''''' lowerCamelCase_ : str = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) lowerCamelCase_ : str = None # compression type in fsspec. ex: "gzip" lowerCamelCase_ : str = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__(self , __magic_name__ = "" , __magic_name__ = None , __magic_name__ = None , **__magic_name__ ) -> Any: '''simple docstring''' super().__init__(self , **__magic_name__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode snake_case_ : Union[str, Any] = fsspec.open( __magic_name__ , mode='''rb''' , protocol=__magic_name__ , compression=self.compression , client_kwargs={ '''requote_redirect_url''': False, # see https://github.com/huggingface/datasets/pull/5459 '''trust_env''': True, # Enable reading proxy env variables. **(target_options or {}).pop('''client_kwargs''' , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) snake_case_ : Tuple = os.path.basename(self.file.path.split('''::''' )[0] ) snake_case_ : Optional[Any] = ( self.compressed_name[: self.compressed_name.rindex('''.''' )] if '''.''' in self.compressed_name else self.compressed_name ) snake_case_ : Dict = None @classmethod def lowerCamelCase (cls , __magic_name__ ) -> Optional[int]: '''simple docstring''' return super()._strip_protocol(__magic_name__ ).lstrip('''/''' ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' if self.dir_cache is None: snake_case_ : Optional[int] = {**self.file.fs.info(self.file.path ), '''name''': self.uncompressed_name} snake_case_ : List[str] = {f['''name''']: f} def lowerCamelCase (self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' return self.file.open().read() def lowerCamelCase (self , __magic_name__ , __magic_name__ = "rb" , __magic_name__=None , __magic_name__=True , __magic_name__=None , **__magic_name__ , ) -> int: '''simple docstring''' snake_case_ : Union[str, Any] = self._strip_protocol(__magic_name__ ) if mode != "rb": raise ValueError(F'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''bz2''' lowerCamelCase_ : Any = '''bz2''' lowerCamelCase_ : int = '''.bz2''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''gzip''' lowerCamelCase_ : Dict = '''gzip''' lowerCamelCase_ : int = '''.gz''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''lz4''' lowerCamelCase_ : Any = '''lz4''' lowerCamelCase_ : Optional[Any] = '''.lz4''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''xz''' lowerCamelCase_ : Any = '''xz''' lowerCamelCase_ : int = '''.xz''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''zstd''' lowerCamelCase_ : Tuple = '''zstd''' lowerCamelCase_ : Any = '''.zst''' def __init__(self , __magic_name__ , __magic_name__ = "rb" , __magic_name__ = None , __magic_name__ = None , __magic_name__ = DEFAULT_BLOCK_SIZE , **__magic_name__ , ) -> Tuple: '''simple docstring''' super().__init__( fo=__magic_name__ , mode=__magic_name__ , target_protocol=__magic_name__ , target_options=__magic_name__ , block_size=__magic_name__ , **__magic_name__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 snake_case_ : Dict = self.file.__enter__ class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : str = file_ def __enter__(self ) -> List[Any]: '''simple docstring''' self._file.__enter__() return self def __exit__(self , *__magic_name__ , **__magic_name__ ) -> int: '''simple docstring''' self._file.__exit__(*__magic_name__ , **__magic_name__ ) def __iter__(self ) -> Optional[int]: '''simple docstring''' return iter(self._file ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return next(self._file ) def __getattr__(self , __magic_name__ ) -> str: '''simple docstring''' return getattr(self._file , __magic_name__ ) def fixed_enter(*__magic_name__ , **__magic_name__ ): return WrappedFile(_enter(*__magic_name__ , **__magic_name__ ) ) snake_case_ : Tuple = fixed_enter
279
0
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() __snake_case = logging.get_logger(__name__) def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> Tuple: '''simple docstring''' UpperCAmelCase : Optional[Any] =original_name.split('''.''' )[0] UpperCAmelCase : int =key.split('''.''' ) UpperCAmelCase : List[str] =int(key_list[key_list.index(_UpperCamelCase ) - 2] ) UpperCAmelCase : Tuple =int(key_list[key_list.index(_UpperCamelCase ) - 1] ) UpperCAmelCase : Optional[Any] =orig_block_num - offset UpperCAmelCase : List[str] =key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def lowerCAmelCase_ ( __lowerCAmelCase )-> int: '''simple docstring''' UpperCAmelCase : Dict =OrderedDict() UpperCAmelCase : Dict =0, 0 for key, value in state_dict.items(): if key.startswith('''network''' ): UpperCAmelCase : Tuple =key.replace('''network''' , '''poolformer.encoder''' ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith('''bias''' ) and "patch_embed" not in key: patch_emb_offset += 1 UpperCAmelCase : List[Any] =key[: key.find('''proj''' )] UpperCAmelCase : int =key.replace(_UpperCamelCase , f'''patch_embeddings.{total_embed_found}.''' ) UpperCAmelCase : str =key.replace('''proj''' , '''projection''' ) if key.endswith('''bias''' ): total_embed_found += 1 if "patch_embeddings" in key: UpperCAmelCase : List[Any] ='''poolformer.encoder.''' + key if "mlp.fc1" in key: UpperCAmelCase : str =replace_key_with_offset(_UpperCamelCase , _UpperCamelCase , '''mlp.fc1''' , '''output.conv1''' ) if "mlp.fc2" in key: UpperCAmelCase : Optional[Any] =replace_key_with_offset(_UpperCamelCase , _UpperCamelCase , '''mlp.fc2''' , '''output.conv2''' ) if "norm1" in key: UpperCAmelCase : Dict =replace_key_with_offset(_UpperCamelCase , _UpperCamelCase , '''norm1''' , '''before_norm''' ) if "norm2" in key: UpperCAmelCase : Union[str, Any] =replace_key_with_offset(_UpperCamelCase , _UpperCamelCase , '''norm2''' , '''after_norm''' ) if "layer_scale_1" in key: UpperCAmelCase : Dict =replace_key_with_offset(_UpperCamelCase , _UpperCamelCase , '''layer_scale_1''' , '''layer_scale_1''' ) if "layer_scale_2" in key: UpperCAmelCase : List[Any] =replace_key_with_offset(_UpperCamelCase , _UpperCamelCase , '''layer_scale_2''' , '''layer_scale_2''' ) if "head" in key: UpperCAmelCase : Optional[Any] =key.replace('''head''' , '''classifier''' ) UpperCAmelCase : List[str] =value return new_state_dict def lowerCAmelCase_ ( )-> Optional[int]: '''simple docstring''' UpperCAmelCase : Optional[int] ='''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase : List[Any] =Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return image @torch.no_grad() def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> Optional[int]: '''simple docstring''' UpperCAmelCase : int =PoolFormerConfig() # set attributes based on model_name UpperCAmelCase : Union[str, Any] ='''huggingface/label-files''' UpperCAmelCase : Any =model_name[-3:] UpperCAmelCase : Any =10_00 UpperCAmelCase : Optional[Any] ='''imagenet-1k-id2label.json''' UpperCAmelCase : Union[str, Any] =(1, 10_00) # set config attributes UpperCAmelCase : Optional[Any] =json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase : Any ={int(_UpperCamelCase ): v for k, v in idalabel.items()} UpperCAmelCase : int =idalabel UpperCAmelCase : Optional[int] ={v: k for k, v in idalabel.items()} if size == "s12": UpperCAmelCase : Optional[Any] =[2, 2, 6, 2] UpperCAmelCase : Optional[int] =[64, 1_28, 3_20, 5_12] UpperCAmelCase : Optional[int] =4.0 UpperCAmelCase : Any =0.9 elif size == "s24": UpperCAmelCase : List[Any] =[4, 4, 12, 4] UpperCAmelCase : str =[64, 1_28, 3_20, 5_12] UpperCAmelCase : Union[str, Any] =4.0 UpperCAmelCase : Optional[Any] =0.9 elif size == "s36": UpperCAmelCase : Optional[int] =[6, 6, 18, 6] UpperCAmelCase : List[str] =[64, 1_28, 3_20, 5_12] UpperCAmelCase : Dict =4.0 UpperCAmelCase : Union[str, Any] =1e-6 UpperCAmelCase : Union[str, Any] =0.9 elif size == "m36": UpperCAmelCase : str =[6, 6, 18, 6] UpperCAmelCase : Dict =[96, 1_92, 3_84, 7_68] UpperCAmelCase : List[Any] =4.0 UpperCAmelCase : List[Any] =1e-6 UpperCAmelCase : str =0.95 elif size == "m48": UpperCAmelCase : List[Any] =[8, 8, 24, 8] UpperCAmelCase : Union[str, Any] =[96, 1_92, 3_84, 7_68] UpperCAmelCase : Optional[int] =4.0 UpperCAmelCase : Dict =1e-6 UpperCAmelCase : Any =0.95 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor UpperCAmelCase : Optional[Any] =PoolFormerImageProcessor(crop_pct=_UpperCamelCase ) # Prepare image UpperCAmelCase : Tuple =prepare_img() UpperCAmelCase : str =image_processor(images=_UpperCamelCase , return_tensors='''pt''' ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict UpperCAmelCase : List[Any] =torch.load(_UpperCamelCase , map_location=torch.device('''cpu''' ) ) # rename keys UpperCAmelCase : Optional[int] =rename_keys(_UpperCamelCase ) # create HuggingFace model and load state dict UpperCAmelCase : str =PoolFormerForImageClassification(_UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) model.eval() # Define image processor UpperCAmelCase : str =PoolFormerImageProcessor(crop_pct=_UpperCamelCase ) UpperCAmelCase : Any =image_processor(images=prepare_img() , return_tensors='''pt''' ).pixel_values # forward pass UpperCAmelCase : List[Any] =model(_UpperCamelCase ) UpperCAmelCase : Union[str, Any] =outputs.logits # define expected logit slices for different models if size == "s12": UpperCAmelCase : List[str] =torch.tensor([-0.3045, -0.6758, -0.4869] ) elif size == "s24": UpperCAmelCase : Optional[int] =torch.tensor([0.4402, -0.1374, -0.8045] ) elif size == "s36": UpperCAmelCase : Dict =torch.tensor([-0.6080, -0.5133, -0.5898] ) elif size == "m36": UpperCAmelCase : Dict =torch.tensor([0.3952, 0.2263, -1.2668] ) elif size == "m48": UpperCAmelCase : Dict =torch.tensor([0.1167, -0.0656, -0.3423] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , _UpperCamelCase , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) model.save_pretrained(_UpperCamelCase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''poolformer_s12''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) __snake_case = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
348
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''megatron-bert''' def __init__(self , __magic_name__=2_9056 , __magic_name__=1024 , __magic_name__=24 , __magic_name__=16 , __magic_name__=4096 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=512 , __magic_name__=2 , __magic_name__=0.02 , __magic_name__=1e-12 , __magic_name__=0 , __magic_name__="absolute" , __magic_name__=True , **__magic_name__ , ) -> Any: '''simple docstring''' super().__init__(pad_token_id=__magic_name__ , **__magic_name__ ) snake_case_ : Union[str, Any] = vocab_size snake_case_ : Dict = hidden_size snake_case_ : Dict = num_hidden_layers snake_case_ : Optional[int] = num_attention_heads snake_case_ : int = hidden_act snake_case_ : List[str] = intermediate_size snake_case_ : Dict = hidden_dropout_prob snake_case_ : str = attention_probs_dropout_prob snake_case_ : str = max_position_embeddings snake_case_ : Any = type_vocab_size snake_case_ : int = initializer_range snake_case_ : int = layer_norm_eps snake_case_ : List[str] = position_embedding_type snake_case_ : Dict = use_cache
279
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Dict = { "microsoft/biogpt": "https://huggingface.co/microsoft/biogpt/resolve/main/config.json", # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class UpperCamelCase__ ( _a): UpperCAmelCase__ : Tuple = '''biogpt''' def __init__( self :Optional[int] , _A :Dict=42_384 , _A :Tuple=1_024 , _A :Dict=24 , _A :List[Any]=16 , _A :Union[str, Any]=4_096 , _A :Optional[int]="gelu" , _A :List[Any]=0.1 , _A :Union[str, Any]=0.1 , _A :int=1_024 , _A :Union[str, Any]=0.02 , _A :int=1E-12 , _A :Optional[Any]=True , _A :Union[str, Any]=True , _A :Optional[int]=0.0 , _A :int=0.0 , _A :Dict=1 , _A :Any=0 , _A :Optional[Any]=2 , **_A :Optional[Any] , ) -> Optional[int]: '''simple docstring''' __A = vocab_size __A = max_position_embeddings __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = initializer_range __A = layer_norm_eps __A = scale_embedding __A = use_cache __A = layerdrop __A = activation_dropout super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A )
161
import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch lowerCAmelCase_ = random.Random() def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase=1.0 , _UpperCamelCase=None , _UpperCamelCase=None ) -> List[Any]: """simple docstring""" if rng is None: snake_case_ : str = global_rng snake_case_ : Any = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=400 , __magic_name__=2000 , __magic_name__=10 , __magic_name__=160 , __magic_name__=8 , __magic_name__=0.0 , __magic_name__=4000 , __magic_name__=False , __magic_name__=True , ) -> List[str]: '''simple docstring''' snake_case_ : Tuple = parent snake_case_ : str = batch_size snake_case_ : Union[str, Any] = min_seq_length snake_case_ : Tuple = max_seq_length snake_case_ : Optional[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) snake_case_ : Optional[int] = padding_value snake_case_ : Union[str, Any] = sampling_rate snake_case_ : Optional[int] = return_attention_mask snake_case_ : str = do_normalize snake_case_ : str = feature_size snake_case_ : Optional[Any] = chunk_length snake_case_ : Union[str, Any] = hop_length def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def lowerCamelCase (self , __magic_name__=False , __magic_name__=False ) -> Optional[Any]: '''simple docstring''' def _flatten(__magic_name__ ): return list(itertools.chain(*__magic_name__ ) ) if equal_length: snake_case_ : int = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size snake_case_ : int = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: snake_case_ : str = [np.asarray(__magic_name__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[Any] = WhisperFeatureExtractor if is_speech_available() else None def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[str] = WhisperFeatureExtractionTester(self ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : Union[str, Any] = feat_extract_first.save_pretrained(__magic_name__ )[0] check_json_file_has_correct_format(__magic_name__ ) snake_case_ : List[Any] = self.feature_extraction_class.from_pretrained(__magic_name__ ) snake_case_ : Optional[int] = feat_extract_first.to_dict() snake_case_ : Dict = feat_extract_second.to_dict() snake_case_ : List[str] = feat_extract_first.mel_filters snake_case_ : Union[str, Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(__magic_name__ , __magic_name__ ) ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : List[Any] = os.path.join(__magic_name__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(__magic_name__ ) snake_case_ : Optional[int] = self.feature_extraction_class.from_json_file(__magic_name__ ) snake_case_ : int = feat_extract_first.to_dict() snake_case_ : Optional[int] = feat_extract_second.to_dict() snake_case_ : Union[str, Any] = feat_extract_first.mel_filters snake_case_ : str = feat_extract_second.mel_filters self.assertTrue(np.allclose(__magic_name__ , __magic_name__ ) ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 snake_case_ : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] snake_case_ : str = [np.asarray(__magic_name__ ) for speech_input in speech_inputs] # Test feature size snake_case_ : str = feature_extractor(__magic_name__ , padding='''max_length''' , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input snake_case_ : Dict = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features snake_case_ : Optional[int] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test batched snake_case_ : int = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : Union[str, Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. snake_case_ : Union[str, Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] snake_case_ : List[str] = np.asarray(__magic_name__ ) snake_case_ : List[Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : Dict = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test truncation required snake_case_ : Any = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] snake_case_ : Union[str, Any] = [np.asarray(__magic_name__ ) for speech_input in speech_inputs] snake_case_ : Tuple = [x[: feature_extractor.n_samples] for x in speech_inputs] snake_case_ : Optional[Any] = [np.asarray(__magic_name__ ) for speech_input in speech_inputs_truncated] snake_case_ : Any = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : List[Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) def lowerCamelCase (self ) -> int: '''simple docstring''' import torch snake_case_ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case_ : Union[str, Any] = np.random.rand(100 , 32 ).astype(np.floataa ) snake_case_ : Dict = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: snake_case_ : Optional[Any] = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) snake_case_ : Optional[Any] = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Optional[Any] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech snake_case_ : Optional[Any] = ds.sort('''id''' ).select(range(__magic_name__ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : str = torch.tensor( [ 0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951, 0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678, 0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554, -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854 ] ) # fmt: on snake_case_ : List[Any] = self._load_datasamples(1 ) snake_case_ : Union[str, Any] = WhisperFeatureExtractor() snake_case_ : Union[str, Any] = feature_extractor(__magic_name__ , return_tensors='''pt''' ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __magic_name__ , atol=1e-4 ) ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case_ : Optional[int] = self._load_datasamples(1 )[0] snake_case_ : List[str] = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue snake_case_ : Optional[Any] = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__magic_name__ )[0] self.assertTrue(np.all(np.mean(__magic_name__ ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(__magic_name__ ) - 1 ) < 1e-3 ) )
279
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __a = logging.get_logger(__name__) class lowercase__( _a ): """simple docstring""" a :Dict = ['''pixel_values'''] def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[Any] = True , SCREAMING_SNAKE_CASE_ : List[str] = None , SCREAMING_SNAKE_CASE_ : str = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ : Union[str, Any] = True , SCREAMING_SNAKE_CASE_ : int = None , SCREAMING_SNAKE_CASE_ : Dict = True , SCREAMING_SNAKE_CASE_ : Dict = 1 / 2_5_5 , SCREAMING_SNAKE_CASE_ : Optional[int] = True , SCREAMING_SNAKE_CASE_ : Tuple = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , **SCREAMING_SNAKE_CASE_ : Union[str, Any] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE_ ) lowercase_ = size if size is not None else {'''shortest_edge''': 2_5_6} lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) lowercase_ = crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ ) lowercase_ = do_resize lowercase_ = size lowercase_ = resample lowercase_ = do_center_crop lowercase_ = crop_size lowercase_ = do_rescale lowercase_ = rescale_factor lowercase_ = do_normalize lowercase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowercase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Union[str, Any] = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ : Tuple = None , **SCREAMING_SNAKE_CASE_ : Any , ) -> np.ndarray: lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) lowercase_ = get_resize_output_image_size(SCREAMING_SNAKE_CASE_ , size=size['''shortest_edge'''] , default_to_square=SCREAMING_SNAKE_CASE_ ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Any , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[str] = None , **SCREAMING_SNAKE_CASE_ : Any , ) -> np.ndarray: lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ ) return center_crop(SCREAMING_SNAKE_CASE_ , size=(size['''height'''], size['''width''']) , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Any , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[str] = None , **SCREAMING_SNAKE_CASE_ : Any ) -> np.ndarray: return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : str , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Dict = None , **SCREAMING_SNAKE_CASE_ : List[Any] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[str] = None , SCREAMING_SNAKE_CASE_ : List[str] = None , SCREAMING_SNAKE_CASE_ : List[Any] = None , SCREAMING_SNAKE_CASE_ : Tuple = None , SCREAMING_SNAKE_CASE_ : Optional[Any] = None , SCREAMING_SNAKE_CASE_ : List[str] = None , SCREAMING_SNAKE_CASE_ : Tuple = None , SCREAMING_SNAKE_CASE_ : Tuple = None , SCREAMING_SNAKE_CASE_ : Any = None , SCREAMING_SNAKE_CASE_ : Tuple = None , SCREAMING_SNAKE_CASE_ : List[Any] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> Optional[Any]: lowercase_ = do_resize if do_resize is not None else self.do_resize lowercase_ = size if size is not None else self.size lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) lowercase_ = resample if resample is not None else self.resample lowercase_ = do_center_crop if do_center_crop is not None else self.do_center_crop lowercase_ = crop_size if crop_size is not None else self.crop_size lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ ) lowercase_ = do_rescale if do_rescale is not None else self.do_rescale lowercase_ = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase_ = do_normalize if do_normalize is not None else self.do_normalize lowercase_ = image_mean if image_mean is not None else self.image_mean lowercase_ = image_std if image_std is not None else self.image_std lowercase_ = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: 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. lowercase_ = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: lowercase_ = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_center_crop: lowercase_ = [self.center_crop(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: lowercase_ = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: lowercase_ = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] lowercase_ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] lowercase_ = {'''pixel_values''': images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ )
30
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase_ = logging.getLogger(__name__) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : List[str] = argparse.ArgumentParser( description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' ) parser.add_argument( '''--dataset_name''' , type=_UpperCamelCase , default='''wikitext''' , help='''Name of the training. Explore datasets at: hf.co/datasets.''' , ) parser.add_argument( '''--dataset_config''' , type=_UpperCamelCase , default='''wikitext-103-raw-v1''' , help='''Configuration name of the dataset.''' ) parser.add_argument( '''--tokenizer_name_or_path''' , type=_UpperCamelCase , default='''sayakpaul/unigram-tokenizer-wikitext''' , help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' , ) parser.add_argument( '''--shard_size''' , type=_UpperCamelCase , default=1_000 , help='''Number of entries to go in a single shard.''' , ) parser.add_argument('''--split''' , type=_UpperCamelCase , default='''train''' , choices=['''train''', '''test''', '''validation'''] ) parser.add_argument( '''--limit''' , default=_UpperCamelCase , type=_UpperCamelCase , help='''Limit the number of shards (used for debugging).''' , ) parser.add_argument( '''--max_length''' , type=_UpperCamelCase , default=512 , help='''Maximum sequence length. For training on TPUs, it helps to have a maximum''' ''' sequence length that is a multiple of 8.''' , ) parser.add_argument( '''--output_dir''' , default='''tf-tpu''' , type=_UpperCamelCase , help='''Output directory where the TFRecord shards will be saved. If the''' ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord''' ''' shards will be directly saved to a Google Cloud Storage bucket.''' , ) snake_case_ : List[Any] = parser.parse_args() return args def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple: """simple docstring""" def fn(_UpperCamelCase ): return tokenizer(examples['''text'''] ) return fn def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : Any = [] for i in range(len(tokenized_data['''input_ids'''] ) ): snake_case_ : Any = { '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ), '''attention_mask''': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ), } snake_case_ : Optional[int] = tf.train.Features(feature=_UpperCamelCase ) snake_case_ : Optional[Any] = tf.train.Example(features=_UpperCamelCase ) snake_case_ : Optional[Any] = example.SerializeToString() records.append(_UpperCamelCase ) return records def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : int = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: snake_case_ : Union[str, Any] = min(len(_UpperCamelCase ) , args.limit ) snake_case_ : int = dataset.select(range(_UpperCamelCase ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) snake_case_ : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) snake_case_ : str = os.path.join(args.output_dir , args.split ) if not os.path.exists(_UpperCamelCase ): os.makedirs(_UpperCamelCase ) else: snake_case_ : Optional[Any] = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. snake_case_ : Optional[Any] = tokenize_function(_UpperCamelCase ) snake_case_ : List[Any] = dataset.map(_UpperCamelCase , batched=_UpperCamelCase , num_proc=4 , remove_columns=['''text'''] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(_UpperCamelCase ): # Concatenate all texts. snake_case_ : Tuple = {k: sum(examples[k] , [] ) for k in examples.keys()} snake_case_ : List[str] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 snake_case_ : int = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. snake_case_ : Union[str, Any] = { k: [t[i : i + args.max_length] for i in range(0 , _UpperCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result snake_case_ : int = dataset_tokenized.map(_UpperCamelCase , batched=_UpperCamelCase , batch_size=1_000 , num_proc=4 ) snake_case_ : str = 0 snake_case_ : Optional[Any] = 0 for shard in range(0 , len(_UpperCamelCase ) , args.shard_size ): snake_case_ : Any = grouped_dataset[shard : shard + args.shard_size] snake_case_ : str = len(dataset_snapshot['''input_ids'''] ) snake_case_ : Union[str, Any] = os.path.join(_UpperCamelCase , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) snake_case_ : Dict = get_serialized_examples(_UpperCamelCase ) with tf.io.TFRecordWriter(_UpperCamelCase ) as out_file: for i in range(len(_UpperCamelCase ) ): snake_case_ : List[str] = serialized_examples[i] out_file.write(_UpperCamelCase ) print('''Wrote file {} containing {} records'''.format(_UpperCamelCase , _UpperCamelCase ) ) shard_count += 1 total_records += records_containing with open(f'''split-{args.split}-records-count.txt''' , '''w''' ) as f: print(f'''Total {args.split} records: {total_records}''' , file=_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = parse_args() main(args)
279
0
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class __lowerCAmelCase ( _a ): lowerCAmelCase__ = ['''image_processor''', '''tokenizer'''] lowerCAmelCase__ = '''BlipImageProcessor''' lowerCAmelCase__ = '''AutoTokenizer''' def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' super().__init__(__UpperCAmelCase , __UpperCAmelCase ) # add QFormer tokenizer __lowerCamelCase = qformer_tokenizer def __call__( self , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = True , __UpperCAmelCase = False , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = 0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = True , __UpperCAmelCase = None , **__UpperCAmelCase , ): '''simple docstring''' if images is None and text is None: raise ValueError('''You have to specify at least images or text.''' ) __lowerCamelCase = BatchFeature() if text is not None: __lowerCamelCase = self.tokenizer( text=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=__UpperCAmelCase , stride=__UpperCAmelCase , pad_to_multiple_of=__UpperCAmelCase , return_attention_mask=__UpperCAmelCase , return_overflowing_tokens=__UpperCAmelCase , return_special_tokens_mask=__UpperCAmelCase , return_offsets_mapping=__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase , return_length=__UpperCAmelCase , verbose=__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase , ) encoding.update(__UpperCAmelCase ) __lowerCamelCase = self.qformer_tokenizer( text=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=__UpperCAmelCase , stride=__UpperCAmelCase , pad_to_multiple_of=__UpperCAmelCase , return_attention_mask=__UpperCAmelCase , return_overflowing_tokens=__UpperCAmelCase , return_special_tokens_mask=__UpperCAmelCase , return_offsets_mapping=__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase , return_length=__UpperCAmelCase , verbose=__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase , ) __lowerCamelCase = qformer_text_encoding.pop('''input_ids''' ) __lowerCamelCase = qformer_text_encoding.pop('''attention_mask''' ) if images is not None: __lowerCamelCase = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase ) encoding.update(__UpperCAmelCase ) return encoding def lowerCamelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.tokenizer.batch_decode(*__UpperCAmelCase , **__UpperCAmelCase ) def lowerCamelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return self.tokenizer.decode(*__UpperCAmelCase , **__UpperCAmelCase ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = self.tokenizer.model_input_names __lowerCamelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def lowerCamelCase ( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' if os.path.isfile(__UpperCAmelCase ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(__UpperCAmelCase , exist_ok=__UpperCAmelCase ) __lowerCamelCase = os.path.join(__UpperCAmelCase , '''qformer_tokenizer''' ) self.qformer_tokenizer.save_pretrained(__UpperCAmelCase ) return super().save_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) @classmethod def lowerCamelCase ( cls , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = AutoTokenizer.from_pretrained(__UpperCAmelCase , subfolder='''qformer_tokenizer''' ) __lowerCamelCase = cls._get_arguments_from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) args.append(__UpperCAmelCase ) return cls(*__UpperCAmelCase )
330
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Any = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Any = hf_hub_download( repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : List[Any] = VideoClassificationPipeline(model=__magic_name__ , image_processor=__magic_name__ , top_k=2 ) snake_case_ : str = [ example_video_filepath, '''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''', ] return video_classifier, examples def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' for example in examples: snake_case_ : Union[str, Any] = video_classifier(__magic_name__ ) self.assertEqual( __magic_name__ , [ {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, ] , ) @require_torch def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Any = '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification''' snake_case_ : str = VideoMAEFeatureExtractor( size={'''shortest_edge''': 10} , crop_size={'''height''': 10, '''width''': 10} ) snake_case_ : int = pipeline( '''video-classification''' , model=__magic_name__ , feature_extractor=__magic_name__ , frame_sampling_rate=4 ) snake_case_ : List[str] = hf_hub_download(repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : Union[str, Any] = video_classifier(__magic_name__ , top_k=2 ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}] , ) snake_case_ : int = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], ] , ) @require_tf def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' pass
279
0
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin a_ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe_char.model") @require_sentencepiece @require_tokenizers class a ( _a , unittest.TestCase ): _lowerCAmelCase = SpeechTaTokenizer _lowerCAmelCase = False _lowerCAmelCase = True def __UpperCAmelCase ( self ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing _a = SpeechTaTokenizer(__magic_name__ ) _a = AddedToken('<mask>' , lstrip=__magic_name__ , rstrip=__magic_name__ ) _a = mask_token tokenizer.add_special_tokens({'mask_token': mask_token} ) tokenizer.add_tokens(['<ctc_blank>'] ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self , __magic_name__ ) -> Dict: _a = '''this is a test''' _a = '''this is a test''' return input_text, output_text def __UpperCAmelCase ( self , __magic_name__ , __magic_name__=False , __magic_name__=20 , __magic_name__=5 ) -> List[Any]: _a = self.get_input_output_texts(__magic_name__ ) _a = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) _a = tokenizer.decode(__magic_name__ , clean_up_tokenization_spaces=__magic_name__ ) return text, ids def __UpperCAmelCase ( self ) -> Optional[int]: _a = '''<pad>''' _a = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def __UpperCAmelCase ( self ) -> Any: _a = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-4] , 'œ' ) self.assertEqual(vocab_keys[-2] , '<mask>' ) self.assertEqual(vocab_keys[-1] , '<ctc_blank>' ) self.assertEqual(len(__magic_name__ ) , 81 ) def __UpperCAmelCase ( self ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def __UpperCAmelCase ( self ) -> Tuple: _a = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): _a = tokenizer.vocab_size _a = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) _a = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] _a = tokenizer.add_tokens(__magic_name__ ) _a = tokenizer.vocab_size _a = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size + len(__magic_name__ ) ) _a = tokenizer.encode('aaaaa bbbbbb low cccccccccdddddddd l' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) _a = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} _a = tokenizer.add_special_tokens(__magic_name__ ) _a = tokenizer.vocab_size _a = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size_a + len(__magic_name__ ) ) _a = tokenizer.encode( '>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __UpperCAmelCase ( self ) -> Union[str, Any]: pass def __UpperCAmelCase ( self ) -> List[str]: pass def __UpperCAmelCase ( self ) -> int: _a = self.get_tokenizer() _a = tokenizer.tokenize('This is a test' ) # fmt: off self.assertListEqual(__magic_name__ , [SPIECE_UNDERLINE, 'T', 'h', 'i', 's', SPIECE_UNDERLINE, 'i', 's', SPIECE_UNDERLINE, 'a', SPIECE_UNDERLINE, 't', 'e', 's', 't'] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) _a = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, 'I', SPIECE_UNDERLINE, 'w', 'a', 's', SPIECE_UNDERLINE, 'b', 'o', 'r', 'n', SPIECE_UNDERLINE, 'i', 'n', SPIECE_UNDERLINE, '92000', ',', SPIECE_UNDERLINE, 'a', 'n', 'd', SPIECE_UNDERLINE, 't', 'h', 'i', 's', SPIECE_UNDERLINE, 'i', 's', SPIECE_UNDERLINE, 'f', 'a', 'l', 's', 'é', '.'] ) _a = tokenizer.convert_tokens_to_ids(__magic_name__ ) # fmt: off self.assertListEqual(__magic_name__ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on _a = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, 'I', SPIECE_UNDERLINE, 'w', 'a', 's', SPIECE_UNDERLINE, 'b', 'o', 'r', 'n', SPIECE_UNDERLINE, 'i', 'n', SPIECE_UNDERLINE, '<unk>', ',', SPIECE_UNDERLINE, 'a', 'n', 'd', SPIECE_UNDERLINE, 't', 'h', 'i', 's', SPIECE_UNDERLINE, 'i', 's', SPIECE_UNDERLINE, 'f', 'a', 'l', 's', 'é', '.'] ) @slow def __UpperCAmelCase ( self ) -> Tuple: _a = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off _a = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name='microsoft/speecht5_asr' , revision='c5ef64c71905caeccde0e4462ef3f9077224c524' , sequences=__magic_name__ , )
168
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" return "\n".join( f'''{number} * {i} = {number * i}''' for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=1_0))
279
0
import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase , _a ): def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' __a = load_tool("""text-to-speech""" ) self.tool.setup() def UpperCamelCase_ ( self : Dict ): '''simple docstring''' torch.manual_seed(0 ) __a = self.tool("""hey""" ) __a = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0005966668832115829, -0.0003657640190795064, -0.00013439502799883485] ) , ) ) def UpperCamelCase_ ( self : int ): '''simple docstring''' torch.manual_seed(0 ) __a = self.tool("""hey""" ) __a = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0005966668832115829, -0.0003657640190795064, -0.00013439502799883485] ) , ) )
302
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCAmelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" snake_case_ : List[str] = ['''layers''', '''blocks'''] for k in ignore_keys: state_dict.pop(_UpperCamelCase , _UpperCamelCase ) lowerCAmelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" snake_case_ : str = list(s_dict.keys() ) for key in keys: snake_case_ : Optional[int] = key for k, v in WHISPER_MAPPING.items(): if k in key: snake_case_ : List[str] = new_key.replace(_UpperCamelCase , _UpperCamelCase ) print(f'''{key} -> {new_key}''' ) snake_case_ : Tuple = s_dict.pop(_UpperCamelCase ) return s_dict def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" snake_case_ , snake_case_ : Dict = emb.weight.shape snake_case_ : Tuple = nn.Linear(_UpperCamelCase , _UpperCamelCase , bias=_UpperCamelCase ) snake_case_ : Any = emb.weight.data return lin_layer def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> bytes: """simple docstring""" os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase ) snake_case_ : List[Any] = os.path.basename(_UpperCamelCase ) snake_case_ : Any = url.split('''/''' )[-2] snake_case_ : str = os.path.join(_UpperCamelCase , _UpperCamelCase ) if os.path.exists(_UpperCamelCase ) and not os.path.isfile(_UpperCamelCase ): raise RuntimeError(f'''{download_target} exists and is not a regular file''' ) if os.path.isfile(_UpperCamelCase ): snake_case_ : Union[str, Any] = open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file''' ) with urllib.request.urlopen(_UpperCamelCase ) as source, open(_UpperCamelCase , '''wb''' ) as output: with tqdm( total=int(source.info().get('''Content-Length''' ) ) , ncols=80 , unit='''iB''' , unit_scale=_UpperCamelCase , unit_divisor=1_024 ) as loop: while True: snake_case_ : Dict = source.read(8_192 ) if not buffer: break output.write(_UpperCamelCase ) loop.update(len(_UpperCamelCase ) ) snake_case_ : Any = open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() != expected_shaaaa: raise RuntimeError( '''Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.''' ) return model_bytes def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" if ".pt" not in checkpoint_path: snake_case_ : str = _download(_MODELS[checkpoint_path] ) else: snake_case_ : Union[str, Any] = torch.load(_UpperCamelCase , map_location='''cpu''' ) snake_case_ : int = original_checkpoint['''dims'''] snake_case_ : List[str] = original_checkpoint['''model_state_dict'''] snake_case_ : str = state_dict['''decoder.token_embedding.weight'''] remove_ignore_keys_(_UpperCamelCase ) rename_keys(_UpperCamelCase ) snake_case_ : Optional[int] = True snake_case_ : int = state_dict['''decoder.layers.0.fc1.weight'''].shape[0] snake_case_ : List[str] = WhisperConfig( vocab_size=dimensions['''n_vocab'''] , encoder_ffn_dim=_UpperCamelCase , decoder_ffn_dim=_UpperCamelCase , num_mel_bins=dimensions['''n_mels'''] , d_model=dimensions['''n_audio_state'''] , max_target_positions=dimensions['''n_text_ctx'''] , encoder_layers=dimensions['''n_audio_layer'''] , encoder_attention_heads=dimensions['''n_audio_head'''] , decoder_layers=dimensions['''n_text_layer'''] , decoder_attention_heads=dimensions['''n_text_state'''] , max_source_positions=dimensions['''n_audio_ctx'''] , ) snake_case_ : Union[str, Any] = WhisperForConditionalGeneration(_UpperCamelCase ) snake_case_ , snake_case_ : List[Any] = model.model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) if len(_UpperCamelCase ) > 0 and not set(_UpperCamelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' f''' but all the following weights are missing {missing}''' ) if tie_embeds: snake_case_ : List[str] = make_linear_from_emb(model.model.decoder.embed_tokens ) else: snake_case_ : Any = proj_out_weights model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCAmelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
279
0
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): @require_torch def UpperCAmelCase_ ( self : int ) -> List[str]: """simple docstring""" snake_case_ : str = pipeline( task='zero-shot-audio-classification' , model='hf-internal-testing/tiny-clap-htsat-unfused' ) snake_case_ : Tuple = load_dataset('ashraq/esc50' ) snake_case_ : List[str] = dataset['''train''']['''audio'''][-1]['''array'''] snake_case_ : Optional[int] = audio_classifier(_A , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(_A ) , [{'score': 0.5_0_1, 'label': 'Sound of a dog'}, {'score': 0.4_9_9, 'label': 'Sound of vaccum cleaner'}] , ) @unittest.skip('No models are available in TF' ) def UpperCAmelCase_ ( self : str ) -> List[Any]: """simple docstring""" pass @slow @require_torch def UpperCAmelCase_ ( self : Tuple ) -> int: """simple docstring""" snake_case_ : List[str] = pipeline( task='zero-shot-audio-classification' , model='laion/clap-htsat-unfused' , ) # This is an audio of a dog snake_case_ : Dict = load_dataset('ashraq/esc50' ) snake_case_ : List[Any] = dataset['''train''']['''audio'''][-1]['''array'''] snake_case_ : int = audio_classifier(_A , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(_A ) , [ {'score': 0.9_9_9, 'label': 'Sound of a dog'}, {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'}, ] , ) snake_case_ : List[str] = audio_classifier([audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] ) self.assertEqual( nested_simplify(_A ) , [ [ {'score': 0.9_9_9, 'label': 'Sound of a dog'}, {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'}, ], ] * 5 , ) snake_case_ : List[Any] = audio_classifier( [audio] * 5 , candidate_labels=['Sound of a dog', 'Sound of vaccum cleaner'] , batch_size=5 ) self.assertEqual( nested_simplify(_A ) , [ [ {'score': 0.9_9_9, 'label': 'Sound of a dog'}, {'score': 0.0_0_1, 'label': 'Sound of vaccum cleaner'}, ], ] * 5 , ) @unittest.skip('No models are available in TF' ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: """simple docstring""" pass
327
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCAmelCase_ = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) lowerCAmelCase_ = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 1_4]), ('''2H 5D 3C AS 5S''', False, [1_4, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [1_4, 1_3, 1_2, 1_1, 1_0]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 2_3), ('''JH 9H TH KH QH''', 2_2), ('''JC KH JS JD JH''', 2_1), ('''KH KC 3S 3H 3D''', 2_0), ('''8C 9C 5C 3C TC''', 1_9), ('''JS QS 9H TS KH''', 1_8), ('''7C 7S KH 2H 7H''', 1_7), ('''3C KH 5D 5S KH''', 1_6), ('''QH 8H KD JH 8S''', 1_5), ('''2D 6D 9D TH 7D''', 1_4), ) def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ , snake_case_ : Any = randrange(len(_UpperCamelCase ) ), randrange(len(_UpperCamelCase ) ) snake_case_ : Any = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] snake_case_ , snake_case_ : Tuple = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def lowerCamelCase_ ( _UpperCamelCase = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(_UpperCamelCase )) @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : str = PokerHand(_UpperCamelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[Any]: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = [PokerHand(_UpperCamelCase ) for hand in SORTED_HANDS] snake_case_ : str = poker_hands.copy() shuffle(_UpperCamelCase ) snake_case_ : List[str] = chain(sorted(_UpperCamelCase ) ) for index, hand in enumerate(_UpperCamelCase ): assert hand == poker_hands[index] def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ : Union[str, Any] = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=_UpperCamelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = PokerHand('''2C 4S AS 3D 5C''' ) snake_case_ : str = True snake_case_ : Tuple = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def lowerCamelCase_ ( ) -> List[str]: """simple docstring""" snake_case_ : List[str] = 0 snake_case_ : Union[str, Any] = os.path.abspath(os.path.dirname(_UpperCamelCase ) ) snake_case_ : Dict = os.path.join(_UpperCamelCase , '''poker_hands.txt''' ) with open(_UpperCamelCase ) as file_hand: for line in file_hand: snake_case_ : Dict = line[:14].strip() snake_case_ : List[str] = line[15:].strip() snake_case_ , snake_case_ : str = PokerHand(_UpperCamelCase ), PokerHand(_UpperCamelCase ) snake_case_ : int = player.compare_with(_UpperCamelCase ) if output == "Win": answer += 1 assert answer == 376
279
0
'''simple docstring''' from collections import namedtuple A__: List[Any] = namedtuple('''from_to''', '''from_ to''') A__: Union[str, Any] = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.001, 1000), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.00_454, 264.172), '''cubicyard''': from_to(0.76_455, 1.30_795), '''cubicfoot''': from_to(0.028, 35.3_147), '''cup''': from_to(0.000_236_588, 4226.75), } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : str ,_UpperCAmelCase : str ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( F"Invalid \'from_type\' value: {from_type!r} Supported values are:\n" + """, """.join(_UpperCamelCase ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F"Invalid \'to_type\' value: {to_type!r}. Supported values are:\n" + """, """.join(_UpperCamelCase ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
276
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available lowerCAmelCase_ = logging.getLogger(__name__) @dataclass class __lowerCAmelCase : lowerCamelCase_ : str lowerCamelCase_ : List[str] lowerCamelCase_ : Optional[List[str]] @dataclass class __lowerCAmelCase : lowerCamelCase_ : List[int] lowerCamelCase_ : List[int] lowerCamelCase_ : Optional[List[int]] = None lowerCamelCase_ : Optional[List[int]] = None class __lowerCAmelCase ( _a ): lowerCamelCase_ : str = '''train''' lowerCamelCase_ : List[str] = '''dev''' lowerCamelCase_ : List[Any] = '''test''' class __lowerCAmelCase : @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def lowerCamelCase (__magic_name__ ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=False , __magic_name__="[CLS]" , __magic_name__=1 , __magic_name__="[SEP]" , __magic_name__=False , __magic_name__=False , __magic_name__=0 , __magic_name__=0 , __magic_name__=-100 , __magic_name__=0 , __magic_name__=True , ) -> List[InputFeatures]: '''simple docstring''' snake_case_ : Optional[int] = {label: i for i, label in enumerate(__magic_name__ )} snake_case_ : Dict = [] for ex_index, example in enumerate(__magic_name__ ): if ex_index % 1_0000 == 0: logger.info('''Writing example %d of %d''' , __magic_name__ , len(__magic_name__ ) ) snake_case_ : List[str] = [] snake_case_ : List[str] = [] for word, label in zip(example.words , example.labels ): snake_case_ : Optional[Any] = tokenizer.tokenize(__magic_name__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(__magic_name__ ) > 0: tokens.extend(__magic_name__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__magic_name__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. snake_case_ : Union[str, Any] = tokenizer.num_special_tokens_to_add() if len(__magic_name__ ) > max_seq_length - special_tokens_count: snake_case_ : str = tokens[: (max_seq_length - special_tokens_count)] snake_case_ : Any = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] snake_case_ : Union[str, Any] = [sequence_a_segment_id] * len(__magic_name__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: snake_case_ : Union[str, Any] = [cls_token] + tokens snake_case_ : List[Any] = [pad_token_label_id] + label_ids snake_case_ : Optional[Any] = [cls_token_segment_id] + segment_ids snake_case_ : Optional[Any] = tokenizer.convert_tokens_to_ids(__magic_name__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. snake_case_ : int = [1 if mask_padding_with_zero else 0] * len(__magic_name__ ) # Zero-pad up to the sequence length. snake_case_ : Optional[int] = max_seq_length - len(__magic_name__ ) if pad_on_left: snake_case_ : Optional[Any] = ([pad_token] * padding_length) + input_ids snake_case_ : Optional[int] = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask snake_case_ : Optional[Any] = ([pad_token_segment_id] * padding_length) + segment_ids snake_case_ : Dict = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(__magic_name__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(__magic_name__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: snake_case_ : int = None features.append( InputFeatures( input_ids=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , label_ids=__magic_name__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[InputFeatures] lowerCamelCase_ : int = nn.CrossEntropyLoss().ignore_index def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=False , __magic_name__ = Split.train , ) -> Union[str, Any]: '''simple docstring''' snake_case_ : List[str] = os.path.join( __magic_name__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(__magic_name__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case_ : Dict = cached_features_file + '''.lock''' with FileLock(__magic_name__ ): if os.path.exists(__magic_name__ ) and not overwrite_cache: logger.info(F'''Loading features from cached file {cached_features_file}''' ) snake_case_ : Dict = torch.load(__magic_name__ ) else: logger.info(F'''Creating features from dataset file at {data_dir}''' ) snake_case_ : Any = token_classification_task.read_examples_from_file(__magic_name__ , __magic_name__ ) # TODO clean up all this to leverage built-in features of tokenizers snake_case_ : int = token_classification_task.convert_examples_to_features( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , __magic_name__ ) def __len__(self ) -> Optional[Any]: '''simple docstring''' return len(self.features ) def __getitem__(self , __magic_name__ ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class __lowerCAmelCase : lowerCamelCase_ : List[InputFeatures] lowerCamelCase_ : int = -100 def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=False , __magic_name__ = Split.train , ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[int] = token_classification_task.read_examples_from_file(__magic_name__ , __magic_name__ ) # TODO clean up all this to leverage built-in features of tokenizers snake_case_ : int = token_classification_task.convert_examples_to_features( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: snake_case_ : Optional[Any] = tf.data.Dataset.from_generator( __magic_name__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: snake_case_ : int = tf.data.Dataset.from_generator( __magic_name__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__(self ) -> str: '''simple docstring''' return len(self.features ) def __getitem__(self , __magic_name__ ) -> InputFeatures: '''simple docstring''' return self.features[i]
279
0
"""simple docstring""" import math from datetime import datetime, timedelta def lowercase (_lowerCAmelCase ): __lowerCAmelCase = year % 19 __lowerCAmelCase = year % 4 __lowerCAmelCase = year % 7 __lowerCAmelCase = math.floor(year / 100 ) __lowerCAmelCase = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCAmelCase = leap_day_inhibits / 4 __lowerCAmelCase = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCAmelCase = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCAmelCase = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCAmelCase = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(_UpperCamelCase , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(_UpperCamelCase , 4 , 18 ) else: return datetime(_UpperCamelCase , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_994, 2_000, 2_010, 2_021, 2_023): SCREAMING_SNAKE_CASE_ = '''will be''' if year > datetime.now().year else '''was''' print(F"Easter in {year} {tense} {gauss_easter(year)}")
301
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir('''fixtures/test_sentencepiece_bpe_char.model''') @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[int] = SpeechTaTokenizer lowerCamelCase_ : int = False lowerCamelCase_ : Dict = True def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing snake_case_ : Tuple = SpeechTaTokenizer(__magic_name__ ) snake_case_ : Any = AddedToken('''<mask>''' , lstrip=__magic_name__ , rstrip=__magic_name__ ) snake_case_ : int = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Dict = '''this is a test''' snake_case_ : int = '''this is a test''' return input_text, output_text def lowerCamelCase (self , __magic_name__ , __magic_name__=False , __magic_name__=20 , __magic_name__=5 ) -> List[Any]: '''simple docstring''' snake_case_ , snake_case_ : int = self.get_input_output_texts(__magic_name__ ) snake_case_ : Optional[Any] = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) snake_case_ : Any = tokenizer.decode(__magic_name__ , clean_up_tokenization_spaces=__magic_name__ ) return text, ids def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[str] = '''<pad>''' snake_case_ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__magic_name__ ) , 81 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : int = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): snake_case_ : int = tokenizer.vocab_size snake_case_ : Optional[Any] = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case_ : List[Any] = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] snake_case_ : List[Any] = tokenizer.add_tokens(__magic_name__ ) snake_case_ : Dict = tokenizer.vocab_size snake_case_ : Optional[Any] = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size + len(__magic_name__ ) ) snake_case_ : Union[str, Any] = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case_ : Union[str, Any] = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} snake_case_ : List[str] = tokenizer.add_special_tokens(__magic_name__ ) snake_case_ : Dict = tokenizer.vocab_size snake_case_ : Dict = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size_a + len(__magic_name__ ) ) snake_case_ : Tuple = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> List[str]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.get_tokenizer() snake_case_ : Optional[Any] = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__magic_name__ , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case_ : List[Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) snake_case_ : List[str] = tokenizer.convert_tokens_to_ids(__magic_name__ ) # fmt: off self.assertListEqual(__magic_name__ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case_ : int = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Tuple = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off snake_case_ : List[Any] = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__magic_name__ , )
279
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/config.json""", """umberto-commoncrawl-cased-v1""": ( """https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json""" ), """umberto-wikipedia-uncased-v1""": ( """https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json""" ), } class UpperCamelCase__ ( _a ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''camembert''' def __init__( self : Tuple , lowerCamelCase_ : Union[str, Any]=3_05_22 , lowerCamelCase_ : Optional[Any]=7_68 , lowerCamelCase_ : Union[str, Any]=12 , lowerCamelCase_ : Any=12 , lowerCamelCase_ : Union[str, Any]=30_72 , lowerCamelCase_ : Optional[Any]="gelu" , lowerCamelCase_ : Optional[int]=0.1 , lowerCamelCase_ : List[Any]=0.1 , lowerCamelCase_ : Dict=5_12 , lowerCamelCase_ : List[str]=2 , lowerCamelCase_ : Optional[int]=0.02 , lowerCamelCase_ : Union[str, Any]=1e-12 , lowerCamelCase_ : Optional[Any]=1 , lowerCamelCase_ : Optional[int]=0 , lowerCamelCase_ : List[str]=2 , lowerCamelCase_ : Optional[Any]="absolute" , lowerCamelCase_ : Dict=True , lowerCamelCase_ : int=None , **lowerCamelCase_ : Union[str, Any] , ): '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : int = hidden_size SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE : Tuple = num_attention_heads SCREAMING_SNAKE_CASE : Any = hidden_act SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : List[str] = type_vocab_size SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : Dict = layer_norm_eps SCREAMING_SNAKE_CASE : int = position_embedding_type SCREAMING_SNAKE_CASE : int = use_cache SCREAMING_SNAKE_CASE : Optional[Any] = classifier_dropout class UpperCamelCase__ ( _a ): """simple docstring""" @property def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' if self.task == "multiple-choice": SCREAMING_SNAKE_CASE : Any = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: SCREAMING_SNAKE_CASE : List[str] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
323
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' ) for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): if dist[i][j] != float('''inf''' ): print(int(dist[i][j] ) , end='''\t''' ) else: print('''INF''' , end='''\t''' ) print() def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : int = [[float('''inf''' ) for _ in range(_UpperCamelCase )] for _ in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): snake_case_ : Dict = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(_UpperCamelCase ): # looping through rows of graph array for i in range(_UpperCamelCase ): # looping through columns of graph array for j in range(_UpperCamelCase ): if ( dist[i][k] != float('''inf''' ) and dist[k][j] != float('''inf''' ) and dist[i][k] + dist[k][j] < dist[i][j] ): snake_case_ : List[Any] = dist[i][k] + dist[k][j] _print_dist(_UpperCamelCase , _UpperCamelCase ) return dist, v if __name__ == "__main__": lowerCAmelCase_ = int(input('''Enter number of vertices: ''')) lowerCAmelCase_ = int(input('''Enter number of edges: ''')) lowerCAmelCase_ = [[float('''inf''') for i in range(v)] for j in range(v)] for i in range(v): lowerCAmelCase_ = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print('''\nEdge ''', i + 1) lowerCAmelCase_ = int(input('''Enter source:''')) lowerCAmelCase_ = int(input('''Enter destination:''')) lowerCAmelCase_ = float(input('''Enter weight:''')) lowerCAmelCase_ = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
279
0
"""simple docstring""" import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger __SCREAMING_SNAKE_CASE =get_logger(__name__) class UpperCamelCase : def __init__( self ,__UpperCamelCase = None ) -> Tuple: '''simple docstring''' lowercase_ : Dict = ( os.path.join(__UpperCamelCase ,config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) lowercase_ : int = Extractor def _UpperCAmelCase ( self ,__UpperCamelCase ) -> str: '''simple docstring''' from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" lowercase_ : Optional[int] = os.path.abspath(__UpperCamelCase ) return os.path.join(self.extract_dir ,hash_url_to_filename(__UpperCamelCase ) ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> bool: '''simple docstring''' return force_extract or ( not os.path.isfile(__UpperCamelCase ) and not (os.path.isdir(__UpperCamelCase ) and os.listdir(__UpperCamelCase )) ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase = False ) -> str: '''simple docstring''' lowercase_ : Optional[int] = self.extractor.infer_extractor_format(__UpperCamelCase ) if not extractor_format: return input_path lowercase_ : Optional[int] = self._get_output_path(__UpperCamelCase ) if self._do_extract(__UpperCamelCase ,__UpperCamelCase ): self.extractor.extract(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) return output_path class UpperCamelCase ( _a ): @classmethod @abstractmethod def _UpperCAmelCase ( cls ,__UpperCamelCase ,**__UpperCamelCase ) -> bool: '''simple docstring''' ... @staticmethod @abstractmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: '''simple docstring''' ... class UpperCamelCase ( _a , _a ): lowercase = [] @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Optional[int]: '''simple docstring''' with open(__UpperCamelCase ,'rb' ) as f: return f.read(__UpperCamelCase ) @classmethod def _UpperCAmelCase ( cls ,__UpperCamelCase ,__UpperCamelCase = b"" ) -> bool: '''simple docstring''' if not magic_number: lowercase_ : Dict = max(len(__UpperCamelCase ) for cls_magic_number in cls.magic_numbers ) try: lowercase_ : List[str] = cls.read_magic_number(__UpperCamelCase ,__UpperCamelCase ) except OSError: return False return any(magic_number.startswith(__UpperCamelCase ) for cls_magic_number in cls.magic_numbers ) class UpperCamelCase ( _a ): @classmethod def _UpperCAmelCase ( cls ,__UpperCamelCase ,**__UpperCamelCase ) -> bool: '''simple docstring''' return tarfile.is_tarfile(__UpperCamelCase ) @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Dict: '''simple docstring''' def resolved(__UpperCamelCase ) -> str: return os.path.realpath(os.path.abspath(__UpperCamelCase ) ) def badpath(__UpperCamelCase ,__UpperCamelCase ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(__UpperCamelCase ,__UpperCamelCase ) ).startswith(__UpperCamelCase ) def badlink(__UpperCamelCase ,__UpperCamelCase ) -> bool: # Links are interpreted relative to the directory containing the link lowercase_ : Optional[Any] = resolved(os.path.join(__UpperCamelCase ,os.path.dirname(info.name ) ) ) return badpath(info.linkname ,base=__UpperCamelCase ) lowercase_ : Optional[Any] = resolved(__UpperCamelCase ) for finfo in members: if badpath(finfo.name ,__UpperCamelCase ): logger.error(f'''Extraction of {finfo.name} is blocked (illegal path)''' ) elif finfo.issym() and badlink(__UpperCamelCase ,__UpperCamelCase ): logger.error(f'''Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}''' ) elif finfo.islnk() and badlink(__UpperCamelCase ,__UpperCamelCase ): logger.error(f'''Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}''' ) else: yield finfo @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: '''simple docstring''' os.makedirs(__UpperCamelCase ,exist_ok=__UpperCamelCase ) lowercase_ : Optional[Any] = tarfile.open(__UpperCamelCase ) tar_file.extractall(__UpperCamelCase ,members=TarExtractor.safemembers(__UpperCamelCase ,__UpperCamelCase ) ) tar_file.close() class UpperCamelCase ( _a ): lowercase = [B'''\x1F\x8B'''] @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: '''simple docstring''' with gzip.open(__UpperCamelCase ,'rb' ) as gzip_file: with open(__UpperCamelCase ,'wb' ) as extracted_file: shutil.copyfileobj(__UpperCamelCase ,__UpperCamelCase ) class UpperCamelCase ( _a ): lowercase = [ B'''PK\x03\x04''', B'''PK\x05\x06''', # empty archive B'''PK\x07\x08''', # spanned archive ] @classmethod def _UpperCAmelCase ( cls ,__UpperCamelCase ,__UpperCamelCase = b"" ) -> bool: '''simple docstring''' if super().is_extractable(__UpperCamelCase ,magic_number=__UpperCamelCase ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(__UpperCamelCase ,'rb' ) as fp: lowercase_ : int = _EndRecData(__UpperCamelCase ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: lowercase_ : Optional[int] = fp.read(__UpperCamelCase ) # CD is where we expect it to be if len(__UpperCamelCase ) == sizeCentralDir: lowercase_ : Any = struct.unpack(__UpperCamelCase ,__UpperCamelCase ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: '''simple docstring''' os.makedirs(__UpperCamelCase ,exist_ok=__UpperCamelCase ) with zipfile.ZipFile(__UpperCamelCase ,'r' ) as zip_file: zip_file.extractall(__UpperCamelCase ) zip_file.close() class UpperCamelCase ( _a ): lowercase = [B'''\xFD\x37\x7A\x58\x5A\x00'''] @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: '''simple docstring''' with lzma.open(__UpperCamelCase ) as compressed_file: with open(__UpperCamelCase ,'wb' ) as extracted_file: shutil.copyfileobj(__UpperCamelCase ,__UpperCamelCase ) class UpperCamelCase ( _a ): lowercase = [B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00'''] # RAR_ID # RAR5_ID @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: '''simple docstring''' if not config.RARFILE_AVAILABLE: raise ImportError('Please pip install rarfile' ) import rarfile os.makedirs(__UpperCamelCase ,exist_ok=__UpperCamelCase ) lowercase_ : List[Any] = rarfile.RarFile(__UpperCamelCase ) rf.extractall(__UpperCamelCase ) rf.close() class UpperCamelCase ( _a ): lowercase = [B'''\x28\xb5\x2F\xFD'''] @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: '''simple docstring''' if not config.ZSTANDARD_AVAILABLE: raise ImportError('Please pip install zstandard' ) import zstandard as zstd lowercase_ : Optional[Any] = zstd.ZstdDecompressor() with open(__UpperCamelCase ,'rb' ) as ifh, open(__UpperCamelCase ,'wb' ) as ofh: dctx.copy_stream(__UpperCamelCase ,__UpperCamelCase ) class UpperCamelCase ( _a ): lowercase = [B'''\x42\x5A\x68'''] @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: '''simple docstring''' with bza.open(__UpperCamelCase ,'rb' ) as compressed_file: with open(__UpperCamelCase ,'wb' ) as extracted_file: shutil.copyfileobj(__UpperCamelCase ,__UpperCamelCase ) class UpperCamelCase ( _a ): lowercase = [B'''\x37\x7A\xBC\xAF\x27\x1C'''] @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: '''simple docstring''' if not config.PY7ZR_AVAILABLE: raise ImportError('Please pip install py7zr' ) import pyazr os.makedirs(__UpperCamelCase ,exist_ok=__UpperCamelCase ) with pyazr.SevenZipFile(__UpperCamelCase ,'r' ) as archive: archive.extractall(__UpperCamelCase ) class UpperCamelCase ( _a ): lowercase = [B'''\x04\x22\x4D\x18'''] @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> None: '''simple docstring''' if not config.LZ4_AVAILABLE: raise ImportError('Please pip install lz4' ) import lza.frame with lza.frame.open(__UpperCamelCase ,'rb' ) as compressed_file: with open(__UpperCamelCase ,'wb' ) as extracted_file: shutil.copyfileobj(__UpperCamelCase ,__UpperCamelCase ) class UpperCamelCase : # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip) lowercase = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def _UpperCAmelCase ( cls ) -> Any: '''simple docstring''' return max( len(__UpperCamelCase ) for extractor in cls.extractors.values() if issubclass(__UpperCamelCase ,__UpperCamelCase ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def _UpperCAmelCase ( __UpperCamelCase ,__UpperCamelCase ) -> Tuple: '''simple docstring''' try: return MagicNumberBaseExtractor.read_magic_number(__UpperCamelCase ,magic_number_length=__UpperCamelCase ) except OSError: return b"" @classmethod def _UpperCAmelCase ( cls ,__UpperCamelCase ,__UpperCamelCase = False ) -> bool: '''simple docstring''' warnings.warn( 'Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. ' 'Use \'infer_extractor_format\' instead.' ,category=__UpperCamelCase ,) lowercase_ : Any = cls.infer_extractor_format(__UpperCamelCase ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def _UpperCAmelCase ( cls ,__UpperCamelCase ) -> str: # <Added version="2.4.0"/> '''simple docstring''' lowercase_ : Optional[int] = cls._get_magic_number_max_length() lowercase_ : Optional[int] = cls._read_magic_number(__UpperCamelCase ,__UpperCamelCase ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(__UpperCamelCase ,magic_number=__UpperCamelCase ): return extractor_format @classmethod def _UpperCAmelCase ( cls ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase = None ,__UpperCamelCase = "deprecated" ,) -> None: '''simple docstring''' os.makedirs(os.path.dirname(__UpperCamelCase ) ,exist_ok=__UpperCamelCase ) # Prevent parallel extractions lowercase_ : Tuple = str(Path(__UpperCamelCase ).with_suffix('.lock' ) ) with FileLock(__UpperCamelCase ): shutil.rmtree(__UpperCamelCase ,ignore_errors=__UpperCamelCase ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(__UpperCamelCase ,__UpperCamelCase ): # passed as positional arg warnings.warn( 'Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. ' 'Use \'extractor_format\' instead.' ,category=__UpperCamelCase ,) lowercase_ : Optional[int] = extractor if extractor != '''deprecated''' else extractor_format else: lowercase_ : Any = cls.extractors[extractor_format] return extractor.extract(__UpperCamelCase ,__UpperCamelCase ) else: warnings.warn( 'Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an ' 'exception in 3.0.0.' ,category=__UpperCamelCase ,) for extractor in cls.extractors.values(): if extractor.is_extractable(__UpperCamelCase ): return extractor.extract(__UpperCamelCase ,__UpperCamelCase )
213
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class __lowerCAmelCase : def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' return None class __lowerCAmelCase : def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' return None class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Dict = [ # (model_name, model_kwargs) ('''bert-base-cased''', {}), ('''gpt2''', {'''use_cache''': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__magic_name__ , '''tf''' , 12 , **__magic_name__ ) @require_torch @slow def lowerCamelCase (self ) -> int: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__magic_name__ , '''pt''' , 12 , **__magic_name__ ) @require_torch @slow def lowerCamelCase (self ) -> int: '''simple docstring''' from transformers import BertModel snake_case_ : str = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(__magic_name__ ) ) vocab_file.flush() snake_case_ : Optional[Any] = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: snake_case_ : str = BertModel(BertConfig(vocab_size=len(__magic_name__ ) ) ) model.save_pretrained(__magic_name__ ) self._test_export(__magic_name__ , '''pt''' , 12 , __magic_name__ ) @require_tf @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ : Tuple = self._test_export(__magic_name__ , '''tf''' , 12 , **__magic_name__ ) snake_case_ : List[str] = quantize(Path(__magic_name__ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__magic_name__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ : Any = self._test_export(__magic_name__ , '''pt''' , 12 , **__magic_name__ ) snake_case_ : Any = quantize(__magic_name__ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__magic_name__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None , **__magic_name__ ) -> Tuple: '''simple docstring''' try: # Compute path with TemporaryDirectory() as tempdir: snake_case_ : List[str] = Path(__magic_name__ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) return path except Exception as e: self.fail(__magic_name__ ) @require_torch @require_tokenizers @slow def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' from transformers import BertModel snake_case_ : Optional[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case_ : int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(__magic_name__ , __magic_name__ , '''pt''' ) @require_tf @require_tokenizers @slow def lowerCamelCase (self ) -> List[str]: '''simple docstring''' from transformers import TFBertModel snake_case_ : Any = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case_ : str = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(__magic_name__ , __magic_name__ , '''tf''' ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : Tuple = FeatureExtractionPipeline(__magic_name__ , __magic_name__ ) snake_case_ : Optional[int] = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] snake_case_ , snake_case_ , snake_case_ , snake_case_ : Optional[int] = infer_shapes(__magic_name__ , __magic_name__ ) # Assert all variables are present self.assertEqual(len(__magic_name__ ) , len(__magic_name__ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __magic_name__ ) self.assertSequenceEqual(variable_names[3:] , __magic_name__ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Tuple = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] snake_case_ : List[str] = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} snake_case_ , snake_case_ : Tuple = ensure_valid_input(FuncContiguousArgs() , __magic_name__ , __magic_name__ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__magic_name__ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__magic_name__ ) , set(__magic_name__ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__magic_name__ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) snake_case_ , snake_case_ : Dict = ensure_valid_input(FuncNonContiguousArgs() , __magic_name__ , __magic_name__ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Optional[int] = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
279
0
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __snake_case ( unittest.TestCase ): def UpperCAmelCase__ ( self , snake_case__ ) -> List[Any]: '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): UpperCAmelCase : Dict =model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(snake_case__ ) def UpperCAmelCase__ ( self ) -> str: '''simple docstring''' UpperCAmelCase : str ='''sshleifer/tiny-gpt2''' UpperCAmelCase : List[Any] =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=snake_case__ , ) UpperCAmelCase : Any =PyTorchBenchmark(snake_case__ ) UpperCAmelCase : Tuple =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self ) -> Dict: '''simple docstring''' UpperCAmelCase : Tuple ='''sgugger/tiny-distilbert-classification''' UpperCAmelCase : Optional[Any] =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=snake_case__ , only_pretrain_model=snake_case__ , ) UpperCAmelCase : List[str] =PyTorchBenchmark(snake_case__ ) UpperCAmelCase : Union[str, Any] =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self ) -> Tuple: '''simple docstring''' UpperCAmelCase : int ='''sshleifer/tiny-gpt2''' UpperCAmelCase : Union[str, Any] =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , torchscript=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=snake_case__ , ) UpperCAmelCase : int =PyTorchBenchmark(snake_case__ ) UpperCAmelCase : List[str] =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def UpperCAmelCase__ ( self ) -> Dict: '''simple docstring''' UpperCAmelCase : Optional[int] ='''sshleifer/tiny-gpt2''' UpperCAmelCase : Optional[int] =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , fpaa=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=snake_case__ , ) UpperCAmelCase : int =PyTorchBenchmark(snake_case__ ) UpperCAmelCase : Optional[Any] =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' UpperCAmelCase : str ='''sshleifer/tiny-gpt2''' UpperCAmelCase : Any =AutoConfig.from_pretrained(snake_case__ ) # set architectures equal to `None` UpperCAmelCase : Optional[Any] =None UpperCAmelCase : str =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=snake_case__ , ) UpperCAmelCase : List[str] =PyTorchBenchmark(snake_case__ , configs=[config] ) UpperCAmelCase : Union[str, Any] =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' UpperCAmelCase : List[str] ='''sshleifer/tiny-gpt2''' UpperCAmelCase : str =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=snake_case__ , ) UpperCAmelCase : List[Any] =PyTorchBenchmark(snake_case__ ) UpperCAmelCase : int =benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''' , '''Can\'t do half precision''' ) def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' UpperCAmelCase : Union[str, Any] ='''sshleifer/tiny-gpt2''' UpperCAmelCase : Optional[int] =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , fpaa=snake_case__ , multi_process=snake_case__ , ) UpperCAmelCase : List[Any] =PyTorchBenchmark(snake_case__ ) UpperCAmelCase : Optional[int] =benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCAmelCase__ ( self ) -> Dict: '''simple docstring''' UpperCAmelCase : Union[str, Any] ='''sshleifer/tiny-gpt2''' UpperCAmelCase : Union[str, Any] =AutoConfig.from_pretrained(snake_case__ ) UpperCAmelCase : Optional[int] =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=snake_case__ , ) UpperCAmelCase : Optional[int] =PyTorchBenchmark(snake_case__ , configs=[config] ) UpperCAmelCase : Optional[int] =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self ) -> Any: '''simple docstring''' UpperCAmelCase : Union[str, Any] ='''sshleifer/tinier_bart''' UpperCAmelCase : Any =AutoConfig.from_pretrained(snake_case__ ) UpperCAmelCase : Tuple =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=snake_case__ , ) UpperCAmelCase : Tuple =PyTorchBenchmark(snake_case__ , configs=[config] ) UpperCAmelCase : Tuple =benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self ) -> Tuple: '''simple docstring''' UpperCAmelCase : str ='''sshleifer/tiny-gpt2''' UpperCAmelCase : Dict =AutoConfig.from_pretrained(snake_case__ ) UpperCAmelCase : List[str] =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=snake_case__ , ) UpperCAmelCase : Union[str, Any] =PyTorchBenchmark(snake_case__ , configs=[config] ) UpperCAmelCase : Optional[int] =benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCAmelCase__ ( self ) -> Tuple: '''simple docstring''' UpperCAmelCase : Optional[int] ='''sshleifer/tinier_bart''' UpperCAmelCase : Union[str, Any] =AutoConfig.from_pretrained(snake_case__ ) UpperCAmelCase : str =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=snake_case__ , ) UpperCAmelCase : List[Any] =PyTorchBenchmark(snake_case__ , configs=[config] ) UpperCAmelCase : str =benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCAmelCase__ ( self ) -> List[str]: '''simple docstring''' UpperCAmelCase : int ='''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase : Optional[int] =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , save_to_csv=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(snake_case__ , '''inf_time.csv''' ) , train_memory_csv_file=os.path.join(snake_case__ , '''train_mem.csv''' ) , inference_memory_csv_file=os.path.join(snake_case__ , '''inf_mem.csv''' ) , train_time_csv_file=os.path.join(snake_case__ , '''train_time.csv''' ) , env_info_csv_file=os.path.join(snake_case__ , '''env.csv''' ) , multi_process=snake_case__ , ) UpperCAmelCase : List[str] =PyTorchBenchmark(snake_case__ ) benchmark.run() self.assertTrue(Path(os.path.join(snake_case__ , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(snake_case__ , '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(snake_case__ , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(snake_case__ , '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(snake_case__ , '''env.csv''' ) ).exists() ) def UpperCAmelCase__ ( self ) -> List[str]: '''simple docstring''' UpperCAmelCase : str ='''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(snake_case__ ): self.assertTrue(hasattr(snake_case__ , '''sequential''' ) ) self.assertTrue(hasattr(snake_case__ , '''cumulative''' ) ) self.assertTrue(hasattr(snake_case__ , '''current''' ) ) self.assertTrue(hasattr(snake_case__ , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase : Dict =PyTorchBenchmarkArguments( models=[MODEL_ID] , training=snake_case__ , inference=snake_case__ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(snake_case__ , '''log.txt''' ) , log_print=snake_case__ , trace_memory_line_by_line=snake_case__ , multi_process=snake_case__ , ) UpperCAmelCase : Union[str, Any] =PyTorchBenchmark(snake_case__ ) UpperCAmelCase : Union[str, Any] =benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(snake_case__ , '''log.txt''' ) ).exists() )
348
lowerCAmelCase_ = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.602_176_634e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.355_818, } def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: snake_case_ : str = ( f'''Incorrect \'from_type\' or \'to_type\' value: {from_type!r}, {to_type!r}\n''' f'''Valid values are: {", ".join(_UpperCamelCase )}''' ) raise ValueError(_UpperCamelCase ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
279
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Optional[int] = logging.get_logger(__name__) a__ : str = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class UpperCamelCase__ ( _a): UpperCAmelCase__ : Any = '''megatron-bert''' def __init__( self :int , _A :List[Any]=29_056 , _A :Optional[int]=1_024 , _A :Optional[int]=24 , _A :Any=16 , _A :List[Any]=4_096 , _A :str="gelu" , _A :str=0.1 , _A :Tuple=0.1 , _A :List[str]=512 , _A :int=2 , _A :List[str]=0.02 , _A :str=1E-12 , _A :str=0 , _A :Optional[Any]="absolute" , _A :Tuple=True , **_A :Any , ) -> Any: '''simple docstring''' super().__init__(pad_token_id=_A , **_A ) __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = hidden_act __A = intermediate_size __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = initializer_range __A = layer_norm_eps __A = position_embedding_type __A = use_cache
161
import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets lowerCAmelCase_ = datasets.logging.get_logger(__name__) lowerCAmelCase_ = '''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } ''' lowerCAmelCase_ = '''\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project\'s README at https://github.com/google-research/bleurt#readme for more information. ''' lowerCAmelCase_ = ''' BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: \'scores\': List of scores. Examples: >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> bleurt = datasets.load_metric("bleurt") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results["scores"]]) [1.03, 1.04] ''' lowerCAmelCase_ = { '''bleurt-tiny-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip''', '''bleurt-tiny-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip''', '''bleurt-base-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip''', '''bleurt-base-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip''', '''bleurt-large-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip''', '''bleurt-large-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip''', '''BLEURT-20-D3''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip''', '''BLEURT-20-D6''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip''', '''BLEURT-20-D12''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip''', '''BLEURT-20''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip''', } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/google-research/bleurt''' , 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/bleurt'''] , reference_urls=['''https://github.com/google-research/bleurt''', '''https://arxiv.org/abs/2004.04696'''] , ) def lowerCamelCase (self , __magic_name__ ) -> List[Any]: '''simple docstring''' if self.config_name == "default": logger.warning( '''Using default BLEURT-Base checkpoint for sequence maximum length 128. ''' '''You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').''' ) snake_case_ : Dict = '''bleurt-base-128''' if self.config_name.lower() in CHECKPOINT_URLS: snake_case_ : Optional[int] = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: snake_case_ : Union[str, Any] = self.config_name.upper() else: raise KeyError( F'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}''' ) # download the model checkpoint specified by self.config_name and set up the scorer snake_case_ : Any = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) snake_case_ : Dict = score.BleurtScorer(os.path.join(__magic_name__ , __magic_name__ ) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Dict = self.scorer.score(references=__magic_name__ , candidates=__magic_name__ ) return {"scores": scores}
279
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__( _a , _a , _a , unittest.TestCase ): """simple docstring""" a :Tuple = StableDiffusionInpaintPipeline a :Tuple = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS a :str = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS a :str = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess a :Union[str, Any] = frozenset([] ) def _lowercase ( self : List[str] ) -> List[str]: torch.manual_seed(0 ) lowercase_ = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=9 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=3_2 , attention_head_dim=(2, 4) , use_linear_projection=SCREAMING_SNAKE_CASE_ , ) lowercase_ = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) lowercase_ = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowercase_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='''gelu''' , projection_dim=5_1_2 , ) lowercase_ = CLIPTextModel(SCREAMING_SNAKE_CASE_ ) lowercase_ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) lowercase_ = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str=0 ) -> Optional[Any]: lowercase_ = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(SCREAMING_SNAKE_CASE_ ) ).to(SCREAMING_SNAKE_CASE_ ) lowercase_ = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowercase_ = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_ ) ).convert('''RGB''' ).resize((6_4, 6_4) ) lowercase_ = Image.fromarray(np.uinta(image + 4 ) ).convert('''RGB''' ).resize((6_4, 6_4) ) if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): lowercase_ = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: lowercase_ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) lowercase_ = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': init_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def _lowercase ( self : Dict ) -> Any: lowercase_ = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowercase_ = self.get_dummy_components() lowercase_ = StableDiffusionInpaintPipeline(**SCREAMING_SNAKE_CASE_ ) lowercase_ = sd_pipe.to(SCREAMING_SNAKE_CASE_ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) lowercase_ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) lowercase_ = sd_pipe(**SCREAMING_SNAKE_CASE_ ).images lowercase_ = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) lowercase_ = np.array([0.47_27, 0.57_35, 0.39_41, 0.54_46, 0.59_26, 0.43_94, 0.50_62, 0.46_54, 0.44_76] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _lowercase ( self : Any ) -> List[Any]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class lowercase__( unittest.TestCase ): """simple docstring""" def _lowercase ( self : List[str] ) -> List[str]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase ( self : Optional[int] ) -> Dict: lowercase_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) lowercase_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) lowercase_ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench.npy''' ) lowercase_ = '''stabilityai/stable-diffusion-2-inpainting''' lowercase_ = StableDiffusionInpaintPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing() lowercase_ = '''Face of a yellow cat, high resolution, sitting on a park bench''' lowercase_ = torch.manual_seed(0 ) lowercase_ = pipe( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , output_type='''np''' , ) lowercase_ = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 9e-3 def _lowercase ( self : Dict ) -> Optional[int]: lowercase_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) lowercase_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) lowercase_ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench_fp16.npy''' ) lowercase_ = '''stabilityai/stable-diffusion-2-inpainting''' lowercase_ = StableDiffusionInpaintPipeline.from_pretrained( SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa , safety_checker=SCREAMING_SNAKE_CASE_ , ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing() lowercase_ = '''Face of a yellow cat, high resolution, sitting on a park bench''' lowercase_ = torch.manual_seed(0 ) lowercase_ = pipe( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , output_type='''np''' , ) lowercase_ = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 5e-1 def _lowercase ( self : str ) -> Any: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() lowercase_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) lowercase_ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) lowercase_ = '''stabilityai/stable-diffusion-2-inpainting''' lowercase_ = PNDMScheduler.from_pretrained(SCREAMING_SNAKE_CASE_ , subfolder='''scheduler''' ) lowercase_ = StableDiffusionInpaintPipeline.from_pretrained( SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , torch_dtype=torch.floataa , ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() lowercase_ = '''Face of a yellow cat, high resolution, sitting on a park bench''' lowercase_ = torch.manual_seed(0 ) lowercase_ = pipe( prompt=SCREAMING_SNAKE_CASE_ , image=SCREAMING_SNAKE_CASE_ , mask_image=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=2 , output_type='''np''' , ) lowercase_ = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 1_0**9
30
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''): lowerCAmelCase_ = { '''linear''': PIL.Image.Resampling.BILINEAR, '''bilinear''': PIL.Image.Resampling.BILINEAR, '''bicubic''': PIL.Image.Resampling.BICUBIC, '''lanczos''': PIL.Image.Resampling.LANCZOS, '''nearest''': PIL.Image.Resampling.NEAREST, } else: lowerCAmelCase_ = { '''linear''': PIL.Image.LINEAR, '''bilinear''': PIL.Image.BILINEAR, '''bicubic''': PIL.Image.BICUBIC, '''lanczos''': PIL.Image.LANCZOS, '''nearest''': PIL.Image.NEAREST, } def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : Dict = (images / 2 + 0.5).clamp(0 , 1 ) snake_case_ : Dict = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() snake_case_ : int = numpy_to_pil(_UpperCamelCase ) return images def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" if images.ndim == 3: snake_case_ : Optional[Any] = images[None, ...] snake_case_ : Any = (images * 255).round().astype('''uint8''' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images snake_case_ : str = [Image.fromarray(image.squeeze() , mode='''L''' ) for image in images] else: snake_case_ : List[Any] = [Image.fromarray(_UpperCamelCase ) for image in images] return pil_images
279
0
import math def a__ ( _UpperCamelCase : List[Any] ): __lowerCamelCase = [True] * n __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __lowerCamelCase = i * 2 while index < n: __lowerCamelCase = False __lowerCamelCase = index + i __lowerCamelCase = [2] for i in range(3 ,_UpperCamelCase ,2 ): if is_prime[i]: primes.append(_UpperCamelCase ) return primes def a__ ( _UpperCamelCase : List[Any] = 99_99_66_66_33_33 ): __lowerCamelCase = math.floor(math.sqrt(_UpperCamelCase ) ) + 1_00 __lowerCamelCase = prime_sieve(_UpperCamelCase ) __lowerCamelCase = 0 __lowerCamelCase = 0 __lowerCamelCase = primes[prime_index] while (last_prime**2) <= limit: __lowerCamelCase = primes[prime_index + 1] __lowerCamelCase = last_prime**2 __lowerCamelCase = next_prime**2 # Get numbers divisible by lps(current) __lowerCamelCase = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __lowerCamelCase = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __lowerCamelCase = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __lowerCamelCase = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
330
import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Any = BioGptTokenizer lowerCamelCase_ : Optional[Any] = False def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case_ : Optional[Any] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] snake_case_ : Union[str, Any] = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) snake_case_ : Union[str, Any] = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] snake_case_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(__magic_name__ ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(__magic_name__ ) ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : str = '''lower newer''' snake_case_ : Dict = '''lower newer''' return input_text, output_text def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Optional[int] = BioGptTokenizer(self.vocab_file , self.merges_file ) snake_case_ : Union[str, Any] = '''lower''' snake_case_ : Optional[int] = ['''low''', '''er</w>'''] snake_case_ : Any = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) snake_case_ : Optional[int] = tokens + ['''<unk>'''] snake_case_ : List[str] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) @slow def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) snake_case_ : List[Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=__magic_name__ ) snake_case_ : str = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__magic_name__ ) snake_case_ : str = tokenizer.build_inputs_with_special_tokens(__magic_name__ ) snake_case_ : List[str] = tokenizer.build_inputs_with_special_tokens(__magic_name__ , __magic_name__ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
279
0
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): a_ : Dict = yaml.safe_load( "\\nname: \"\"\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: \"Dataset Card for X\" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: \"Table of Contents\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Dataset Description\"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: \"Dataset Summary\"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: \"Supported Tasks and Leaderboards\"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n" ) a_ : Any = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } a_ : List[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : Any = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : List[Any] = { "name": "root", "text": "", "is_empty_text": True, "subsections": [ { "name": "Dataset Card for My Dataset", "text": "", "is_empty_text": True, "subsections": [ {"name": "Table of Contents", "text": "Some text here.", "is_empty_text": False, "subsections": []}, { "name": "Dataset Description", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Dataset Summary", "text": "Some text here.", "is_empty_text": False, "subsections": [ { "name": "Extra Ignored Subsection", "text": "", "is_empty_text": True, "subsections": [], } ], }, { "name": "Supported Tasks and Leaderboards", "text": "", "is_empty_text": True, "subsections": [], }, {"name": "Languages", "text": "Language Text", "is_empty_text": False, "subsections": []}, ], }, ], } ], } a_ : List[str] = "\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : str = ( "The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README." ) a_ : Tuple = "\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : Dict = ( "The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README." ) a_ : int = "\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : Optional[int] = "The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README." a_ : Any = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored)." a_ : Tuple = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n" a_ : str = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'." a_ : Union[str, Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n" a_ : Tuple = "The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`." a_ : Any = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n" a_ : int = "The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty." a_ : Any = "\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : Union[str, Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README." a_ : str = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n" a_ : List[Any] = "The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README." a_ : int = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : Any = "The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README." a_ : Tuple = "" a_ : List[str] = "The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README." a_ : Optional[Any] = "\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n" a_ : Any = "The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections." @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def _A (lowerCAmelCase__ :Dict , lowerCAmelCase__ :Dict ) -> List[str]: '''simple docstring''' assert ReadMe.from_string(_UpperCamelCase , _UpperCamelCase ).to_dict() == expected_dict @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def _A (lowerCAmelCase__ :Optional[int] , lowerCAmelCase__ :List[Any] ) -> Union[str, Any]: '''simple docstring''' with pytest.raises(_UpperCamelCase , match=re.escape(expected_error.format(path='root' ) ) ): _a = ReadMe.from_string(_UpperCamelCase , _UpperCamelCase ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def _A (lowerCAmelCase__ :Dict , lowerCAmelCase__ :Union[str, Any] ) -> Dict: '''simple docstring''' with pytest.raises(_UpperCamelCase , match=re.escape(expected_error.format(path='root' ) ) ): ReadMe.from_string(_UpperCamelCase , _UpperCamelCase ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def _A (lowerCAmelCase__ :Tuple ) -> List[str]: '''simple docstring''' ReadMe.from_string(_UpperCamelCase , _UpperCamelCase , suppress_parsing_errors=_UpperCamelCase ) @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def _A (lowerCAmelCase__ :List[Any] , lowerCAmelCase__ :Optional[Any] ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _a = Path(_UpperCamelCase ) / '''README.md''' with open(_UpperCamelCase , 'w+' ) as readme_file: readme_file.write(_UpperCamelCase ) _a = ReadMe.from_readme(_UpperCamelCase , _UpperCamelCase ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def _A (lowerCAmelCase__ :str , lowerCAmelCase__ :List[Any] ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _a = Path(_UpperCamelCase ) / '''README.md''' with open(_UpperCamelCase , 'w+' ) as readme_file: readme_file.write(_UpperCamelCase ) _a = expected_error.format(path=_UpperCamelCase ) with pytest.raises(_UpperCamelCase , match=re.escape(_UpperCamelCase ) ): _a = ReadMe.from_readme(_UpperCamelCase , _UpperCamelCase ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def _A (lowerCAmelCase__ :List[Any] , lowerCAmelCase__ :Any ) -> Optional[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _a = Path(_UpperCamelCase ) / '''README.md''' with open(_UpperCamelCase , 'w+' ) as readme_file: readme_file.write(_UpperCamelCase ) _a = expected_error.format(path=_UpperCamelCase ) with pytest.raises(_UpperCamelCase , match=re.escape(_UpperCamelCase ) ): ReadMe.from_readme(_UpperCamelCase , _UpperCamelCase ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def _A (lowerCAmelCase__ :Union[str, Any] ) -> Tuple: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _a = Path(_UpperCamelCase ) / '''README.md''' with open(_UpperCamelCase , 'w+' ) as readme_file: readme_file.write(_UpperCamelCase ) ReadMe.from_readme(_UpperCamelCase , _UpperCamelCase , suppress_parsing_errors=_UpperCamelCase )
168
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> tuple[float, list[float]]: """simple docstring""" snake_case_ : Dict = list(range(len(_UpperCamelCase ) ) ) snake_case_ : Dict = [v / w for v, w in zip(_UpperCamelCase , _UpperCamelCase )] index.sort(key=lambda _UpperCamelCase : ratio[i] , reverse=_UpperCamelCase ) snake_case_ : float = 0 snake_case_ : list[float] = [0] * len(_UpperCamelCase ) for i in index: if weight[i] <= capacity: snake_case_ : Dict = 1 max_value += value[i] capacity -= weight[i] else: snake_case_ : Union[str, Any] = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
279
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class SCREAMING_SNAKE_CASE ( _a ): __lowerCamelCase : List[Any] ='''facebook/bart-large-mnli''' __lowerCamelCase : str =( '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ''' '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. ''' '''It returns the most likely label in the list of provided `labels` for the input text.''' ) __lowerCamelCase : Optional[int] ='''text_classifier''' __lowerCamelCase : Optional[Any] =AutoTokenizer __lowerCamelCase : List[str] =AutoModelForSequenceClassification __lowerCamelCase : List[Any] =['''text''', ['''text''']] __lowerCamelCase : Union[str, Any] =['''text'''] def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' super().setup() __a = self.model.config __a = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): __a = int(__lowercase ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def UpperCamelCase_ ( self : List[str] , __lowercase : Optional[Any] , __lowercase : Any ): '''simple docstring''' __a = labels return self.pre_processor( [text] * len(__lowercase ) , [F"This example is {label}" for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def UpperCamelCase_ ( self : Optional[int] , __lowercase : str ): '''simple docstring''' __a = outputs.logits __a = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
302
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=3 , __magic_name__=18 , __magic_name__=30 , __magic_name__=400 , __magic_name__=True , __magic_name__=32 , __magic_name__=True , ) -> Dict: '''simple docstring''' snake_case_ : Tuple = parent snake_case_ : Union[str, Any] = batch_size snake_case_ : Union[str, Any] = num_channels snake_case_ : Optional[Any] = image_size snake_case_ : int = min_resolution snake_case_ : Any = max_resolution snake_case_ : Tuple = do_resize snake_case_ : str = size_divisor snake_case_ : Optional[Any] = do_rescale def lowerCamelCase (self ) -> Dict: '''simple docstring''' return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[Any] = GLPNImageProcessor if is_vision_available() else None def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : str = GLPNImageProcessingTester(self ) @property def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , '''do_resize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''size_divisor''' ) ) self.assertTrue(hasattr(__magic_name__ , '''resample''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_rescale''' ) ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
279
0
from __future__ import annotations from collections import namedtuple def SCREAMING_SNAKE_CASE__ ( __a , __a , __a ): snake_case_ : Optional[Any] = namedtuple('result' , 'name value' ) if (voltage, current, power).count(0 ) != 1: raise ValueError('Only one argument must be 0' ) elif power < 0: raise ValueError( 'Power cannot be negative in any electrical/electronics system' ) elif voltage == 0: return result('voltage' , power / current ) elif current == 0: return result('current' , power / voltage ) elif power == 0: return result('power' , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
327
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
279
0
'''simple docstring''' import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class A__ ( _a , _a , _a ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Union[str, Any] = False , ) -> Optional[int]: '''simple docstring''' super().__init__() _a : Tuple =nn.Embedding(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =nn.Embedding(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : List[str] =False _a : Union[str, Any] =nn.Dropout(p=SCREAMING_SNAKE_CASE ) _a : Any =TaConfig( vocab_size=SCREAMING_SNAKE_CASE , d_model=SCREAMING_SNAKE_CASE , num_heads=SCREAMING_SNAKE_CASE , d_kv=SCREAMING_SNAKE_CASE , d_ff=SCREAMING_SNAKE_CASE , dropout_rate=SCREAMING_SNAKE_CASE , feed_forward_proj=SCREAMING_SNAKE_CASE , is_decoder=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , ) _a : List[Any] =nn.ModuleList() for lyr_num in range(SCREAMING_SNAKE_CASE ): _a : List[Any] =TaBlock(SCREAMING_SNAKE_CASE ) self.encoders.append(SCREAMING_SNAKE_CASE ) _a : List[str] =TaLayerNorm(SCREAMING_SNAKE_CASE ) _a : int =nn.Dropout(p=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> int: '''simple docstring''' _a : Dict =self.token_embedder(SCREAMING_SNAKE_CASE ) _a : int =encoder_input_tokens.shape[1] _a : Union[str, Any] =torch.arange(SCREAMING_SNAKE_CASE , device=encoder_input_tokens.device ) x += self.position_encoding(SCREAMING_SNAKE_CASE ) _a : Any =self.dropout_pre(SCREAMING_SNAKE_CASE ) # inverted the attention mask _a : Dict =encoder_input_tokens.size() _a : Dict =self.get_extended_attention_mask(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for lyr in self.encoders: _a : Dict =lyr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )[0] _a : Optional[int] =self.layer_norm(SCREAMING_SNAKE_CASE ) return self.dropout_post(SCREAMING_SNAKE_CASE ), encoder_inputs_mask
276
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers lowerCAmelCase_ = float('''nan''') class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : List[Any] = sys.stdout snake_case_ : int = open(__magic_name__ , '''a''' ) def __getattr__(self , __magic_name__ ) -> Dict: '''simple docstring''' return getattr(self.stdout , __magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' self.stdout.write(__magic_name__ ) # strip tqdm codes self.file.write(re.sub(R'''^.*\r''' , '''''' , __magic_name__ , 0 , re.M ) ) def lowerCamelCase_ ( _UpperCamelCase=80 , _UpperCamelCase=False ) -> str: """simple docstring""" snake_case_ : str = [] # deal with critical env vars snake_case_ : int = ['''CUDA_VISIBLE_DEVICES'''] for key in env_keys: snake_case_ : Optional[int] = os.environ.get(_UpperCamelCase , _UpperCamelCase ) if val is not None: cmd.append(f'''{key}={val}''' ) # python executable (not always needed if the script is executable) snake_case_ : Optional[int] = sys.executable if full_python_path else sys.executable.split('''/''' )[-1] cmd.append(_UpperCamelCase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes snake_case_ : Dict = [] snake_case_ : Dict = '''''' while len(_UpperCamelCase ) > 0: current_line += f'''{cmd.pop(0 )} ''' if len(_UpperCamelCase ) == 0 or len(_UpperCamelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(_UpperCamelCase ) snake_case_ : List[Any] = '''''' return "\\\n".join(_UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" snake_case_ : str = re.sub(R'''[\\\n]+''' , ''' ''' , args.base_cmd ) # remove --output_dir if any and set our own snake_case_ : Optional[Any] = re.sub('''--output_dir\s+[^\s]+''' , '''''' , args.base_cmd ) args.base_cmd += f''' --output_dir {output_dir}''' # ensure we have --overwrite_output_dir snake_case_ : int = re.sub('''--overwrite_output_dir\s+''' , '''''' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6_666, 222.22_222_222] )} , ) snake_case_ : Tuple = subprocess.run(_UpperCamelCase , capture_output=_UpperCamelCase , text=_UpperCamelCase ) if verbose: print('''STDOUT''' , result.stdout ) print('''STDERR''' , result.stderr ) # save the streams snake_case_ : Any = variation.replace(''' ''' , '''-''' ) with open(Path(_UpperCamelCase ) / f'''log.{prefix}.stdout.txt''' , '''w''' ) as f: f.write(result.stdout ) with open(Path(_UpperCamelCase ) / f'''log.{prefix}.stderr.txt''' , '''w''' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('''failed''' ) return {target_metric_key: nan} with io.open(f'''{output_dir}/all_results.json''' , '''r''' , encoding='''utf-8''' ) as f: snake_case_ : str = json.load(_UpperCamelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) -> Tuple: """simple docstring""" snake_case_ : Tuple = [] snake_case_ : Any = [] snake_case_ : int = f'''{id}: {variation:<{longest_variation_len}}''' snake_case_ : Optional[Any] = f'''{preamble}: ''' snake_case_ : Optional[int] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(_UpperCamelCase ) , desc=_UpperCamelCase , leave=_UpperCamelCase ): snake_case_ : int = process_run_single( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) snake_case_ : List[str] = single_run_metrics[target_metric_key] if not math.isnan(_UpperCamelCase ): metrics.append(_UpperCamelCase ) results.append(_UpperCamelCase ) outcome += "✓" else: outcome += "✘" snake_case_ : Any = f'''\33[2K\r{outcome}''' if len(_UpperCamelCase ) > 0: snake_case_ : List[Any] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} snake_case_ : Any = round(mean_metrics[target_metric_key] , 2 ) snake_case_ : List[str] = f'''{outcome} {mean_target}''' if len(_UpperCamelCase ) > 1: results_str += f''' {tuple(round(_UpperCamelCase , 2 ) for x in results )}''' print(_UpperCamelCase ) snake_case_ : Optional[int] = variation return mean_metrics else: print(_UpperCamelCase ) return {variation_key: variation, target_metric_key: nan} def lowerCamelCase_ ( ) -> Optional[int]: """simple docstring""" snake_case_ : Any = torch.cuda.get_device_properties(torch.device('''cuda''' ) ) return f''' Datetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB ''' def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : str = pd.DataFrame(_UpperCamelCase ) snake_case_ : Optional[int] = '''variation''' snake_case_ : Union[str, Any] = '''diff_%''' snake_case_ : Optional[int] = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan snake_case_ : Optional[Any] = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(_UpperCamelCase ): # as a fallback, use the minimal value as the sentinel snake_case_ : Any = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(_UpperCamelCase ): snake_case_ : Dict = df.apply( lambda _UpperCamelCase : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='''columns''' , ) # re-order columns snake_case_ : Dict = [variation_key, target_metric_key, diff_key, *report_metric_keys] snake_case_ : int = df.reindex(_UpperCamelCase , axis='''columns''' ) # reorder cols # capitalize snake_case_ : Optional[int] = df.rename(str.capitalize , axis='''columns''' ) # make the cols as narrow as possible snake_case_ : Any = df.rename(lambda _UpperCamelCase : c.replace('''_''' , '''<br>''' ) , axis='''columns''' ) snake_case_ : int = df.rename(lambda _UpperCamelCase : c.replace('''_''' , '''\n''' ) , axis='''columns''' ) snake_case_ : Tuple = ['''''', '''Copy between the cut-here-lines and paste as is to github or a forum'''] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=_UpperCamelCase , floatfmt='''.2f''' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=_UpperCamelCase , floatfmt='''.2f''' )] print('''\n\n'''.join(_UpperCamelCase ) ) def lowerCamelCase_ ( ) -> Any: """simple docstring""" snake_case_ : Any = argparse.ArgumentParser() parser.add_argument( '''--base-cmd''' , default=_UpperCamelCase , type=_UpperCamelCase , required=_UpperCamelCase , help='''Base cmd''' , ) parser.add_argument( '''--variations''' , default=_UpperCamelCase , type=_UpperCamelCase , nargs='''+''' , required=_UpperCamelCase , help='''Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'''' , ) parser.add_argument( '''--base-variation''' , default=_UpperCamelCase , type=_UpperCamelCase , help='''Baseline variation to compare to. if None the minimal target value will be used to compare against''' , ) parser.add_argument( '''--target-metric-key''' , default=_UpperCamelCase , type=_UpperCamelCase , required=_UpperCamelCase , help='''Target metric key in output_dir/all_results.json, e.g., train_samples_per_second''' , ) parser.add_argument( '''--report-metric-keys''' , default='''''' , type=_UpperCamelCase , help='''Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples''' , ) parser.add_argument( '''--repeat-times''' , default=1 , type=_UpperCamelCase , help='''How many times to re-run each variation - an average will be reported''' , ) parser.add_argument( '''--output_dir''' , default='''output_benchmark''' , type=_UpperCamelCase , help='''The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked''' , ) parser.add_argument( '''--verbose''' , default=_UpperCamelCase , action='''store_true''' , help='''Whether to show the outputs of each run or just the benchmark progress''' , ) snake_case_ : Tuple = parser.parse_args() snake_case_ : Optional[Any] = args.output_dir Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) snake_case_ : Optional[int] = get_base_command(_UpperCamelCase , _UpperCamelCase ) # split each dimension into its --foo variations snake_case_ : Optional[int] = [list(map(str.strip , re.split(R'''\|''' , _UpperCamelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty snake_case_ : List[str] = list(map(str.strip , map(''' '''.join , itertools.product(*_UpperCamelCase ) ) ) ) snake_case_ : Optional[int] = max(len(_UpperCamelCase ) for x in variations ) # split wanted keys snake_case_ : int = args.report_metric_keys.split() # capture prints into a log file for convenience snake_case_ : str = f'''benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt''' print(f'''\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt''' ) print(f'''and this script\'s output is also piped into {report_fn}''' ) snake_case_ : Tuple = Tee(_UpperCamelCase ) print(f'''\n*** Running {len(_UpperCamelCase )} benchmarks:''' ) print(f'''Base command: {" ".join(_UpperCamelCase )}''' ) snake_case_ : List[Any] = '''variation''' snake_case_ : Tuple = [] for id, variation in enumerate(tqdm(_UpperCamelCase , desc='''Total completion: ''' , leave=_UpperCamelCase ) ): snake_case_ : Optional[Any] = base_cmd + variation.split() results.append( process_run( id + 1 , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , args.target_metric_key , _UpperCamelCase , args.repeat_times , _UpperCamelCase , args.verbose , ) ) process_results(_UpperCamelCase , args.target_metric_key , _UpperCamelCase , args.base_variation , _UpperCamelCase ) if __name__ == "__main__": main()
279
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class lowerCAmelCase_ ( _a , _a , unittest.TestCase ): '''simple docstring''' _snake_case = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) _snake_case = ( { '''feature-extraction''': TFMobileBertModel, '''fill-mask''': TFMobileBertForMaskedLM, '''question-answering''': TFMobileBertForQuestionAnswering, '''text-classification''': TFMobileBertForSequenceClassification, '''token-classification''': TFMobileBertForTokenClassification, '''zero-shot''': TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) _snake_case = False _snake_case = False def A__ ( self , snake_case_ , snake_case_ , snake_case_=False ) -> int: __lowerCAmelCase = super()._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) if return_labels: if model_class in get_values(snake_case_ ): __lowerCAmelCase = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) return inputs_dict class lowerCAmelCase_ ( _a ): '''simple docstring''' def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=32 , snake_case_=2 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ) -> int: __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = seq_length __lowerCAmelCase = is_training __lowerCAmelCase = use_input_mask __lowerCAmelCase = use_token_type_ids __lowerCAmelCase = use_labels __lowerCAmelCase = vocab_size __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = max_position_embeddings __lowerCAmelCase = type_vocab_size __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = num_labels __lowerCAmelCase = num_choices __lowerCAmelCase = scope __lowerCAmelCase = embedding_size def A__ ( self ) -> Dict: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase = None if self.use_input_mask: __lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase = None if self.use_token_type_ids: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase = None __lowerCAmelCase = None __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase = MobileBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def A__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: __lowerCAmelCase = TFMobileBertModel(config=snake_case_ ) __lowerCAmelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __lowerCAmelCase = model(snake_case_ ) __lowerCAmelCase = [input_ids, input_mask] __lowerCAmelCase = model(snake_case_ ) __lowerCAmelCase = model(snake_case_ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def A__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[str]: __lowerCAmelCase = TFMobileBertForMaskedLM(config=snake_case_ ) __lowerCAmelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __lowerCAmelCase = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: __lowerCAmelCase = TFMobileBertForNextSentencePrediction(config=snake_case_ ) __lowerCAmelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __lowerCAmelCase = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def A__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> int: __lowerCAmelCase = TFMobileBertForPreTraining(config=snake_case_ ) __lowerCAmelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __lowerCAmelCase = model(snake_case_ ) self.parent.assertEqual( result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def A__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: __lowerCAmelCase = self.num_labels __lowerCAmelCase = TFMobileBertForSequenceClassification(config=snake_case_ ) __lowerCAmelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __lowerCAmelCase = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: __lowerCAmelCase = self.num_choices __lowerCAmelCase = TFMobileBertForMultipleChoice(config=snake_case_ ) __lowerCAmelCase = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase = tf.tile(tf.expand_dims(snake_case_ , 1 ) , (1, self.num_choices, 1) ) __lowerCAmelCase = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } __lowerCAmelCase = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def A__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: __lowerCAmelCase = self.num_labels __lowerCAmelCase = TFMobileBertForTokenClassification(config=snake_case_ ) __lowerCAmelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __lowerCAmelCase = model(snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Any: __lowerCAmelCase = TFMobileBertForQuestionAnswering(config=snake_case_ ) __lowerCAmelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __lowerCAmelCase = model(snake_case_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def A__ ( self ) -> str: __lowerCAmelCase = self.prepare_config_and_inputs() ( __lowerCAmelCase ) = config_and_inputs __lowerCAmelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict def A__ ( self ) -> str: __lowerCAmelCase = TFMobileBertModelTest.TFMobileBertModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def A__ ( self ) -> List[Any]: self.config_tester.run_common_tests() def A__ ( self ) -> Dict: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*snake_case_ ) def A__ ( self ) -> Optional[int]: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*snake_case_ ) def A__ ( self ) -> int: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*snake_case_ ) def A__ ( self ) -> Tuple: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*snake_case_ ) def A__ ( self ) -> Optional[int]: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*snake_case_ ) def A__ ( self ) -> int: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*snake_case_ ) def A__ ( self ) -> Tuple: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*snake_case_ ) def A__ ( self ) -> Optional[int]: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*snake_case_ ) @slow def A__ ( self ) -> Optional[int]: for model_name in ["google/mobilebert-uncased"]: __lowerCAmelCase = TFMobileBertModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) @require_tf class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def A__ ( self ) -> Tuple: __lowerCAmelCase = TFMobileBertForPreTraining.from_pretrained("""google/mobilebert-uncased""" ) __lowerCAmelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) __lowerCAmelCase = model(snake_case_ )[0] __lowerCAmelCase = [1, 6, 30_522] self.assertEqual(output.shape , snake_case_ ) __lowerCAmelCase = tf.constant( [ [ [-4.5_919_547, -9.248_295, -9.645_256], [-6.7_306_175, -6.440_284, -6.6_052_837], [-7.2_743_506, -6.7_847_915, -6.024_673], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , snake_case_ , atol=1e-4 )
301
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--txt2img_unclip''', default='''kakaobrain/karlo-v1-alpha''', type=str, required=False, help='''The pretrained txt2img unclip.''', ) lowerCAmelCase_ = parser.parse_args() lowerCAmelCase_ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) lowerCAmelCase_ = CLIPImageProcessor() lowerCAmelCase_ = CLIPVisionModelWithProjection.from_pretrained('''openai/clip-vit-large-patch14''') lowerCAmelCase_ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
279
0
'''simple docstring''' def __A ( lowerCamelCase_ ): """simple docstring""" if isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError("""\'float\' object cannot be interpreted as an integer""" ) if isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError("""\'str\' object cannot be interpreted as an integer""" ) if num == 0: return "0b0" SCREAMING_SNAKE_CASE : Optional[Any] = False if num < 0: SCREAMING_SNAKE_CASE : Dict = True SCREAMING_SNAKE_CASE : Any = -num SCREAMING_SNAKE_CASE : list[int] = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(_UpperCamelCase ) for e in binary ) return "0b" + "".join(str(_UpperCamelCase ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
323
from math import factorial lowerCAmelCase_ = {str(digit): factorial(digit) for digit in range(1_0)} def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError('''Parameter number must be int''' ) if number < 0: raise ValueError('''Parameter number must be greater than or equal to 0''' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCamelCase ) ) def lowerCamelCase_ ( _UpperCamelCase = 60 , _UpperCamelCase = 1_000_000 ) -> int: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ) or not isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError('''Parameters chain_length and number_limit must be int''' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( '''Parameters chain_length and number_limit must be greater than 0''' ) # the counter for the chains with the exact desired length snake_case_ : Optional[Any] = 0 # the cached sizes of the previous chains snake_case_ : dict[int, int] = {} for start_chain_element in range(1 , _UpperCamelCase ): # The temporary set will contain the elements of the chain snake_case_ : List[str] = set() snake_case_ : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. snake_case_ : Any = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCamelCase ) chain_set_length += 1 snake_case_ : List[Any] = digit_factorial_sum(_UpperCamelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] snake_case_ : List[str] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F'''{solution()}''')
279
0
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class UpperCamelCase : @staticmethod def _UpperCAmelCase ( *__UpperCamelCase ,**__UpperCamelCase ) -> int: '''simple docstring''' pass @is_pipeline_test @require_vision @require_timm @require_torch class UpperCamelCase ( unittest.TestCase ): lowercase = MODEL_FOR_OBJECT_DETECTION_MAPPING def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Optional[int]: '''simple docstring''' lowercase_ : Tuple = ObjectDetectionPipeline(model=__UpperCamelCase ,image_processor=__UpperCamelCase ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> Optional[Any]: '''simple docstring''' lowercase_ : Dict = object_detector('./tests/fixtures/tests_samples/COCO/000000039769.png' ,threshold=0.0 ) self.assertGreater(len(__UpperCamelCase ) ,0 ) for detected_object in outputs: self.assertEqual( __UpperCamelCase ,{ 'score': ANY(__UpperCamelCase ), 'label': ANY(__UpperCamelCase ), 'box': {'xmin': ANY(__UpperCamelCase ), 'ymin': ANY(__UpperCamelCase ), 'xmax': ANY(__UpperCamelCase ), 'ymax': ANY(__UpperCamelCase )}, } ,) import datasets lowercase_ : int = datasets.load_dataset('hf-internal-testing/fixtures_image_utils' ,'image' ,split='test' ) lowercase_ : str = [ Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ] lowercase_ : Any = object_detector(__UpperCamelCase ,threshold=0.0 ) self.assertEqual(len(__UpperCamelCase ) ,len(__UpperCamelCase ) ) for outputs in batch_outputs: self.assertGreater(len(__UpperCamelCase ) ,0 ) for detected_object in outputs: self.assertEqual( __UpperCamelCase ,{ 'score': ANY(__UpperCamelCase ), 'label': ANY(__UpperCamelCase ), 'box': {'xmin': ANY(__UpperCamelCase ), 'ymin': ANY(__UpperCamelCase ), 'xmax': ANY(__UpperCamelCase ), 'ymax': ANY(__UpperCamelCase )}, } ,) @require_tf @unittest.skip('Object detection not implemented in TF' ) def _UpperCAmelCase ( self ) -> Dict: '''simple docstring''' pass @require_torch def _UpperCAmelCase ( self ) -> Union[str, Any]: '''simple docstring''' lowercase_ : Tuple = '''hf-internal-testing/tiny-detr-mobilenetsv3''' lowercase_ : Any = AutoModelForObjectDetection.from_pretrained(__UpperCamelCase ) lowercase_ : str = AutoFeatureExtractor.from_pretrained(__UpperCamelCase ) lowercase_ : Optional[Any] = ObjectDetectionPipeline(model=__UpperCamelCase ,feature_extractor=__UpperCamelCase ) lowercase_ : int = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ,threshold=0.0 ) self.assertEqual( nested_simplify(__UpperCamelCase ,decimals=4 ) ,[ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ] ,) lowercase_ : Union[str, Any] = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] ,threshold=0.0 ,) self.assertEqual( nested_simplify(__UpperCamelCase ,decimals=4 ) ,[ [ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ], [ {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, {'score': 0.3376, 'label': 'LABEL_0', 'box': {'xmin': 159, 'ymin': 120, 'xmax': 480, 'ymax': 359}}, ], ] ,) @require_torch @slow def _UpperCAmelCase ( self ) -> Any: '''simple docstring''' lowercase_ : Optional[Any] = '''facebook/detr-resnet-50''' lowercase_ : str = AutoModelForObjectDetection.from_pretrained(__UpperCamelCase ) lowercase_ : Any = AutoFeatureExtractor.from_pretrained(__UpperCamelCase ) lowercase_ : Optional[int] = ObjectDetectionPipeline(model=__UpperCamelCase ,feature_extractor=__UpperCamelCase ) lowercase_ : str = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ) self.assertEqual( nested_simplify(__UpperCamelCase ,decimals=4 ) ,[ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] ,) lowercase_ : List[str] = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] ) self.assertEqual( nested_simplify(__UpperCamelCase ,decimals=4 ) ,[ [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], ] ,) @require_torch @slow def _UpperCAmelCase ( self ) -> List[Any]: '''simple docstring''' lowercase_ : List[str] = '''facebook/detr-resnet-50''' lowercase_ : Tuple = pipeline('object-detection' ,model=__UpperCamelCase ) lowercase_ : str = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ) self.assertEqual( nested_simplify(__UpperCamelCase ,decimals=4 ) ,[ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] ,) lowercase_ : str = object_detector( [ 'http://images.cocodataset.org/val2017/000000039769.jpg', 'http://images.cocodataset.org/val2017/000000039769.jpg', ] ) self.assertEqual( nested_simplify(__UpperCamelCase ,decimals=4 ) ,[ [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], [ {'score': 0.9982, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 70, 'xmax': 175, 'ymax': 117}}, {'score': 0.9960, 'label': 'remote', 'box': {'xmin': 333, 'ymin': 72, 'xmax': 368, 'ymax': 187}}, {'score': 0.9955, 'label': 'couch', 'box': {'xmin': 0, 'ymin': 1, 'xmax': 639, 'ymax': 473}}, {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ], ] ,) @require_torch @slow def _UpperCAmelCase ( self ) -> Optional[int]: '''simple docstring''' lowercase_ : Dict = 0.9985 lowercase_ : Dict = '''facebook/detr-resnet-50''' lowercase_ : Dict = pipeline('object-detection' ,model=__UpperCamelCase ) lowercase_ : str = object_detector('http://images.cocodataset.org/val2017/000000039769.jpg' ,threshold=__UpperCamelCase ) self.assertEqual( nested_simplify(__UpperCamelCase ,decimals=4 ) ,[ {'score': 0.9988, 'label': 'cat', 'box': {'xmin': 13, 'ymin': 52, 'xmax': 314, 'ymax': 470}}, {'score': 0.9987, 'label': 'cat', 'box': {'xmin': 345, 'ymin': 23, 'xmax': 640, 'ymax': 368}}, ] ,) @require_torch @require_pytesseract @slow def _UpperCAmelCase ( self ) -> List[str]: '''simple docstring''' lowercase_ : List[str] = '''Narsil/layoutlmv3-finetuned-funsd''' lowercase_ : List[str] = 0.9993 lowercase_ : Dict = pipeline('object-detection' ,model=__UpperCamelCase ,threshold=__UpperCamelCase ) lowercase_ : Optional[Any] = object_detector( 'https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png' ) self.assertEqual( nested_simplify(__UpperCamelCase ,decimals=4 ) ,[ {'score': 0.9993, 'label': 'I-ANSWER', 'box': {'xmin': 294, 'ymin': 254, 'xmax': 343, 'ymax': 264}}, {'score': 0.9993, 'label': 'I-ANSWER', 'box': {'xmin': 294, 'ymin': 254, 'xmax': 343, 'ymax': 264}}, ] ,)
213
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''''' lowerCamelCase_ : str = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) lowerCamelCase_ : str = None # compression type in fsspec. ex: "gzip" lowerCamelCase_ : str = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__(self , __magic_name__ = "" , __magic_name__ = None , __magic_name__ = None , **__magic_name__ ) -> Any: '''simple docstring''' super().__init__(self , **__magic_name__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode snake_case_ : Union[str, Any] = fsspec.open( __magic_name__ , mode='''rb''' , protocol=__magic_name__ , compression=self.compression , client_kwargs={ '''requote_redirect_url''': False, # see https://github.com/huggingface/datasets/pull/5459 '''trust_env''': True, # Enable reading proxy env variables. **(target_options or {}).pop('''client_kwargs''' , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) snake_case_ : Tuple = os.path.basename(self.file.path.split('''::''' )[0] ) snake_case_ : Optional[Any] = ( self.compressed_name[: self.compressed_name.rindex('''.''' )] if '''.''' in self.compressed_name else self.compressed_name ) snake_case_ : Dict = None @classmethod def lowerCamelCase (cls , __magic_name__ ) -> Optional[int]: '''simple docstring''' return super()._strip_protocol(__magic_name__ ).lstrip('''/''' ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' if self.dir_cache is None: snake_case_ : Optional[int] = {**self.file.fs.info(self.file.path ), '''name''': self.uncompressed_name} snake_case_ : List[str] = {f['''name''']: f} def lowerCamelCase (self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' return self.file.open().read() def lowerCamelCase (self , __magic_name__ , __magic_name__ = "rb" , __magic_name__=None , __magic_name__=True , __magic_name__=None , **__magic_name__ , ) -> int: '''simple docstring''' snake_case_ : Union[str, Any] = self._strip_protocol(__magic_name__ ) if mode != "rb": raise ValueError(F'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''bz2''' lowerCamelCase_ : Any = '''bz2''' lowerCamelCase_ : int = '''.bz2''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''gzip''' lowerCamelCase_ : Dict = '''gzip''' lowerCamelCase_ : int = '''.gz''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''lz4''' lowerCamelCase_ : Any = '''lz4''' lowerCamelCase_ : Optional[Any] = '''.lz4''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''xz''' lowerCamelCase_ : Any = '''xz''' lowerCamelCase_ : int = '''.xz''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''zstd''' lowerCamelCase_ : Tuple = '''zstd''' lowerCamelCase_ : Any = '''.zst''' def __init__(self , __magic_name__ , __magic_name__ = "rb" , __magic_name__ = None , __magic_name__ = None , __magic_name__ = DEFAULT_BLOCK_SIZE , **__magic_name__ , ) -> Tuple: '''simple docstring''' super().__init__( fo=__magic_name__ , mode=__magic_name__ , target_protocol=__magic_name__ , target_options=__magic_name__ , block_size=__magic_name__ , **__magic_name__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 snake_case_ : Dict = self.file.__enter__ class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : str = file_ def __enter__(self ) -> List[Any]: '''simple docstring''' self._file.__enter__() return self def __exit__(self , *__magic_name__ , **__magic_name__ ) -> int: '''simple docstring''' self._file.__exit__(*__magic_name__ , **__magic_name__ ) def __iter__(self ) -> Optional[int]: '''simple docstring''' return iter(self._file ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return next(self._file ) def __getattr__(self , __magic_name__ ) -> str: '''simple docstring''' return getattr(self._file , __magic_name__ ) def fixed_enter(*__magic_name__ , **__magic_name__ ): return WrappedFile(_enter(*__magic_name__ , **__magic_name__ ) ) snake_case_ : Tuple = fixed_enter
279
0
import csv import tweepy # Twitter API credentials __snake_case = '''''' __snake_case = '''''' __snake_case = '''''' __snake_case = '''''' def lowerCAmelCase_ ( __lowerCAmelCase )-> None: '''simple docstring''' UpperCAmelCase : Optional[Any] =tweepy.OAuthHandler(_UpperCamelCase , _UpperCamelCase ) auth.set_access_token(_UpperCamelCase , _UpperCamelCase ) UpperCAmelCase : Optional[int] =tweepy.API(_UpperCamelCase ) # initialize a list to hold all the tweepy Tweets UpperCAmelCase : Union[str, Any] =[] # make initial request for most recent tweets (200 is the maximum allowed count) UpperCAmelCase : int =api.user_timeline(screen_name=_UpperCamelCase , count=2_00 ) # save most recent tweets alltweets.extend(_UpperCamelCase ) # save the id of the oldest tweet less one UpperCAmelCase : str =alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(_UpperCamelCase ) > 0: print(f'''getting tweets before {oldest}''' ) # all subsequent requests use the max_id param to prevent duplicates UpperCAmelCase : Dict =api.user_timeline( screen_name=_UpperCamelCase , count=2_00 , max_id=_UpperCamelCase ) # save most recent tweets alltweets.extend(_UpperCamelCase ) # update the id of the oldest tweet less one UpperCAmelCase : Optional[Any] =alltweets[-1].id - 1 print(f'''...{len(_UpperCamelCase )} tweets downloaded so far''' ) # transform the tweepy tweets into a 2D array that will populate the csv UpperCAmelCase : Tuple =[[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(f'''new_{screen_name}_tweets.csv''' , '''w''' ) as f: UpperCAmelCase : Union[str, Any] =csv.writer(_UpperCamelCase ) writer.writerow(['''id''', '''created_at''', '''text'''] ) writer.writerows(_UpperCamelCase ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets('''FirePing32''')
348
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''megatron-bert''' def __init__(self , __magic_name__=2_9056 , __magic_name__=1024 , __magic_name__=24 , __magic_name__=16 , __magic_name__=4096 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=512 , __magic_name__=2 , __magic_name__=0.02 , __magic_name__=1e-12 , __magic_name__=0 , __magic_name__="absolute" , __magic_name__=True , **__magic_name__ , ) -> Any: '''simple docstring''' super().__init__(pad_token_id=__magic_name__ , **__magic_name__ ) snake_case_ : Union[str, Any] = vocab_size snake_case_ : Dict = hidden_size snake_case_ : Dict = num_hidden_layers snake_case_ : Optional[int] = num_attention_heads snake_case_ : int = hidden_act snake_case_ : List[str] = intermediate_size snake_case_ : Dict = hidden_dropout_prob snake_case_ : str = attention_probs_dropout_prob snake_case_ : str = max_position_embeddings snake_case_ : Any = type_vocab_size snake_case_ : int = initializer_range snake_case_ : int = layer_norm_eps snake_case_ : List[str] = position_embedding_type snake_case_ : Dict = use_cache
279
0
'''simple docstring''' def snake_case ( UpperCAmelCase , UpperCAmelCase )-> bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
161
import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch lowerCAmelCase_ = random.Random() def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase=1.0 , _UpperCamelCase=None , _UpperCamelCase=None ) -> List[Any]: """simple docstring""" if rng is None: snake_case_ : str = global_rng snake_case_ : Any = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=400 , __magic_name__=2000 , __magic_name__=10 , __magic_name__=160 , __magic_name__=8 , __magic_name__=0.0 , __magic_name__=4000 , __magic_name__=False , __magic_name__=True , ) -> List[str]: '''simple docstring''' snake_case_ : Tuple = parent snake_case_ : str = batch_size snake_case_ : Union[str, Any] = min_seq_length snake_case_ : Tuple = max_seq_length snake_case_ : Optional[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) snake_case_ : Optional[int] = padding_value snake_case_ : Union[str, Any] = sampling_rate snake_case_ : Optional[int] = return_attention_mask snake_case_ : str = do_normalize snake_case_ : str = feature_size snake_case_ : Optional[Any] = chunk_length snake_case_ : Union[str, Any] = hop_length def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def lowerCamelCase (self , __magic_name__=False , __magic_name__=False ) -> Optional[Any]: '''simple docstring''' def _flatten(__magic_name__ ): return list(itertools.chain(*__magic_name__ ) ) if equal_length: snake_case_ : int = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size snake_case_ : int = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: snake_case_ : str = [np.asarray(__magic_name__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[Any] = WhisperFeatureExtractor if is_speech_available() else None def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[str] = WhisperFeatureExtractionTester(self ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : Union[str, Any] = feat_extract_first.save_pretrained(__magic_name__ )[0] check_json_file_has_correct_format(__magic_name__ ) snake_case_ : List[Any] = self.feature_extraction_class.from_pretrained(__magic_name__ ) snake_case_ : Optional[int] = feat_extract_first.to_dict() snake_case_ : Dict = feat_extract_second.to_dict() snake_case_ : List[str] = feat_extract_first.mel_filters snake_case_ : Union[str, Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(__magic_name__ , __magic_name__ ) ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : List[Any] = os.path.join(__magic_name__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(__magic_name__ ) snake_case_ : Optional[int] = self.feature_extraction_class.from_json_file(__magic_name__ ) snake_case_ : int = feat_extract_first.to_dict() snake_case_ : Optional[int] = feat_extract_second.to_dict() snake_case_ : Union[str, Any] = feat_extract_first.mel_filters snake_case_ : str = feat_extract_second.mel_filters self.assertTrue(np.allclose(__magic_name__ , __magic_name__ ) ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 snake_case_ : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] snake_case_ : str = [np.asarray(__magic_name__ ) for speech_input in speech_inputs] # Test feature size snake_case_ : str = feature_extractor(__magic_name__ , padding='''max_length''' , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input snake_case_ : Dict = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features snake_case_ : Optional[int] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test batched snake_case_ : int = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : Union[str, Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. snake_case_ : Union[str, Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] snake_case_ : List[str] = np.asarray(__magic_name__ ) snake_case_ : List[Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : Dict = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test truncation required snake_case_ : Any = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] snake_case_ : Union[str, Any] = [np.asarray(__magic_name__ ) for speech_input in speech_inputs] snake_case_ : Tuple = [x[: feature_extractor.n_samples] for x in speech_inputs] snake_case_ : Optional[Any] = [np.asarray(__magic_name__ ) for speech_input in speech_inputs_truncated] snake_case_ : Any = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : List[Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) def lowerCamelCase (self ) -> int: '''simple docstring''' import torch snake_case_ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case_ : Union[str, Any] = np.random.rand(100 , 32 ).astype(np.floataa ) snake_case_ : Dict = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: snake_case_ : Optional[Any] = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) snake_case_ : Optional[Any] = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Optional[Any] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech snake_case_ : Optional[Any] = ds.sort('''id''' ).select(range(__magic_name__ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : str = torch.tensor( [ 0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951, 0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678, 0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554, -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854 ] ) # fmt: on snake_case_ : List[Any] = self._load_datasamples(1 ) snake_case_ : Union[str, Any] = WhisperFeatureExtractor() snake_case_ : Union[str, Any] = feature_extractor(__magic_name__ , return_tensors='''pt''' ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __magic_name__ , atol=1e-4 ) ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case_ : Optional[int] = self._load_datasamples(1 )[0] snake_case_ : List[str] = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue snake_case_ : Optional[Any] = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__magic_name__ )[0] self.assertTrue(np.all(np.mean(__magic_name__ ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(__magic_name__ ) - 1 ) < 1e-3 ) )
279
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __a = logging.get_logger(__name__) if is_vision_available(): import PIL class lowercase__( _a ): """simple docstring""" a :List[str] = ['''pixel_values'''] def __init__( self : Tuple , SCREAMING_SNAKE_CASE_ : str = True , SCREAMING_SNAKE_CASE_ : Any = None , SCREAMING_SNAKE_CASE_ : Optional[Any] = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ : Optional[Any] = True , SCREAMING_SNAKE_CASE_ : List[str] = None , SCREAMING_SNAKE_CASE_ : Optional[Any] = True , SCREAMING_SNAKE_CASE_ : Tuple = 1 / 2_5_5 , SCREAMING_SNAKE_CASE_ : Dict = True , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Tuple = None , SCREAMING_SNAKE_CASE_ : Optional[int] = True , **SCREAMING_SNAKE_CASE_ : Optional[Any] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE_ ) lowercase_ = size if size is not None else {'''shortest_edge''': 2_2_4} lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) lowercase_ = crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' ) lowercase_ = do_resize lowercase_ = size lowercase_ = resample lowercase_ = do_center_crop lowercase_ = crop_size lowercase_ = do_rescale lowercase_ = rescale_factor lowercase_ = do_normalize lowercase_ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowercase_ = image_std if image_std is not None else OPENAI_CLIP_STD lowercase_ = do_convert_rgb def _lowercase ( self : List[str] , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ : List[Any] = None , **SCREAMING_SNAKE_CASE_ : Optional[Any] , ) -> np.ndarray: lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) lowercase_ = get_resize_output_image_size(SCREAMING_SNAKE_CASE_ , size=size['''shortest_edge'''] , default_to_square=SCREAMING_SNAKE_CASE_ ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : int = None , **SCREAMING_SNAKE_CASE_ : Optional[int] , ) -> np.ndarray: lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(SCREAMING_SNAKE_CASE_ , size=(size['''height'''], size['''width''']) , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple = None , **SCREAMING_SNAKE_CASE_ : int , ) -> Dict: return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] = None , **SCREAMING_SNAKE_CASE_ : Tuple , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Any = None , SCREAMING_SNAKE_CASE_ : Any = None , SCREAMING_SNAKE_CASE_ : Dict = None , SCREAMING_SNAKE_CASE_ : Tuple = None , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : Any = None , SCREAMING_SNAKE_CASE_ : Dict = None , SCREAMING_SNAKE_CASE_ : Tuple = None , SCREAMING_SNAKE_CASE_ : int = None , SCREAMING_SNAKE_CASE_ : Tuple = None , SCREAMING_SNAKE_CASE_ : Dict = None , SCREAMING_SNAKE_CASE_ : Dict = None , SCREAMING_SNAKE_CASE_ : List[Any] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> PIL.Image.Image: lowercase_ = do_resize if do_resize is not None else self.do_resize lowercase_ = size if size is not None else self.size lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name='''size''' , default_to_square=SCREAMING_SNAKE_CASE_ ) lowercase_ = resample if resample is not None else self.resample lowercase_ = do_center_crop if do_center_crop is not None else self.do_center_crop lowercase_ = crop_size if crop_size is not None else self.crop_size lowercase_ = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' , default_to_square=SCREAMING_SNAKE_CASE_ ) lowercase_ = do_rescale if do_rescale is not None else self.do_rescale lowercase_ = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase_ = do_normalize if do_normalize is not None else self.do_normalize lowercase_ = image_mean if image_mean is not None else self.image_mean lowercase_ = image_std if image_std is not None else self.image_std lowercase_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowercase_ = make_list_of_images(SCREAMING_SNAKE_CASE_ ) if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: 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.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: lowercase_ = [convert_to_rgb(SCREAMING_SNAKE_CASE_ ) for image in images] # All transformations expect numpy arrays. lowercase_ = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: lowercase_ = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_center_crop: lowercase_ = [self.center_crop(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: lowercase_ = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: lowercase_ = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] lowercase_ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] lowercase_ = {'''pixel_values''': images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ )
30
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase_ = logging.getLogger(__name__) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : List[str] = argparse.ArgumentParser( description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' ) parser.add_argument( '''--dataset_name''' , type=_UpperCamelCase , default='''wikitext''' , help='''Name of the training. Explore datasets at: hf.co/datasets.''' , ) parser.add_argument( '''--dataset_config''' , type=_UpperCamelCase , default='''wikitext-103-raw-v1''' , help='''Configuration name of the dataset.''' ) parser.add_argument( '''--tokenizer_name_or_path''' , type=_UpperCamelCase , default='''sayakpaul/unigram-tokenizer-wikitext''' , help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' , ) parser.add_argument( '''--shard_size''' , type=_UpperCamelCase , default=1_000 , help='''Number of entries to go in a single shard.''' , ) parser.add_argument('''--split''' , type=_UpperCamelCase , default='''train''' , choices=['''train''', '''test''', '''validation'''] ) parser.add_argument( '''--limit''' , default=_UpperCamelCase , type=_UpperCamelCase , help='''Limit the number of shards (used for debugging).''' , ) parser.add_argument( '''--max_length''' , type=_UpperCamelCase , default=512 , help='''Maximum sequence length. For training on TPUs, it helps to have a maximum''' ''' sequence length that is a multiple of 8.''' , ) parser.add_argument( '''--output_dir''' , default='''tf-tpu''' , type=_UpperCamelCase , help='''Output directory where the TFRecord shards will be saved. If the''' ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord''' ''' shards will be directly saved to a Google Cloud Storage bucket.''' , ) snake_case_ : List[Any] = parser.parse_args() return args def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple: """simple docstring""" def fn(_UpperCamelCase ): return tokenizer(examples['''text'''] ) return fn def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : Any = [] for i in range(len(tokenized_data['''input_ids'''] ) ): snake_case_ : Any = { '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ), '''attention_mask''': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ), } snake_case_ : Optional[int] = tf.train.Features(feature=_UpperCamelCase ) snake_case_ : Optional[Any] = tf.train.Example(features=_UpperCamelCase ) snake_case_ : Optional[Any] = example.SerializeToString() records.append(_UpperCamelCase ) return records def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : int = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: snake_case_ : Union[str, Any] = min(len(_UpperCamelCase ) , args.limit ) snake_case_ : int = dataset.select(range(_UpperCamelCase ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) snake_case_ : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) snake_case_ : str = os.path.join(args.output_dir , args.split ) if not os.path.exists(_UpperCamelCase ): os.makedirs(_UpperCamelCase ) else: snake_case_ : Optional[Any] = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. snake_case_ : Optional[Any] = tokenize_function(_UpperCamelCase ) snake_case_ : List[Any] = dataset.map(_UpperCamelCase , batched=_UpperCamelCase , num_proc=4 , remove_columns=['''text'''] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(_UpperCamelCase ): # Concatenate all texts. snake_case_ : Tuple = {k: sum(examples[k] , [] ) for k in examples.keys()} snake_case_ : List[str] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 snake_case_ : int = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. snake_case_ : Union[str, Any] = { k: [t[i : i + args.max_length] for i in range(0 , _UpperCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result snake_case_ : int = dataset_tokenized.map(_UpperCamelCase , batched=_UpperCamelCase , batch_size=1_000 , num_proc=4 ) snake_case_ : str = 0 snake_case_ : Optional[Any] = 0 for shard in range(0 , len(_UpperCamelCase ) , args.shard_size ): snake_case_ : Any = grouped_dataset[shard : shard + args.shard_size] snake_case_ : str = len(dataset_snapshot['''input_ids'''] ) snake_case_ : Union[str, Any] = os.path.join(_UpperCamelCase , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) snake_case_ : Dict = get_serialized_examples(_UpperCamelCase ) with tf.io.TFRecordWriter(_UpperCamelCase ) as out_file: for i in range(len(_UpperCamelCase ) ): snake_case_ : List[str] = serialized_examples[i] out_file.write(_UpperCamelCase ) print('''Wrote file {} containing {} records'''.format(_UpperCamelCase , _UpperCamelCase ) ) shard_count += 1 total_records += records_containing with open(f'''split-{args.split}-records-count.txt''' , '''w''' ) as f: print(f'''Total {args.split} records: {total_records}''' , file=_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = parse_args() main(args)
279
0
from statistics import mean, stdev def a__ ( _UpperCamelCase : Optional[int] ,_UpperCamelCase : Any = 3 ): __lowerCamelCase = min(_UpperCamelCase ) __lowerCamelCase = max(_UpperCamelCase ) # normalize data return [round((x - x_min) / (x_max - x_min) ,_UpperCamelCase ) for x in data] def a__ ( _UpperCamelCase : str ,_UpperCamelCase : int = 3 ): __lowerCamelCase = mean(_UpperCamelCase ) __lowerCamelCase = stdev(_UpperCamelCase ) # standardize data return [round((x - mu) / (sigma) ,_UpperCamelCase ) for x in data]
330
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Any = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Any = hf_hub_download( repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : List[Any] = VideoClassificationPipeline(model=__magic_name__ , image_processor=__magic_name__ , top_k=2 ) snake_case_ : str = [ example_video_filepath, '''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''', ] return video_classifier, examples def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' for example in examples: snake_case_ : Union[str, Any] = video_classifier(__magic_name__ ) self.assertEqual( __magic_name__ , [ {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, ] , ) @require_torch def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Any = '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification''' snake_case_ : str = VideoMAEFeatureExtractor( size={'''shortest_edge''': 10} , crop_size={'''height''': 10, '''width''': 10} ) snake_case_ : int = pipeline( '''video-classification''' , model=__magic_name__ , feature_extractor=__magic_name__ , frame_sampling_rate=4 ) snake_case_ : List[str] = hf_hub_download(repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : Union[str, Any] = video_classifier(__magic_name__ , top_k=2 ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}] , ) snake_case_ : int = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], ] , ) @require_tf def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' pass
279
0
'''simple docstring''' import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, 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 a_ : List[str] = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class a : def __init__( self , __magic_name__ , __magic_name__=16 , __magic_name__=13 , __magic_name__=7 , __magic_name__=14 , __magic_name__=10 , __magic_name__=19 , __magic_name__=5 , __magic_name__=4 , __magic_name__=True , __magic_name__=16 , __magic_name__=2 , __magic_name__=4 , __magic_name__=4 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=[1, 2, 3, 4, 5] , __magic_name__=25 , __magic_name__=5 , ) -> Optional[int]: _a = d_model _a = parent _a = batch_size _a = prediction_length _a = context_length _a = cardinality _a = num_time_features _a = lags_sequence _a = embedding_dimension _a = is_training _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = context_length _a = prediction_length + label_length _a = label_length _a = moving_average _a = autocorrelation_factor def __UpperCAmelCase ( self ) -> Dict: return AutoformerConfig( d_model=self.d_model , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def __UpperCAmelCase ( self , __magic_name__ ) -> Dict: _a = config.context_length + max(config.lags_sequence ) _a = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) _a = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) _a = floats_tensor([self.batch_size, _past_length] ) _a = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs _a = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) _a = floats_tensor([self.batch_size, config.prediction_length] ) _a = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def __UpperCAmelCase ( self ) -> Optional[Any]: _a = self.get_config() _a = self.prepare_autoformer_inputs_dict(__magic_name__ ) return config, inputs_dict def __UpperCAmelCase ( self ) -> Union[str, Any]: _a = self.prepare_config_and_inputs() return config, inputs_dict def __UpperCAmelCase ( self , __magic_name__ , __magic_name__ ) -> int: _a = AutoformerModel(config=__magic_name__ ).to(__magic_name__ ).eval() _a = model(**__magic_name__ ) _a = outputs.encoder_last_hidden_state _a = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: _a = model.get_encoder() encoder.save_pretrained(__magic_name__ ) _a = AutoformerEncoder.from_pretrained(__magic_name__ ).to(__magic_name__ ) _a = model.create_network_inputs(**__magic_name__ ) _a = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) _a = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) _a = encoder(inputs_embeds=__magic_name__ )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 ) _a = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) _a = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) _a = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) _a = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: _a = model.get_decoder() decoder.save_pretrained(__magic_name__ ) _a = AutoformerDecoder.from_pretrained(__magic_name__ ).to(__magic_name__ ) _a = decoder( trend=__magic_name__ , inputs_embeds=__magic_name__ , encoder_hidden_states=__magic_name__ , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 ) @require_torch class a ( _a , _a , unittest.TestCase ): _lowerCAmelCase = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () _lowerCAmelCase = (AutoformerForPrediction,) if is_torch_available() else () _lowerCAmelCase = {'''feature-extraction''': AutoformerModel} if is_torch_available() else {} _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def __UpperCAmelCase ( self ) -> int: _a = AutoformerModelTester(self ) _a = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ ) def __UpperCAmelCase ( self ) -> List[Any]: self.config_tester.run_common_tests() def __UpperCAmelCase ( self ) -> List[Any]: _a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: _a = model_class(__magic_name__ ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__magic_name__ ) _a = model_class.from_pretrained(__magic_name__ , output_loading_info=__magic_name__ ) self.assertEqual(info['missing_keys'] , [] ) def __UpperCAmelCase ( self ) -> Optional[int]: _a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*__magic_name__ ) @unittest.skip(reason='Model has no tokens embeddings' ) def __UpperCAmelCase ( self ) -> Any: pass def __UpperCAmelCase ( self ) -> List[Any]: _a = inspect.signature(getattr(__magic_name__ , 'forward' ) ) # The main input is the name of the argument after `self` _a = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , __magic_name__ ) def __UpperCAmelCase ( self ) -> Optional[Any]: _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a = model_class(__magic_name__ ) _a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a = [*signature.parameters.keys()] _a = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('future_observed_mask' ) expected_arg_names.extend( [ 'decoder_attention_mask', 'head_mask', 'decoder_head_mask', 'cross_attn_head_mask', 'encoder_outputs', 'past_key_values', 'output_hidden_states', 'output_attentions', 'use_cache', 'return_dict', ] ) self.assertListEqual(arg_names[: len(__magic_name__ )] , __magic_name__ ) def __UpperCAmelCase ( self ) -> str: _a = self.model_tester.prepare_config_and_inputs_for_common() _a = True _a = getattr(self.model_tester , 'seq_length' , __magic_name__ ) _a = getattr(self.model_tester , 'decoder_seq_length' , __magic_name__ ) _a = getattr(self.model_tester , 'encoder_seq_length' , __magic_name__ ) _a = getattr(self.model_tester , 'd_model' , __magic_name__ ) _a = getattr(self.model_tester , 'num_attention_heads' , __magic_name__ ) _a = d_model // num_attention_heads for model_class in self.all_model_classes: _a = True _a = False _a = True _a = model_class(__magic_name__ ) model.to(__magic_name__ ) model.eval() with torch.no_grad(): _a = model(**self._prepare_for_class(__magic_name__ , __magic_name__ ) ) _a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__magic_name__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _a = True _a = model_class(__magic_name__ ) model.to(__magic_name__ ) model.eval() with torch.no_grad(): _a = model(**self._prepare_for_class(__magic_name__ , __magic_name__ ) ) _a = outputs.encoder_attentions self.assertEqual(len(__magic_name__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) _a = len(__magic_name__ ) _a = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(__magic_name__ , __magic_name__ ) # decoder attentions _a = outputs.decoder_attentions self.assertIsInstance(__magic_name__ , (list, tuple) ) self.assertEqual(len(__magic_name__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions _a = outputs.cross_attentions self.assertIsInstance(__magic_name__ , (list, tuple) ) self.assertEqual(len(__magic_name__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine _a = True _a = True _a = model_class(__magic_name__ ) model.to(__magic_name__ ) model.eval() with torch.no_grad(): _a = model(**self._prepare_for_class(__magic_name__ , __magic_name__ ) ) self.assertEqual(out_len + 2 , len(__magic_name__ ) ) _a = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__magic_name__ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def __UpperCAmelCase ( self ) -> str: super().test_retain_grad_hidden_states_attentions() def _A (lowerCAmelCase__ :List[Any]="train-batch.pt" ) -> Optional[Any]: '''simple docstring''' _a = hf_hub_download(repo_id='hf-internal-testing/tourism-monthly-batch' , filename=_UpperCamelCase , repo_type='dataset' ) _a = torch.load(_UpperCamelCase , map_location=_UpperCamelCase ) return batch @require_torch @slow class a ( unittest.TestCase ): def __UpperCAmelCase ( self ) -> int: _a = AutoformerModel.from_pretrained('huggingface/autoformer-tourism-monthly' ).to(__magic_name__ ) _a = prepare_batch() with torch.no_grad(): _a = model( past_values=batch['past_values'] , past_time_features=batch['past_time_features'] , past_observed_mask=batch['past_observed_mask'] , static_categorical_features=batch['static_categorical_features'] , future_values=batch['future_values'] , future_time_features=batch['future_time_features'] , )[0] _a = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , __magic_name__ ) _a = torch.tensor( [[0.3_5_9_3, -1.3_3_9_8, 0.6_3_3_0], [0.2_2_7_9, 1.5_3_9_6, -0.1_7_9_2], [0.0_4_5_0, 1.3_2_2_5, -0.2_3_3_5]] , device=__magic_name__ ) self.assertTrue(torch.allclose(output[0, :3, :3] , __magic_name__ , atol=__magic_name__ ) ) def __UpperCAmelCase ( self ) -> Optional[int]: _a = AutoformerForPrediction.from_pretrained('huggingface/autoformer-tourism-monthly' ).to(__magic_name__ ) _a = prepare_batch('val-batch.pt' ) with torch.no_grad(): _a = model( past_values=batch['past_values'] , past_time_features=batch['past_time_features'] , past_observed_mask=batch['past_observed_mask'] , static_categorical_features=batch['static_categorical_features'] , ).encoder_last_hidden_state _a = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , __magic_name__ ) _a = torch.tensor( [[-0.0_7_3_4, -0.9_0_3_6, 0.8_3_5_8], [4.7_1_8_6, 2.4_1_1_3, 1.9_5_8_1], [1.7_9_5_3, 2.3_5_5_8, 1.2_9_7_0]] , device=__magic_name__ ) self.assertTrue(torch.allclose(output[0, :3, :3] , __magic_name__ , atol=__magic_name__ ) ) def __UpperCAmelCase ( self ) -> str: _a = AutoformerForPrediction.from_pretrained('huggingface/autoformer-tourism-monthly' ).to(__magic_name__ ) _a = prepare_batch('val-batch.pt' ) with torch.no_grad(): _a = model.generate( static_categorical_features=batch['static_categorical_features'] , past_time_features=batch['past_time_features'] , past_values=batch['past_values'] , future_time_features=batch['future_time_features'] , past_observed_mask=batch['past_observed_mask'] , ) _a = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , __magic_name__ ) _a = torch.tensor([31_30.67_63, 40_56.52_93, 70_53.07_86] , device=__magic_name__ ) _a = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , __magic_name__ , rtol=1e-1 ) )
168
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" return "\n".join( f'''{number} * {i} = {number * i}''' for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=1_0))
279
0
from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCamelCase__ = {"""tokenization_bertweet""": ["""BertweetTokenizer"""]} if TYPE_CHECKING: from .tokenization_bertweet import BertweetTokenizer else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
302
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCAmelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" snake_case_ : List[str] = ['''layers''', '''blocks'''] for k in ignore_keys: state_dict.pop(_UpperCamelCase , _UpperCamelCase ) lowerCAmelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" snake_case_ : str = list(s_dict.keys() ) for key in keys: snake_case_ : Optional[int] = key for k, v in WHISPER_MAPPING.items(): if k in key: snake_case_ : List[str] = new_key.replace(_UpperCamelCase , _UpperCamelCase ) print(f'''{key} -> {new_key}''' ) snake_case_ : Tuple = s_dict.pop(_UpperCamelCase ) return s_dict def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" snake_case_ , snake_case_ : Dict = emb.weight.shape snake_case_ : Tuple = nn.Linear(_UpperCamelCase , _UpperCamelCase , bias=_UpperCamelCase ) snake_case_ : Any = emb.weight.data return lin_layer def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> bytes: """simple docstring""" os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase ) snake_case_ : List[Any] = os.path.basename(_UpperCamelCase ) snake_case_ : Any = url.split('''/''' )[-2] snake_case_ : str = os.path.join(_UpperCamelCase , _UpperCamelCase ) if os.path.exists(_UpperCamelCase ) and not os.path.isfile(_UpperCamelCase ): raise RuntimeError(f'''{download_target} exists and is not a regular file''' ) if os.path.isfile(_UpperCamelCase ): snake_case_ : Union[str, Any] = open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file''' ) with urllib.request.urlopen(_UpperCamelCase ) as source, open(_UpperCamelCase , '''wb''' ) as output: with tqdm( total=int(source.info().get('''Content-Length''' ) ) , ncols=80 , unit='''iB''' , unit_scale=_UpperCamelCase , unit_divisor=1_024 ) as loop: while True: snake_case_ : Dict = source.read(8_192 ) if not buffer: break output.write(_UpperCamelCase ) loop.update(len(_UpperCamelCase ) ) snake_case_ : Any = open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() != expected_shaaaa: raise RuntimeError( '''Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.''' ) return model_bytes def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" if ".pt" not in checkpoint_path: snake_case_ : str = _download(_MODELS[checkpoint_path] ) else: snake_case_ : Union[str, Any] = torch.load(_UpperCamelCase , map_location='''cpu''' ) snake_case_ : int = original_checkpoint['''dims'''] snake_case_ : List[str] = original_checkpoint['''model_state_dict'''] snake_case_ : str = state_dict['''decoder.token_embedding.weight'''] remove_ignore_keys_(_UpperCamelCase ) rename_keys(_UpperCamelCase ) snake_case_ : Optional[int] = True snake_case_ : int = state_dict['''decoder.layers.0.fc1.weight'''].shape[0] snake_case_ : List[str] = WhisperConfig( vocab_size=dimensions['''n_vocab'''] , encoder_ffn_dim=_UpperCamelCase , decoder_ffn_dim=_UpperCamelCase , num_mel_bins=dimensions['''n_mels'''] , d_model=dimensions['''n_audio_state'''] , max_target_positions=dimensions['''n_text_ctx'''] , encoder_layers=dimensions['''n_audio_layer'''] , encoder_attention_heads=dimensions['''n_audio_head'''] , decoder_layers=dimensions['''n_text_layer'''] , decoder_attention_heads=dimensions['''n_text_state'''] , max_source_positions=dimensions['''n_audio_ctx'''] , ) snake_case_ : Union[str, Any] = WhisperForConditionalGeneration(_UpperCamelCase ) snake_case_ , snake_case_ : List[Any] = model.model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) if len(_UpperCamelCase ) > 0 and not set(_UpperCamelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' f''' but all the following weights are missing {missing}''' ) if tie_embeds: snake_case_ : List[str] = make_linear_from_emb(model.model.decoder.embed_tokens ) else: snake_case_ : Any = proj_out_weights model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCAmelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
279
0
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("TEST_SAGEMAKER" , "False" ) ) is not True , reason="Skipping test because should only be run when releasing minor transformers version" , ) @pytest.mark.usefixtures("sm_env" ) @parameterized_class( [ { "framework": "pytorch", "script": "run_glue.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 650, "eval_accuracy": 0.6, "eval_loss": 0.9}, }, { "framework": "tensorflow", "script": "run_tf.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 600, "eval_accuracy": 0.3, "eval_loss": 0.9}, }, ] ) class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: """simple docstring""" if self.framework == "pytorch": subprocess.run( F"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding='utf-8' , check=_A , ) assert hasattr(self , 'env' ) def UpperCAmelCase_ ( self : str , _A : Optional[Any]=1 ) -> Tuple: """simple docstring""" return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F"""{self.env.base_job_name}-single""" , instance_count=_A , instance_type=self.instance_type , debugger_hook_config=_A , hyperparameters={**self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version='py36' , ) def UpperCAmelCase_ ( self : Tuple , _A : Tuple ) -> List[str]: """simple docstring""" TrainingJobAnalytics(_A ).export_csv(F"""{self.env.test_path}/{job_name}_metrics.csv""" ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" snake_case_ : Optional[Any] = self.create_estimator() # run training estimator.fit() # result dataframe snake_case_ : int = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis snake_case_ : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value'] ) snake_case_ : str = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value'] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping snake_case_ : Union[str, Any] = ( Session().describe_training_job(estimator.latest_training_job.name ).get('TrainingTimeInSeconds' , 999999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy ) assert all(t <= self.results['eval_loss'] for t in eval_loss ) # dump tests result into json file to share in PR with open(F"""{estimator.latest_training_job.name}.json""" , 'w' ) as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} , _A )
327
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCAmelCase_ = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) lowerCAmelCase_ = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 1_4]), ('''2H 5D 3C AS 5S''', False, [1_4, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [1_4, 1_3, 1_2, 1_1, 1_0]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 2_3), ('''JH 9H TH KH QH''', 2_2), ('''JC KH JS JD JH''', 2_1), ('''KH KC 3S 3H 3D''', 2_0), ('''8C 9C 5C 3C TC''', 1_9), ('''JS QS 9H TS KH''', 1_8), ('''7C 7S KH 2H 7H''', 1_7), ('''3C KH 5D 5S KH''', 1_6), ('''QH 8H KD JH 8S''', 1_5), ('''2D 6D 9D TH 7D''', 1_4), ) def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ , snake_case_ : Any = randrange(len(_UpperCamelCase ) ), randrange(len(_UpperCamelCase ) ) snake_case_ : Any = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] snake_case_ , snake_case_ : Tuple = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def lowerCamelCase_ ( _UpperCamelCase = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(_UpperCamelCase )) @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : str = PokerHand(_UpperCamelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[Any]: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = [PokerHand(_UpperCamelCase ) for hand in SORTED_HANDS] snake_case_ : str = poker_hands.copy() shuffle(_UpperCamelCase ) snake_case_ : List[str] = chain(sorted(_UpperCamelCase ) ) for index, hand in enumerate(_UpperCamelCase ): assert hand == poker_hands[index] def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ : Union[str, Any] = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=_UpperCamelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = PokerHand('''2C 4S AS 3D 5C''' ) snake_case_ : str = True snake_case_ : Tuple = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def lowerCamelCase_ ( ) -> List[str]: """simple docstring""" snake_case_ : List[str] = 0 snake_case_ : Union[str, Any] = os.path.abspath(os.path.dirname(_UpperCamelCase ) ) snake_case_ : Dict = os.path.join(_UpperCamelCase , '''poker_hands.txt''' ) with open(_UpperCamelCase ) as file_hand: for line in file_hand: snake_case_ : Dict = line[:14].strip() snake_case_ : List[str] = line[15:].strip() snake_case_ , snake_case_ : str = PokerHand(_UpperCamelCase ), PokerHand(_UpperCamelCase ) snake_case_ : int = player.compare_with(_UpperCamelCase ) if output == "Win": answer += 1 assert answer == 376
279
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
276
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available lowerCAmelCase_ = logging.getLogger(__name__) @dataclass class __lowerCAmelCase : lowerCamelCase_ : str lowerCamelCase_ : List[str] lowerCamelCase_ : Optional[List[str]] @dataclass class __lowerCAmelCase : lowerCamelCase_ : List[int] lowerCamelCase_ : List[int] lowerCamelCase_ : Optional[List[int]] = None lowerCamelCase_ : Optional[List[int]] = None class __lowerCAmelCase ( _a ): lowerCamelCase_ : str = '''train''' lowerCamelCase_ : List[str] = '''dev''' lowerCamelCase_ : List[Any] = '''test''' class __lowerCAmelCase : @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def lowerCamelCase (__magic_name__ ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=False , __magic_name__="[CLS]" , __magic_name__=1 , __magic_name__="[SEP]" , __magic_name__=False , __magic_name__=False , __magic_name__=0 , __magic_name__=0 , __magic_name__=-100 , __magic_name__=0 , __magic_name__=True , ) -> List[InputFeatures]: '''simple docstring''' snake_case_ : Optional[int] = {label: i for i, label in enumerate(__magic_name__ )} snake_case_ : Dict = [] for ex_index, example in enumerate(__magic_name__ ): if ex_index % 1_0000 == 0: logger.info('''Writing example %d of %d''' , __magic_name__ , len(__magic_name__ ) ) snake_case_ : List[str] = [] snake_case_ : List[str] = [] for word, label in zip(example.words , example.labels ): snake_case_ : Optional[Any] = tokenizer.tokenize(__magic_name__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(__magic_name__ ) > 0: tokens.extend(__magic_name__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__magic_name__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. snake_case_ : Union[str, Any] = tokenizer.num_special_tokens_to_add() if len(__magic_name__ ) > max_seq_length - special_tokens_count: snake_case_ : str = tokens[: (max_seq_length - special_tokens_count)] snake_case_ : Any = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] snake_case_ : Union[str, Any] = [sequence_a_segment_id] * len(__magic_name__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: snake_case_ : Union[str, Any] = [cls_token] + tokens snake_case_ : List[Any] = [pad_token_label_id] + label_ids snake_case_ : Optional[Any] = [cls_token_segment_id] + segment_ids snake_case_ : Optional[Any] = tokenizer.convert_tokens_to_ids(__magic_name__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. snake_case_ : int = [1 if mask_padding_with_zero else 0] * len(__magic_name__ ) # Zero-pad up to the sequence length. snake_case_ : Optional[int] = max_seq_length - len(__magic_name__ ) if pad_on_left: snake_case_ : Optional[Any] = ([pad_token] * padding_length) + input_ids snake_case_ : Optional[int] = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask snake_case_ : Optional[Any] = ([pad_token_segment_id] * padding_length) + segment_ids snake_case_ : Dict = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(__magic_name__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(__magic_name__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: snake_case_ : int = None features.append( InputFeatures( input_ids=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , label_ids=__magic_name__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[InputFeatures] lowerCamelCase_ : int = nn.CrossEntropyLoss().ignore_index def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=False , __magic_name__ = Split.train , ) -> Union[str, Any]: '''simple docstring''' snake_case_ : List[str] = os.path.join( __magic_name__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(__magic_name__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case_ : Dict = cached_features_file + '''.lock''' with FileLock(__magic_name__ ): if os.path.exists(__magic_name__ ) and not overwrite_cache: logger.info(F'''Loading features from cached file {cached_features_file}''' ) snake_case_ : Dict = torch.load(__magic_name__ ) else: logger.info(F'''Creating features from dataset file at {data_dir}''' ) snake_case_ : Any = token_classification_task.read_examples_from_file(__magic_name__ , __magic_name__ ) # TODO clean up all this to leverage built-in features of tokenizers snake_case_ : int = token_classification_task.convert_examples_to_features( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , __magic_name__ ) def __len__(self ) -> Optional[Any]: '''simple docstring''' return len(self.features ) def __getitem__(self , __magic_name__ ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class __lowerCAmelCase : lowerCamelCase_ : List[InputFeatures] lowerCamelCase_ : int = -100 def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=False , __magic_name__ = Split.train , ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[int] = token_classification_task.read_examples_from_file(__magic_name__ , __magic_name__ ) # TODO clean up all this to leverage built-in features of tokenizers snake_case_ : int = token_classification_task.convert_examples_to_features( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: snake_case_ : Optional[Any] = tf.data.Dataset.from_generator( __magic_name__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: snake_case_ : int = tf.data.Dataset.from_generator( __magic_name__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__(self ) -> str: '''simple docstring''' return len(self.features ) def __getitem__(self , __magic_name__ ) -> InputFeatures: '''simple docstring''' return self.features[i]
279
0
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def lowercase (_lowerCAmelCase ): return x + 2 class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def A__ ( self ) -> Union[str, Any]: __lowerCAmelCase = '''x = 3''' __lowerCAmelCase = {} __lowerCAmelCase = evaluate(snake_case_ , {} , state=snake_case_ ) assert result == 3 self.assertDictEqual(snake_case_ , {"""x""": 3} ) __lowerCAmelCase = '''x = y''' __lowerCAmelCase = {'''y''': 5} __lowerCAmelCase = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(snake_case_ , {"""x""": 5, """y""": 5} ) def A__ ( self ) -> List[str]: __lowerCAmelCase = '''y = add_two(x)''' __lowerCAmelCase = {'''x''': 3} __lowerCAmelCase = evaluate(snake_case_ , {"""add_two""": add_two} , state=snake_case_ ) assert result == 5 self.assertDictEqual(snake_case_ , {"""x""": 3, """y""": 5} ) # Won't work without the tool with CaptureStdout() as out: __lowerCAmelCase = evaluate(snake_case_ , {} , state=snake_case_ ) assert result is None assert "tried to execute add_two" in out.out def A__ ( self ) -> Union[str, Any]: __lowerCAmelCase = '''x = 3''' __lowerCAmelCase = {} __lowerCAmelCase = evaluate(snake_case_ , {} , state=snake_case_ ) assert result == 3 self.assertDictEqual(snake_case_ , {"""x""": 3} ) def A__ ( self ) -> Any: __lowerCAmelCase = '''test_dict = {\'x\': x, \'y\': add_two(x)}''' __lowerCAmelCase = {'''x''': 3} __lowerCAmelCase = evaluate(snake_case_ , {"""add_two""": add_two} , state=snake_case_ ) self.assertDictEqual(snake_case_ , {"""x""": 3, """y""": 5} ) self.assertDictEqual(snake_case_ , {"""x""": 3, """test_dict""": {"""x""": 3, """y""": 5}} ) def A__ ( self ) -> str: __lowerCAmelCase = '''x = 3\ny = 5''' __lowerCAmelCase = {} __lowerCAmelCase = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(snake_case_ , {"""x""": 3, """y""": 5} ) def A__ ( self ) -> Dict: __lowerCAmelCase = '''text = f\'This is x: {x}.\'''' __lowerCAmelCase = {'''x''': 3} __lowerCAmelCase = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(snake_case_ , {"""x""": 3, """text""": """This is x: 3."""} ) def A__ ( self ) -> Tuple: __lowerCAmelCase = '''if x <= 3:\n y = 2\nelse:\n y = 5''' __lowerCAmelCase = {'''x''': 3} __lowerCAmelCase = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(snake_case_ , {"""x""": 3, """y""": 2} ) __lowerCAmelCase = {'''x''': 8} __lowerCAmelCase = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(snake_case_ , {"""x""": 8, """y""": 5} ) def A__ ( self ) -> List[Any]: __lowerCAmelCase = '''test_list = [x, add_two(x)]''' __lowerCAmelCase = {'''x''': 3} __lowerCAmelCase = evaluate(snake_case_ , {"""add_two""": add_two} , state=snake_case_ ) self.assertListEqual(snake_case_ , [3, 5] ) self.assertDictEqual(snake_case_ , {"""x""": 3, """test_list""": [3, 5]} ) def A__ ( self ) -> Dict: __lowerCAmelCase = '''y = x''' __lowerCAmelCase = {'''x''': 3} __lowerCAmelCase = evaluate(snake_case_ , {} , state=snake_case_ ) assert result == 3 self.assertDictEqual(snake_case_ , {"""x""": 3, """y""": 3} ) def A__ ( self ) -> Union[str, Any]: __lowerCAmelCase = '''test_list = [x, add_two(x)]\ntest_list[1]''' __lowerCAmelCase = {'''x''': 3} __lowerCAmelCase = evaluate(snake_case_ , {"""add_two""": add_two} , state=snake_case_ ) assert result == 5 self.assertDictEqual(snake_case_ , {"""x""": 3, """test_list""": [3, 5]} ) __lowerCAmelCase = '''test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']''' __lowerCAmelCase = {'''x''': 3} __lowerCAmelCase = evaluate(snake_case_ , {"""add_two""": add_two} , state=snake_case_ ) assert result == 5 self.assertDictEqual(snake_case_ , {"""x""": 3, """test_dict""": {"""x""": 3, """y""": 5}} ) def A__ ( self ) -> Optional[int]: __lowerCAmelCase = '''x = 0\nfor i in range(3):\n x = i''' __lowerCAmelCase = {} __lowerCAmelCase = evaluate(snake_case_ , {"""range""": range} , state=snake_case_ ) assert result == 2 self.assertDictEqual(snake_case_ , {"""x""": 2, """i""": 2} )
301
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir('''fixtures/test_sentencepiece_bpe_char.model''') @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[int] = SpeechTaTokenizer lowerCamelCase_ : int = False lowerCamelCase_ : Dict = True def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing snake_case_ : Tuple = SpeechTaTokenizer(__magic_name__ ) snake_case_ : Any = AddedToken('''<mask>''' , lstrip=__magic_name__ , rstrip=__magic_name__ ) snake_case_ : int = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Dict = '''this is a test''' snake_case_ : int = '''this is a test''' return input_text, output_text def lowerCamelCase (self , __magic_name__ , __magic_name__=False , __magic_name__=20 , __magic_name__=5 ) -> List[Any]: '''simple docstring''' snake_case_ , snake_case_ : int = self.get_input_output_texts(__magic_name__ ) snake_case_ : Optional[Any] = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) snake_case_ : Any = tokenizer.decode(__magic_name__ , clean_up_tokenization_spaces=__magic_name__ ) return text, ids def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[str] = '''<pad>''' snake_case_ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__magic_name__ ) , 81 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : int = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): snake_case_ : int = tokenizer.vocab_size snake_case_ : Optional[Any] = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case_ : List[Any] = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] snake_case_ : List[Any] = tokenizer.add_tokens(__magic_name__ ) snake_case_ : Dict = tokenizer.vocab_size snake_case_ : Optional[Any] = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size + len(__magic_name__ ) ) snake_case_ : Union[str, Any] = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case_ : Union[str, Any] = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} snake_case_ : List[str] = tokenizer.add_special_tokens(__magic_name__ ) snake_case_ : Dict = tokenizer.vocab_size snake_case_ : Dict = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size_a + len(__magic_name__ ) ) snake_case_ : Tuple = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> List[str]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.get_tokenizer() snake_case_ : Optional[Any] = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__magic_name__ , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case_ : List[Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) snake_case_ : List[str] = tokenizer.convert_tokens_to_ids(__magic_name__ ) # fmt: off self.assertListEqual(__magic_name__ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case_ : int = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Tuple = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off snake_case_ : List[Any] = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__magic_name__ , )
279
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """bigcode/gpt_bigcode-santacoder""": """https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json""", } class UpperCamelCase__ ( _a ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''gpt_bigcode''' SCREAMING_SNAKE_CASE__ = ['''past_key_values'''] SCREAMING_SNAKE_CASE__ = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Tuple , lowerCamelCase_ : Dict=5_02_57 , lowerCamelCase_ : List[Any]=10_24 , lowerCamelCase_ : List[Any]=7_68 , lowerCamelCase_ : Union[str, Any]=12 , lowerCamelCase_ : Optional[int]=12 , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : List[str]="gelu_pytorch_tanh" , lowerCamelCase_ : Optional[Any]=0.1 , lowerCamelCase_ : Dict=0.1 , lowerCamelCase_ : Optional[int]=0.1 , lowerCamelCase_ : int=1e-5 , lowerCamelCase_ : str=0.02 , lowerCamelCase_ : Dict=True , lowerCamelCase_ : Tuple=True , lowerCamelCase_ : Tuple=5_02_56 , lowerCamelCase_ : str=5_02_56 , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : List[Any]=True , lowerCamelCase_ : str=True , **lowerCamelCase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : int = n_positions SCREAMING_SNAKE_CASE : Optional[Any] = n_embd SCREAMING_SNAKE_CASE : List[str] = n_layer SCREAMING_SNAKE_CASE : Optional[int] = n_head SCREAMING_SNAKE_CASE : Any = n_inner SCREAMING_SNAKE_CASE : List[Any] = activation_function SCREAMING_SNAKE_CASE : Optional[Any] = resid_pdrop SCREAMING_SNAKE_CASE : Dict = embd_pdrop SCREAMING_SNAKE_CASE : List[str] = attn_pdrop SCREAMING_SNAKE_CASE : Any = layer_norm_epsilon SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE : str = scale_attn_weights SCREAMING_SNAKE_CASE : Union[str, Any] = use_cache SCREAMING_SNAKE_CASE : Any = attention_softmax_in_fpaa SCREAMING_SNAKE_CASE : Optional[int] = scale_attention_softmax_in_fpaa SCREAMING_SNAKE_CASE : Optional[int] = multi_query SCREAMING_SNAKE_CASE : List[Any] = bos_token_id SCREAMING_SNAKE_CASE : Union[str, Any] = eos_token_id super().__init__(bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , **lowerCamelCase_ )
323
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' ) for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): if dist[i][j] != float('''inf''' ): print(int(dist[i][j] ) , end='''\t''' ) else: print('''INF''' , end='''\t''' ) print() def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : int = [[float('''inf''' ) for _ in range(_UpperCamelCase )] for _ in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): snake_case_ : Dict = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(_UpperCamelCase ): # looping through rows of graph array for i in range(_UpperCamelCase ): # looping through columns of graph array for j in range(_UpperCamelCase ): if ( dist[i][k] != float('''inf''' ) and dist[k][j] != float('''inf''' ) and dist[i][k] + dist[k][j] < dist[i][j] ): snake_case_ : List[Any] = dist[i][k] + dist[k][j] _print_dist(_UpperCamelCase , _UpperCamelCase ) return dist, v if __name__ == "__main__": lowerCAmelCase_ = int(input('''Enter number of vertices: ''')) lowerCAmelCase_ = int(input('''Enter number of edges: ''')) lowerCAmelCase_ = [[float('''inf''') for i in range(v)] for j in range(v)] for i in range(v): lowerCAmelCase_ = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print('''\nEdge ''', i + 1) lowerCAmelCase_ = int(input('''Enter source:''')) lowerCAmelCase_ = int(input('''Enter destination:''')) lowerCAmelCase_ = float(input('''Enter weight:''')) lowerCAmelCase_ = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
279
0
"""simple docstring""" import operator def lowercase__( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : List[Any] = False , __SCREAMING_SNAKE_CASE : Tuple = None ): lowercase_ : List[str] = operator.lt if reverse else operator.gt lowercase_ : List[Any] = solution or [] if not arr: return solution lowercase_ : Dict = [arr.pop(0 )] for i, item in enumerate(_UpperCamelCase ): if _operator(_UpperCamelCase , sublist[-1] ): sublist.append(_UpperCamelCase ) arr.pop(_UpperCamelCase ) # merging sublist into solution list if not solution: solution.extend(_UpperCamelCase ) else: while sublist: lowercase_ : Any = sublist.pop(0 ) for i, xx in enumerate(_UpperCamelCase ): if not _operator(_UpperCamelCase , _UpperCamelCase ): solution.insert(_UpperCamelCase , _UpperCamelCase ) break else: solution.append(_UpperCamelCase ) strand_sort(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) return solution if __name__ == "__main__": assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]
213
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class __lowerCAmelCase : def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' return None class __lowerCAmelCase : def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' return None class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Dict = [ # (model_name, model_kwargs) ('''bert-base-cased''', {}), ('''gpt2''', {'''use_cache''': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__magic_name__ , '''tf''' , 12 , **__magic_name__ ) @require_torch @slow def lowerCamelCase (self ) -> int: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__magic_name__ , '''pt''' , 12 , **__magic_name__ ) @require_torch @slow def lowerCamelCase (self ) -> int: '''simple docstring''' from transformers import BertModel snake_case_ : str = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(__magic_name__ ) ) vocab_file.flush() snake_case_ : Optional[Any] = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: snake_case_ : str = BertModel(BertConfig(vocab_size=len(__magic_name__ ) ) ) model.save_pretrained(__magic_name__ ) self._test_export(__magic_name__ , '''pt''' , 12 , __magic_name__ ) @require_tf @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ : Tuple = self._test_export(__magic_name__ , '''tf''' , 12 , **__magic_name__ ) snake_case_ : List[str] = quantize(Path(__magic_name__ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__magic_name__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ : Any = self._test_export(__magic_name__ , '''pt''' , 12 , **__magic_name__ ) snake_case_ : Any = quantize(__magic_name__ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__magic_name__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None , **__magic_name__ ) -> Tuple: '''simple docstring''' try: # Compute path with TemporaryDirectory() as tempdir: snake_case_ : List[str] = Path(__magic_name__ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) return path except Exception as e: self.fail(__magic_name__ ) @require_torch @require_tokenizers @slow def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' from transformers import BertModel snake_case_ : Optional[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case_ : int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(__magic_name__ , __magic_name__ , '''pt''' ) @require_tf @require_tokenizers @slow def lowerCamelCase (self ) -> List[str]: '''simple docstring''' from transformers import TFBertModel snake_case_ : Any = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case_ : str = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(__magic_name__ , __magic_name__ , '''tf''' ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : Tuple = FeatureExtractionPipeline(__magic_name__ , __magic_name__ ) snake_case_ : Optional[int] = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] snake_case_ , snake_case_ , snake_case_ , snake_case_ : Optional[int] = infer_shapes(__magic_name__ , __magic_name__ ) # Assert all variables are present self.assertEqual(len(__magic_name__ ) , len(__magic_name__ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __magic_name__ ) self.assertSequenceEqual(variable_names[3:] , __magic_name__ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Tuple = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] snake_case_ : List[str] = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} snake_case_ , snake_case_ : Tuple = ensure_valid_input(FuncContiguousArgs() , __magic_name__ , __magic_name__ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__magic_name__ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__magic_name__ ) , set(__magic_name__ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__magic_name__ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) snake_case_ , snake_case_ : Dict = ensure_valid_input(FuncNonContiguousArgs() , __magic_name__ , __magic_name__ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Optional[int] = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
279
0
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __snake_case = logging.get_logger(__name__) __snake_case = {'''vocab_file''': '''spiece.model'''} __snake_case = { '''vocab_file''': { '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''', } } __snake_case = { '''AI-Sweden/gpt-sw3-126m''': 20_48, '''AI-Sweden/gpt-sw3-350m''': 20_48, '''AI-Sweden/gpt-sw3-1.6b''': 20_48, '''AI-Sweden/gpt-sw3-6.7b''': 20_48, '''AI-Sweden/gpt-sw3-20b''': 20_48, } class __snake_case ( _a ): __lowerCamelCase : List[Any] = VOCAB_FILES_NAMES __lowerCamelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : Tuple = ['''input_ids''', '''attention_mask'''] def __init__( self , snake_case__ , snake_case__=False , snake_case__=False , snake_case__=False , snake_case__=None , snake_case__=None , snake_case__=None , snake_case__=None , snake_case__ = None , **snake_case__ , ) -> None: '''simple docstring''' UpperCAmelCase : List[str] ={} if sp_model_kwargs is None else sp_model_kwargs UpperCAmelCase : Union[str, Any] =kwargs.get('''name_or_path''' ) if name_or_path is None: logger.warning( '''name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,''' ''' you are testing the model, this can safely be ignored''' ) UpperCAmelCase : Dict ='''None''' # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing UpperCAmelCase : str ='''<|endoftext|>''' if eos_token is None else eos_token UpperCAmelCase : str ='''<unk>''' if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: UpperCAmelCase : Dict =unk_token if pad_token is None else pad_token UpperCAmelCase : List[str] =eos_token if bos_token is None else bos_token else: UpperCAmelCase : Tuple ='''<pad>''' if pad_token is None else pad_token UpperCAmelCase : Optional[int] ='''<s>''' if bos_token is None else bos_token super().__init__( do_lower_case=snake_case__ , remove_space=snake_case__ , keep_accents=snake_case__ , bos_token=snake_case__ , eos_token=snake_case__ , unk_token=snake_case__ , pad_token=snake_case__ , sp_model_kwargs=self.sp_model_kwargs , **snake_case__ , ) UpperCAmelCase : Dict =do_lower_case UpperCAmelCase : Optional[Any] =remove_space UpperCAmelCase : Optional[Any] =keep_accents UpperCAmelCase : Tuple =vocab_file UpperCAmelCase : Dict =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case__ ) # Used for whitespace normalization in input texts # fmt : off UpperCAmelCase : List[Any] ={''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', '''''', '''„'''} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing UpperCAmelCase : str =re.compile( f'''[{''.join(map(snake_case__ , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]''' ) def __getstate__( self ) -> Tuple: '''simple docstring''' UpperCAmelCase : List[str] =self.__dict__.copy() UpperCAmelCase : Tuple =None return state def __setstate__( self , snake_case__ ) -> Optional[int]: '''simple docstring''' UpperCAmelCase : Optional[int] =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCAmelCase : Tuple ={} UpperCAmelCase : Any =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' return len(self.sp_model ) def UpperCAmelCase__ ( self , snake_case__ ) -> str: '''simple docstring''' UpperCAmelCase : Dict =self.non_printing_characters_re.sub('''''' , snake_case__ ) # Normalize whitespaces UpperCAmelCase : Optional[int] =''''''.join([char if char not in self.whitespaces else ''' ''' for char in text] ) # NFC Unicode normalization UpperCAmelCase : Union[str, Any] =unicodedata.normalize('''NFC''' , snake_case__ ) return text def UpperCAmelCase__ ( self , snake_case__ , **snake_case__ ) -> List[str]: '''simple docstring''' UpperCAmelCase : Dict =self.preprocess_text(snake_case__ ) return self.sp_model.encode(snake_case__ , out_type=snake_case__ ) def UpperCAmelCase__ ( self , snake_case__ ) -> int: '''simple docstring''' return self.sp_model.PieceToId(snake_case__ ) def UpperCAmelCase__ ( self , snake_case__ ) -> str: '''simple docstring''' return self.sp_model.IdToPiece(snake_case__ ) @staticmethod def UpperCAmelCase__ ( snake_case__ ) -> str: '''simple docstring''' return out_string def UpperCAmelCase__ ( self , snake_case__ ) -> str: '''simple docstring''' UpperCAmelCase : Union[str, Any] =[] UpperCAmelCase : Dict ='''''' UpperCAmelCase : int =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(snake_case__ ) + token UpperCAmelCase : Dict =True UpperCAmelCase : List[Any] =[] else: current_sub_tokens.append(snake_case__ ) UpperCAmelCase : Dict =False out_string += self.sp_model.decode(snake_case__ ) return out_string def UpperCAmelCase__ ( self ) -> Dict[str, int]: '''simple docstring''' UpperCAmelCase : str ={self.convert_ids_to_tokens(snake_case__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCAmelCase__ ( self , snake_case__ , snake_case__ = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(snake_case__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return UpperCAmelCase : List[str] =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: UpperCAmelCase : Union[str, Any] =self.sp_model.serialized_model_proto() fi.write(snake_case__ ) return (out_vocab_file,) def UpperCAmelCase__ ( self , snake_case__ , snake_case__ = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: '''simple docstring''' if isinstance(snake_case__ , snake_case__ ): UpperCAmelCase : List[str] =self.preprocess_text(snake_case__ ) UpperCAmelCase : List[str] =self.sp_model.encode(snake_case__ ) else: UpperCAmelCase : Dict =[self.preprocess_text(snake_case__ ) for t in text] UpperCAmelCase : Union[str, Any] =self.sp_model.encode(snake_case__ ) if return_tensors is True or return_tensors == "pt": UpperCAmelCase : List[Any] =torch.tensor(snake_case__ ) return token_ids def UpperCAmelCase__ ( self , snake_case__ ) -> str: '''simple docstring''' return self.sp_model.decode(snake_case__ ) def UpperCAmelCase__ ( self , snake_case__ ) -> List[int]: '''simple docstring''' UpperCAmelCase : Dict =[f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] UpperCAmelCase : Any =( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(snake_case__ ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=snake_case__ )
348
lowerCAmelCase_ = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.602_176_634e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.355_818, } def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: snake_case_ : str = ( f'''Incorrect \'from_type\' or \'to_type\' value: {from_type!r}, {to_type!r}\n''' f'''Valid values are: {", ".join(_UpperCamelCase )}''' ) raise ValueError(_UpperCamelCase ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
279
0
'''simple docstring''' import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class UpperCamelCase__ ( unittest.TestCase): UpperCAmelCase__ : Any = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def lowercase_ ( self :List[Any] , _A :Dict , _A :List[str] , _A :str ) -> Dict: '''simple docstring''' __A = hf_hub_download( repo_id='nateraw/video-demo' , filename='archery.mp4' , repo_type='dataset' ) __A = VideoClassificationPipeline(model=_A , image_processor=_A , top_k=2 ) __A = [ example_video_filepath, '''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''', ] return video_classifier, examples def lowercase_ ( self :int , _A :List[str] , _A :List[Any] ) -> Any: '''simple docstring''' for example in examples: __A = video_classifier(_A ) self.assertEqual( _A , [ {'score': ANY(_A ), 'label': ANY(_A )}, {'score': ANY(_A ), 'label': ANY(_A )}, ] , ) @require_torch def lowercase_ ( self :str ) -> str: '''simple docstring''' __A = '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification''' __A = VideoMAEFeatureExtractor( size={'shortest_edge': 10} , crop_size={'height': 10, 'width': 10} ) __A = pipeline( 'video-classification' , model=_A , feature_extractor=_A , frame_sampling_rate=4 ) __A = hf_hub_download(repo_id='nateraw/video-demo' , filename='archery.mp4' , repo_type='dataset' ) __A = video_classifier(_A , top_k=2 ) self.assertEqual( nested_simplify(_A , decimals=4 ) , [{'score': 0.5_199, 'label': 'LABEL_0'}, {'score': 0.4_801, 'label': 'LABEL_1'}] , ) __A = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(_A , decimals=4 ) , [ [{'score': 0.5_199, 'label': 'LABEL_0'}, {'score': 0.4_801, 'label': 'LABEL_1'}], [{'score': 0.5_199, 'label': 'LABEL_0'}, {'score': 0.4_801, 'label': 'LABEL_1'}], ] , ) @require_tf def lowercase_ ( self :List[Any] ) -> Optional[int]: '''simple docstring''' pass
161
import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets lowerCAmelCase_ = datasets.logging.get_logger(__name__) lowerCAmelCase_ = '''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } ''' lowerCAmelCase_ = '''\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project\'s README at https://github.com/google-research/bleurt#readme for more information. ''' lowerCAmelCase_ = ''' BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: \'scores\': List of scores. Examples: >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> bleurt = datasets.load_metric("bleurt") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results["scores"]]) [1.03, 1.04] ''' lowerCAmelCase_ = { '''bleurt-tiny-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip''', '''bleurt-tiny-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip''', '''bleurt-base-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip''', '''bleurt-base-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip''', '''bleurt-large-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip''', '''bleurt-large-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip''', '''BLEURT-20-D3''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip''', '''BLEURT-20-D6''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip''', '''BLEURT-20-D12''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip''', '''BLEURT-20''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip''', } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/google-research/bleurt''' , 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/bleurt'''] , reference_urls=['''https://github.com/google-research/bleurt''', '''https://arxiv.org/abs/2004.04696'''] , ) def lowerCamelCase (self , __magic_name__ ) -> List[Any]: '''simple docstring''' if self.config_name == "default": logger.warning( '''Using default BLEURT-Base checkpoint for sequence maximum length 128. ''' '''You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').''' ) snake_case_ : Dict = '''bleurt-base-128''' if self.config_name.lower() in CHECKPOINT_URLS: snake_case_ : Optional[int] = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: snake_case_ : Union[str, Any] = self.config_name.upper() else: raise KeyError( F'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}''' ) # download the model checkpoint specified by self.config_name and set up the scorer snake_case_ : Any = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) snake_case_ : Dict = score.BleurtScorer(os.path.join(__magic_name__ , __magic_name__ ) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Dict = self.scorer.score(references=__magic_name__ , candidates=__magic_name__ ) return {"scores": scores}
279
0
import unittest import numpy as np def a ( snake_case__: Optional[Any] , snake_case__: List[str] , snake_case__: List[Any] , snake_case__: Any = None , ): '''simple docstring''' lowercase_ = np.shape(_UpperCamelCase ) lowercase_ = np.shape(_UpperCamelCase ) lowercase_ = np.shape(_UpperCamelCase ) if shape_a[0] != shape_b[0]: lowercase_ = ( '''Expected the same number of rows for A and B. ''' F'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(_UpperCamelCase ) if shape_b[1] != shape_c[1]: lowercase_ = ( '''Expected the same number of columns for B and C. ''' F'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(_UpperCamelCase ) lowercase_ = pseudo_inv if a_inv is None: try: lowercase_ = np.linalg.inv(_UpperCamelCase ) except np.linalg.LinAlgError: raise ValueError( '''Input matrix A is not invertible. Cannot compute Schur complement.''' ) return mat_c - mat_b.T @ a_inv @ mat_b class lowercase__( unittest.TestCase ): """simple docstring""" def _lowercase ( self : Tuple ) -> None: lowercase_ = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) lowercase_ = np.array([[0, 3], [3, 0], [2, 3]] ) lowercase_ = np.array([[2, 1], [6, 3]] ) lowercase_ = schur_complement(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowercase_ = np.block([[a, b], [b.T, c]] ) lowercase_ = np.linalg.det(SCREAMING_SNAKE_CASE_ ) lowercase_ = np.linalg.det(SCREAMING_SNAKE_CASE_ ) lowercase_ = np.linalg.det(SCREAMING_SNAKE_CASE_ ) self.assertAlmostEqual(SCREAMING_SNAKE_CASE_ , det_a * det_s ) def _lowercase ( self : int ) -> None: lowercase_ = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) lowercase_ = np.array([[0, 3], [3, 0], [2, 3]] ) lowercase_ = np.array([[2, 1], [6, 3]] ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): schur_complement(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Tuple ) -> None: lowercase_ = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) lowercase_ = np.array([[0, 3], [3, 0], [2, 3]] ) lowercase_ = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): schur_complement(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
30
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''): lowerCAmelCase_ = { '''linear''': PIL.Image.Resampling.BILINEAR, '''bilinear''': PIL.Image.Resampling.BILINEAR, '''bicubic''': PIL.Image.Resampling.BICUBIC, '''lanczos''': PIL.Image.Resampling.LANCZOS, '''nearest''': PIL.Image.Resampling.NEAREST, } else: lowerCAmelCase_ = { '''linear''': PIL.Image.LINEAR, '''bilinear''': PIL.Image.BILINEAR, '''bicubic''': PIL.Image.BICUBIC, '''lanczos''': PIL.Image.LANCZOS, '''nearest''': PIL.Image.NEAREST, } def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : Dict = (images / 2 + 0.5).clamp(0 , 1 ) snake_case_ : Dict = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() snake_case_ : int = numpy_to_pil(_UpperCamelCase ) return images def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" if images.ndim == 3: snake_case_ : Optional[Any] = images[None, ...] snake_case_ : Any = (images * 255).round().astype('''uint8''' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images snake_case_ : str = [Image.fromarray(image.squeeze() , mode='''L''' ) for image in images] else: snake_case_ : List[Any] = [Image.fromarray(_UpperCamelCase ) for image in images] return pil_images
279
0
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTokenizer a_ = logging.get_logger(__name__) a_ = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} # See all MVP models at https://huggingface.co/models?filter=mvp a_ = { """vocab_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json""", }, """added_tokens.json""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json""", }, """merges_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt""", }, """tokenizer_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json""", }, } a_ = { """RUCAIBox/mvp""": 1_024, } class __lowerCAmelCase ( _a ): lowerCAmelCase__ = VOCAB_FILES_NAMES lowerCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ = ['''input_ids''', '''attention_mask'''] lowerCAmelCase__ = MvpTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="replace" , __UpperCAmelCase="<s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="<s>" , __UpperCAmelCase="<unk>" , __UpperCAmelCase="<pad>" , __UpperCAmelCase="<mask>" , __UpperCAmelCase=False , __UpperCAmelCase=True , **__UpperCAmelCase , ): '''simple docstring''' super().__init__( __UpperCAmelCase , __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , errors=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase , trim_offsets=__UpperCAmelCase , **__UpperCAmelCase , ) __lowerCamelCase = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , __UpperCAmelCase ) != add_prefix_space: __lowerCamelCase = getattr(__UpperCAmelCase , pre_tok_state.pop('''type''' ) ) __lowerCamelCase = add_prefix_space __lowerCamelCase = pre_tok_class(**__UpperCAmelCase ) __lowerCamelCase = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` __lowerCamelCase = '''post_processor''' __lowerCamelCase = getattr(self.backend_tokenizer , __UpperCAmelCase , __UpperCAmelCase ) if tokenizer_component_instance: __lowerCamelCase = 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: __lowerCamelCase = tuple(state['''sep'''] ) if "cls" in state: __lowerCamelCase = tuple(state['''cls'''] ) __lowerCamelCase = False if state.get('''add_prefix_space''' , __UpperCAmelCase ) != add_prefix_space: __lowerCamelCase = add_prefix_space __lowerCamelCase = True if state.get('''trim_offsets''' , __UpperCAmelCase ) != trim_offsets: __lowerCamelCase = trim_offsets __lowerCamelCase = True if changes_to_apply: __lowerCamelCase = getattr(__UpperCAmelCase , state.pop('''type''' ) ) __lowerCamelCase = component_class(**__UpperCAmelCase ) setattr(self.backend_tokenizer , __UpperCAmelCase , __UpperCAmelCase ) @property def lowerCamelCase ( self ): '''simple docstring''' 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 , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else value __lowerCamelCase = value def lowerCamelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = kwargs.get('''is_split_into_words''' , __UpperCAmelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*__UpperCAmelCase , **__UpperCAmelCase ) def lowerCamelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = kwargs.get('''is_split_into_words''' , __UpperCAmelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*__UpperCAmelCase , **__UpperCAmelCase ) def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' __lowerCamelCase = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase ) def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase=None ): '''simple docstring''' __lowerCamelCase = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [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]
330
import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Any = BioGptTokenizer lowerCamelCase_ : Optional[Any] = False def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case_ : Optional[Any] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] snake_case_ : Union[str, Any] = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) snake_case_ : Union[str, Any] = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] snake_case_ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(__magic_name__ ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(__magic_name__ ) ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : str = '''lower newer''' snake_case_ : Dict = '''lower newer''' return input_text, output_text def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Optional[int] = BioGptTokenizer(self.vocab_file , self.merges_file ) snake_case_ : Union[str, Any] = '''lower''' snake_case_ : Optional[int] = ['''low''', '''er</w>'''] snake_case_ : Any = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) snake_case_ : Optional[int] = tokens + ['''<unk>'''] snake_case_ : List[str] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) @slow def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) snake_case_ : List[Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=__magic_name__ ) snake_case_ : str = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__magic_name__ ) snake_case_ : str = tokenizer.build_inputs_with_special_tokens(__magic_name__ ) snake_case_ : List[str] = tokenizer.build_inputs_with_special_tokens(__magic_name__ , __magic_name__ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
279
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a_ : Tuple = logging.get_logger(__name__) a_ : Optional[int] = { "facebook/data2vec-vision-base-ft": ( "https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json" ), } class a ( _a ): _lowerCAmelCase = '''data2vec-vision''' def __init__( self , __magic_name__=7_68 , __magic_name__=12 , __magic_name__=12 , __magic_name__=30_72 , __magic_name__="gelu" , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=0.0_2 , __magic_name__=1e-12 , __magic_name__=2_24 , __magic_name__=16 , __magic_name__=3 , __magic_name__=False , __magic_name__=False , __magic_name__=False , __magic_name__=False , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=True , __magic_name__=[3, 5, 7, 11] , __magic_name__=[1, 2, 3, 6] , __magic_name__=True , __magic_name__=0.4 , __magic_name__=2_56 , __magic_name__=1 , __magic_name__=False , __magic_name__=2_55 , **__magic_name__ , ) -> int: super().__init__(**__magic_name__ ) _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = initializer_range _a = layer_norm_eps _a = image_size _a = patch_size _a = num_channels _a = use_mask_token _a = use_absolute_position_embeddings _a = use_relative_position_bias _a = use_shared_relative_position_bias _a = layer_scale_init_value _a = drop_path_rate _a = use_mean_pooling # decode head attributes (semantic segmentation) _a = out_indices _a = pool_scales # auxiliary head attributes (semantic segmentation) _a = use_auxiliary_head _a = auxiliary_loss_weight _a = auxiliary_channels _a = auxiliary_num_convs _a = auxiliary_concat_input _a = semantic_loss_ignore_index class a ( _a ): _lowerCAmelCase = version.parse("""1.11""" ) @property def __UpperCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __UpperCAmelCase ( self ) -> float: return 1e-4
168
from __future__ import annotations def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> tuple[float, list[float]]: """simple docstring""" snake_case_ : Dict = list(range(len(_UpperCamelCase ) ) ) snake_case_ : Dict = [v / w for v, w in zip(_UpperCamelCase , _UpperCamelCase )] index.sort(key=lambda _UpperCamelCase : ratio[i] , reverse=_UpperCamelCase ) snake_case_ : float = 0 snake_case_ : list[float] = [0] * len(_UpperCamelCase ) for i in index: if weight[i] <= capacity: snake_case_ : Dict = 1 max_value += value[i] capacity -= weight[i] else: snake_case_ : Union[str, Any] = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
279
0
import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" __a = StableDiffusionPipeline.from_pretrained(_UpperCamelCase , torch_dtype=torch.floataa ) # load LoRA weight from .safetensors __a = load_file(_UpperCamelCase ) __a = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: __a = key.split(""".""" )[0].split(LORA_PREFIX_TEXT_ENCODER + """_""" )[-1].split("""_""" ) __a = pipeline.text_encoder else: __a = key.split(""".""" )[0].split(LORA_PREFIX_UNET + """_""" )[-1].split("""_""" ) __a = pipeline.unet # find the target layer __a = layer_infos.pop(0 ) while len(_UpperCamelCase ) > -1: try: __a = curr_layer.__getattr__(_UpperCamelCase ) if len(_UpperCamelCase ) > 0: __a = layer_infos.pop(0 ) elif len(_UpperCamelCase ) == 0: break except Exception: if len(_UpperCamelCase ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: __a = layer_infos.pop(0 ) __a = [] if "lora_down" in key: pair_keys.append(key.replace("""lora_down""" , """lora_up""" ) ) pair_keys.append(_UpperCamelCase ) else: pair_keys.append(_UpperCamelCase ) pair_keys.append(key.replace("""lora_up""" , """lora_down""" ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: __a = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) __a = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(_UpperCamelCase , _UpperCamelCase ).unsqueeze(2 ).unsqueeze(3 ) else: __a = state_dict[pair_keys[0]].to(torch.floataa ) __a = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(_UpperCamelCase , _UpperCamelCase ) # update visited list for item in pair_keys: visited.append(_UpperCamelCase ) return pipeline if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument( """--base_model_path""", default=None, type=str, required=True, help="""Path to the base model in diffusers format.""" ) parser.add_argument( """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert.""" ) parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument( """--lora_prefix_unet""", default="""lora_unet""", type=str, help="""The prefix of UNet weight in safetensors""" ) parser.add_argument( """--lora_prefix_text_encoder""", default="""lora_te""", type=str, help="""The prefix of text encoder weight in safetensors""", ) parser.add_argument("""--alpha""", default=0.75, type=float, help="""The merging ratio in W = W0 + alpha * deltaW""") parser.add_argument( """--to_safetensors""", action="""store_true""", help="""Whether to store pipeline in safetensors format or not.""" ) parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""") lowerCamelCase__ = parser.parse_args() lowerCamelCase__ = args.base_model_path lowerCamelCase__ = args.checkpoint_path lowerCamelCase__ = args.dump_path lowerCamelCase__ = args.lora_prefix_unet lowerCamelCase__ = args.lora_prefix_text_encoder lowerCamelCase__ = args.alpha lowerCamelCase__ = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) lowerCamelCase__ = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
302
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=3 , __magic_name__=18 , __magic_name__=30 , __magic_name__=400 , __magic_name__=True , __magic_name__=32 , __magic_name__=True , ) -> Dict: '''simple docstring''' snake_case_ : Tuple = parent snake_case_ : Union[str, Any] = batch_size snake_case_ : Union[str, Any] = num_channels snake_case_ : Optional[Any] = image_size snake_case_ : int = min_resolution snake_case_ : Any = max_resolution snake_case_ : Tuple = do_resize snake_case_ : str = size_divisor snake_case_ : Optional[Any] = do_rescale def lowerCamelCase (self ) -> Dict: '''simple docstring''' return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[Any] = GLPNImageProcessor if is_vision_available() else None def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : str = GLPNImageProcessingTester(self ) @property def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , '''do_resize''' ) ) self.assertTrue(hasattr(__magic_name__ , '''size_divisor''' ) ) self.assertTrue(hasattr(__magic_name__ , '''resample''' ) ) self.assertTrue(hasattr(__magic_name__ , '''do_rescale''' ) ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : str = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) snake_case_ : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
279
0
import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def SCREAMING_SNAKE_CASE__ ( __a , __a=False ): try: snake_case_ : str = os.environ[key] except KeyError: # KEY isn't set, default to `default`. snake_case_ : Union[str, Any] = default else: # KEY is set, convert it to True or False. try: snake_case_ : Optional[int] = strtobool(_UpperCamelCase ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"""If set, {key} must be yes or no.""" ) return _value _SCREAMING_SNAKE_CASE = parse_flag_from_env("""RUN_SLOW""", default=False) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skip('Test was skipped' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(_run_slow_tests , 'test is slow' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(not torch.cuda.is_available() , 'test requires only a CPU' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(torch.cuda.is_available() , 'test requires a GPU' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(is_xpu_available() , 'test requires a XPU' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(is_mps_available() , 'test requires a `mps` backend support in `torch`' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless( is_transformers_available() and is_datasets_available() , 'test requires the Hugging Face suite' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(is_bnb_available() , 'test requires the bitsandbytes library' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(is_tpu_available() , 'test requires TPU' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(torch.cuda.device_count() == 1 , 'test requires a GPU' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(torch.xpu.device_count() == 1 , 'test requires a XPU' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(torch.cuda.device_count() > 1 , 'test requires multiple GPUs' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(torch.xpu.device_count() > 1 , 'test requires multiple XPUs' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(is_safetensors_available() , 'test requires safetensors' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(is_deepspeed_available() , 'test requires DeepSpeed' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(is_torch_version('>=' , '1.12.0' ) , 'test requires torch version >= 1.12.0' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a=None , __a=None ): if test_case is None: return partial(_UpperCamelCase , version=_UpperCamelCase ) return unittest.skipUnless(is_torch_version('>=' , _UpperCamelCase ) , f"""test requires torch version >= {version}""" )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(is_tensorboard_available() , 'test requires Tensorboard' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(is_wandb_available() , 'test requires wandb' )(_UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless(is_comet_ml_available() , 'test requires comet_ml' )(_UpperCamelCase ) _SCREAMING_SNAKE_CASE = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def SCREAMING_SNAKE_CASE__ ( __a ): return unittest.skipUnless( _atleast_one_tracker_available , 'test requires at least one tracker to be available and for `comet_ml` to not be installed' , )(_UpperCamelCase ) class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): __magic_name__: Union[str, Any] = True @classmethod def UpperCAmelCase_ ( cls : Optional[int] ) -> int: """simple docstring""" snake_case_ : Optional[Any] = tempfile.mkdtemp() @classmethod def UpperCAmelCase_ ( cls : Tuple ) -> List[str]: """simple docstring""" if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def UpperCAmelCase_ ( self : int ) -> Any: """simple docstring""" if self.clear_on_setup: for path in Path(self.tmpdir ).glob('**/*' ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(_A ) class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): def UpperCAmelCase_ ( self : str ) -> Optional[Any]: """simple docstring""" super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): def UpperCAmelCase_ ( self : List[str] , _A : Optional[int] ) -> List[str]: """simple docstring""" snake_case_ : Optional[int] = mocks if isinstance(_A , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def SCREAMING_SNAKE_CASE__ ( __a ): snake_case_ : Union[str, Any] = AcceleratorState() snake_case_ : str = tensor[None].clone().to(state.device ) snake_case_ : Dict = gather(_UpperCamelCase ).cpu() snake_case_ : Any = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] , _UpperCamelCase ): return False return True class SCREAMING_SNAKE_CASE_ : def __init__( self : Optional[int] , _A : Optional[int] , _A : str , _A : Dict ) -> Tuple: """simple docstring""" snake_case_ : Optional[Any] = returncode snake_case_ : Union[str, Any] = stdout snake_case_ : List[str] = stderr async def SCREAMING_SNAKE_CASE__ ( __a , __a ): while True: snake_case_ : List[str] = await stream.readline() if line: callback(_UpperCamelCase ) else: break async def SCREAMING_SNAKE_CASE__ ( __a , __a=None , __a=None , __a=None , __a=False , __a=False ): if echo: print('\nRunning: ' , ' '.join(_UpperCamelCase ) ) snake_case_ : Optional[int] = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=_UpperCamelCase , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=_UpperCamelCase , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) snake_case_ : Optional[Any] = [] snake_case_ : Any = [] def tee(__a , __a , __a , __a="" ): snake_case_ : List[str] = line.decode('utf-8' ).rstrip() sink.append(_UpperCamelCase ) if not quiet: print(_UpperCamelCase , _UpperCamelCase , file=_UpperCamelCase ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout , lambda __a : tee(_UpperCamelCase , _UpperCamelCase , sys.stdout , label='stdout:' ) ) ), asyncio.create_task(_read_stream(p.stderr , lambda __a : tee(_UpperCamelCase , _UpperCamelCase , sys.stderr , label='stderr:' ) ) ), ] , timeout=_UpperCamelCase , ) return _RunOutput(await p.wait() , _UpperCamelCase , _UpperCamelCase ) def SCREAMING_SNAKE_CASE__ ( __a , __a=None , __a=None , __a=1_80 , __a=False , __a=True ): snake_case_ : int = asyncio.get_event_loop() snake_case_ : Tuple = loop.run_until_complete( _stream_subprocess(_UpperCamelCase , env=_UpperCamelCase , stdin=_UpperCamelCase , timeout=_UpperCamelCase , quiet=_UpperCamelCase , echo=_UpperCamelCase ) ) snake_case_ : Any = ''' '''.join(_UpperCamelCase ) if result.returncode > 0: snake_case_ : Union[str, Any] = '''\n'''.join(result.stderr ) raise RuntimeError( f"""\'{cmd_str}\' failed with returncode {result.returncode}\n\n""" f"""The combined stderr from workers follows:\n{stderr}""" ) return result class SCREAMING_SNAKE_CASE_ ( _a ): pass def SCREAMING_SNAKE_CASE__ ( __a , __a=False ): try: snake_case_ : Dict = subprocess.check_output(_UpperCamelCase , stderr=subprocess.STDOUT ) if return_stdout: if hasattr(_UpperCamelCase , 'decode' ): snake_case_ : Optional[Any] = output.decode('utf-8' ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( f"""Command `{' '.join(_UpperCamelCase )}` failed with the following error:\n\n{e.output.decode()}""" ) from e
327
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
279
0
'''simple docstring''' from PIL import Image def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ) -> Image: _a : Optional[int] =image.size _a : Union[str, Any] =0 _a : Optional[Any] =image.load() for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): _a : List[str] =pixels[j, i] mean += pixel mean //= width * height for j in range(_UpperCamelCase ): for i in range(_UpperCamelCase ): _a : Optional[int] =255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": A__: Optional[Any] = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
276
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers lowerCAmelCase_ = float('''nan''') class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : List[Any] = sys.stdout snake_case_ : int = open(__magic_name__ , '''a''' ) def __getattr__(self , __magic_name__ ) -> Dict: '''simple docstring''' return getattr(self.stdout , __magic_name__ ) def lowerCamelCase (self , __magic_name__ ) -> int: '''simple docstring''' self.stdout.write(__magic_name__ ) # strip tqdm codes self.file.write(re.sub(R'''^.*\r''' , '''''' , __magic_name__ , 0 , re.M ) ) def lowerCamelCase_ ( _UpperCamelCase=80 , _UpperCamelCase=False ) -> str: """simple docstring""" snake_case_ : str = [] # deal with critical env vars snake_case_ : int = ['''CUDA_VISIBLE_DEVICES'''] for key in env_keys: snake_case_ : Optional[int] = os.environ.get(_UpperCamelCase , _UpperCamelCase ) if val is not None: cmd.append(f'''{key}={val}''' ) # python executable (not always needed if the script is executable) snake_case_ : Optional[int] = sys.executable if full_python_path else sys.executable.split('''/''' )[-1] cmd.append(_UpperCamelCase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes snake_case_ : Dict = [] snake_case_ : Dict = '''''' while len(_UpperCamelCase ) > 0: current_line += f'''{cmd.pop(0 )} ''' if len(_UpperCamelCase ) == 0 or len(_UpperCamelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(_UpperCamelCase ) snake_case_ : List[Any] = '''''' return "\\\n".join(_UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" snake_case_ : str = re.sub(R'''[\\\n]+''' , ''' ''' , args.base_cmd ) # remove --output_dir if any and set our own snake_case_ : Optional[Any] = re.sub('''--output_dir\s+[^\s]+''' , '''''' , args.base_cmd ) args.base_cmd += f''' --output_dir {output_dir}''' # ensure we have --overwrite_output_dir snake_case_ : int = re.sub('''--overwrite_output_dir\s+''' , '''''' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6_666, 222.22_222_222] )} , ) snake_case_ : Tuple = subprocess.run(_UpperCamelCase , capture_output=_UpperCamelCase , text=_UpperCamelCase ) if verbose: print('''STDOUT''' , result.stdout ) print('''STDERR''' , result.stderr ) # save the streams snake_case_ : Any = variation.replace(''' ''' , '''-''' ) with open(Path(_UpperCamelCase ) / f'''log.{prefix}.stdout.txt''' , '''w''' ) as f: f.write(result.stdout ) with open(Path(_UpperCamelCase ) / f'''log.{prefix}.stderr.txt''' , '''w''' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('''failed''' ) return {target_metric_key: nan} with io.open(f'''{output_dir}/all_results.json''' , '''r''' , encoding='''utf-8''' ) as f: snake_case_ : str = json.load(_UpperCamelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ) -> Tuple: """simple docstring""" snake_case_ : Tuple = [] snake_case_ : Any = [] snake_case_ : int = f'''{id}: {variation:<{longest_variation_len}}''' snake_case_ : Optional[Any] = f'''{preamble}: ''' snake_case_ : Optional[int] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(_UpperCamelCase ) , desc=_UpperCamelCase , leave=_UpperCamelCase ): snake_case_ : int = process_run_single( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) snake_case_ : List[str] = single_run_metrics[target_metric_key] if not math.isnan(_UpperCamelCase ): metrics.append(_UpperCamelCase ) results.append(_UpperCamelCase ) outcome += "✓" else: outcome += "✘" snake_case_ : Any = f'''\33[2K\r{outcome}''' if len(_UpperCamelCase ) > 0: snake_case_ : List[Any] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} snake_case_ : Any = round(mean_metrics[target_metric_key] , 2 ) snake_case_ : List[str] = f'''{outcome} {mean_target}''' if len(_UpperCamelCase ) > 1: results_str += f''' {tuple(round(_UpperCamelCase , 2 ) for x in results )}''' print(_UpperCamelCase ) snake_case_ : Optional[int] = variation return mean_metrics else: print(_UpperCamelCase ) return {variation_key: variation, target_metric_key: nan} def lowerCamelCase_ ( ) -> Optional[int]: """simple docstring""" snake_case_ : Any = torch.cuda.get_device_properties(torch.device('''cuda''' ) ) return f''' Datetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB ''' def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Dict: """simple docstring""" snake_case_ : str = pd.DataFrame(_UpperCamelCase ) snake_case_ : Optional[int] = '''variation''' snake_case_ : Union[str, Any] = '''diff_%''' snake_case_ : Optional[int] = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan snake_case_ : Optional[Any] = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(_UpperCamelCase ): # as a fallback, use the minimal value as the sentinel snake_case_ : Any = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(_UpperCamelCase ): snake_case_ : Dict = df.apply( lambda _UpperCamelCase : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='''columns''' , ) # re-order columns snake_case_ : Dict = [variation_key, target_metric_key, diff_key, *report_metric_keys] snake_case_ : int = df.reindex(_UpperCamelCase , axis='''columns''' ) # reorder cols # capitalize snake_case_ : Optional[int] = df.rename(str.capitalize , axis='''columns''' ) # make the cols as narrow as possible snake_case_ : Any = df.rename(lambda _UpperCamelCase : c.replace('''_''' , '''<br>''' ) , axis='''columns''' ) snake_case_ : int = df.rename(lambda _UpperCamelCase : c.replace('''_''' , '''\n''' ) , axis='''columns''' ) snake_case_ : Tuple = ['''''', '''Copy between the cut-here-lines and paste as is to github or a forum'''] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=_UpperCamelCase , floatfmt='''.2f''' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=_UpperCamelCase , floatfmt='''.2f''' )] print('''\n\n'''.join(_UpperCamelCase ) ) def lowerCamelCase_ ( ) -> Any: """simple docstring""" snake_case_ : Any = argparse.ArgumentParser() parser.add_argument( '''--base-cmd''' , default=_UpperCamelCase , type=_UpperCamelCase , required=_UpperCamelCase , help='''Base cmd''' , ) parser.add_argument( '''--variations''' , default=_UpperCamelCase , type=_UpperCamelCase , nargs='''+''' , required=_UpperCamelCase , help='''Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'''' , ) parser.add_argument( '''--base-variation''' , default=_UpperCamelCase , type=_UpperCamelCase , help='''Baseline variation to compare to. if None the minimal target value will be used to compare against''' , ) parser.add_argument( '''--target-metric-key''' , default=_UpperCamelCase , type=_UpperCamelCase , required=_UpperCamelCase , help='''Target metric key in output_dir/all_results.json, e.g., train_samples_per_second''' , ) parser.add_argument( '''--report-metric-keys''' , default='''''' , type=_UpperCamelCase , help='''Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples''' , ) parser.add_argument( '''--repeat-times''' , default=1 , type=_UpperCamelCase , help='''How many times to re-run each variation - an average will be reported''' , ) parser.add_argument( '''--output_dir''' , default='''output_benchmark''' , type=_UpperCamelCase , help='''The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked''' , ) parser.add_argument( '''--verbose''' , default=_UpperCamelCase , action='''store_true''' , help='''Whether to show the outputs of each run or just the benchmark progress''' , ) snake_case_ : Tuple = parser.parse_args() snake_case_ : Optional[Any] = args.output_dir Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) snake_case_ : Optional[int] = get_base_command(_UpperCamelCase , _UpperCamelCase ) # split each dimension into its --foo variations snake_case_ : Optional[int] = [list(map(str.strip , re.split(R'''\|''' , _UpperCamelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty snake_case_ : List[str] = list(map(str.strip , map(''' '''.join , itertools.product(*_UpperCamelCase ) ) ) ) snake_case_ : Optional[int] = max(len(_UpperCamelCase ) for x in variations ) # split wanted keys snake_case_ : int = args.report_metric_keys.split() # capture prints into a log file for convenience snake_case_ : str = f'''benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt''' print(f'''\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt''' ) print(f'''and this script\'s output is also piped into {report_fn}''' ) snake_case_ : Tuple = Tee(_UpperCamelCase ) print(f'''\n*** Running {len(_UpperCamelCase )} benchmarks:''' ) print(f'''Base command: {" ".join(_UpperCamelCase )}''' ) snake_case_ : List[Any] = '''variation''' snake_case_ : Tuple = [] for id, variation in enumerate(tqdm(_UpperCamelCase , desc='''Total completion: ''' , leave=_UpperCamelCase ) ): snake_case_ : Optional[Any] = base_cmd + variation.split() results.append( process_run( id + 1 , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , args.target_metric_key , _UpperCamelCase , args.repeat_times , _UpperCamelCase , args.verbose , ) ) process_results(_UpperCamelCase , args.target_metric_key , _UpperCamelCase , args.base_variation , _UpperCamelCase ) if __name__ == "__main__": main()
279
0
"""simple docstring""" import importlib.metadata import operator import re import sys from typing import Optional from packaging import version SCREAMING_SNAKE_CASE_ = { '''<''': operator.lt, '''<=''': operator.le, '''==''': operator.eq, '''!=''': operator.ne, '''>=''': operator.ge, '''>''': operator.gt, } def lowercase (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): if got_ver is None or want_ver is None: raise ValueError( f"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider""" f""" reinstalling {pkg}.""" ) if not ops[op](version.parse(_UpperCamelCase ) , version.parse(_UpperCamelCase ) ): raise ImportError( f"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" ) def lowercase (_lowerCAmelCase , _lowerCAmelCase = None ): __lowerCAmelCase = f"""\n{hint}""" if hint is not None else '''''' # non-versioned check if re.match(r"""^[\w_\-\d]+$""" , _UpperCamelCase ): __lowerCAmelCase = requirement, None, None else: __lowerCAmelCase = re.findall(r"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , _UpperCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" f""" got {requirement}""" ) __lowerCAmelCase = match[0] __lowerCAmelCase = want_full.split(""",""" ) # there could be multiple requirements __lowerCAmelCase = {} for w in want_range: __lowerCAmelCase = re.findall(r"""^([\s!=<>]{1,2})(.+)""" , _UpperCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" f""" but got {requirement}""" ) __lowerCAmelCase = match[0] __lowerCAmelCase = want_ver if op not in ops: raise ValueError(f"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" ) # special case if pkg == "python": __lowerCAmelCase = '''.'''.join([str(_UpperCamelCase ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) return # check if any version is installed try: __lowerCAmelCase = importlib.metadata.version(_UpperCamelCase ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( f"""The \'{requirement}\' distribution was not found and is required by this application. {hint}""" ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) def lowercase (_lowerCAmelCase ): __lowerCAmelCase = '''Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main''' return require_version(_UpperCamelCase , _UpperCamelCase )
301
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--txt2img_unclip''', default='''kakaobrain/karlo-v1-alpha''', type=str, required=False, help='''The pretrained txt2img unclip.''', ) lowerCAmelCase_ = parser.parse_args() lowerCAmelCase_ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) lowerCAmelCase_ = CLIPImageProcessor() lowerCAmelCase_ = CLIPVisionModelWithProjection.from_pretrained('''openai/clip-vit-large-patch14''') lowerCAmelCase_ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
279
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) def __A ( lowerCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE : int = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: SCREAMING_SNAKE_CASE : Any = 1_92 SCREAMING_SNAKE_CASE : Dict = 7_68 SCREAMING_SNAKE_CASE : Dict = 12 SCREAMING_SNAKE_CASE : List[Any] = 3 SCREAMING_SNAKE_CASE : Dict = [8_00, 13_33] SCREAMING_SNAKE_CASE : List[str] = False elif yolos_name == "yolos_s_dWr": SCREAMING_SNAKE_CASE : Optional[int] = 3_30 SCREAMING_SNAKE_CASE : List[str] = 14 SCREAMING_SNAKE_CASE : str = 6 SCREAMING_SNAKE_CASE : List[str] = 13_20 elif "yolos_s" in yolos_name: SCREAMING_SNAKE_CASE : Union[str, Any] = 3_84 SCREAMING_SNAKE_CASE : Dict = 15_36 SCREAMING_SNAKE_CASE : int = 12 SCREAMING_SNAKE_CASE : List[str] = 6 elif "yolos_b" in yolos_name: SCREAMING_SNAKE_CASE : List[Any] = [8_00, 13_44] SCREAMING_SNAKE_CASE : Optional[Any] = 91 SCREAMING_SNAKE_CASE : str = '''huggingface/label-files''' SCREAMING_SNAKE_CASE : Optional[Any] = '''coco-detection-id2label.json''' SCREAMING_SNAKE_CASE : Dict = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE : Dict = {int(_UpperCamelCase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Optional[Any] = idalabel SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} return config def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = False ): """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE : Any = state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE : Dict = state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : List[Any] = in_proj_weight[: config.hidden_size, :] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE : List[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE : Tuple = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE : str = in_proj_weight[-config.hidden_size :, :] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[-config.hidden_size :] def __A ( lowerCamelCase_ ): """simple docstring""" if "backbone" in name: SCREAMING_SNAKE_CASE : List[str] = name.replace("""backbone""" , """vit""" ) if "cls_token" in name: SCREAMING_SNAKE_CASE : List[str] = name.replace("""cls_token""" , """embeddings.cls_token""" ) if "det_token" in name: SCREAMING_SNAKE_CASE : int = name.replace("""det_token""" , """embeddings.detection_tokens""" ) if "mid_pos_embed" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("""mid_pos_embed""" , """encoder.mid_position_embeddings""" ) if "pos_embed" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace("""pos_embed""" , """embeddings.position_embeddings""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE : Dict = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "blocks" in name: SCREAMING_SNAKE_CASE : Any = name.replace("""blocks""" , """encoder.layer""" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE : int = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE : str = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE : Dict = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE : int = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE : Any = name.replace("""mlp.fc2""" , """output.dense""" ) if "class_embed" in name: SCREAMING_SNAKE_CASE : Any = name.replace("""class_embed""" , """class_labels_classifier""" ) if "bbox_embed" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("""bbox_embed""" , """bbox_predictor""" ) if "vit.norm" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("""vit.norm""" , """vit.layernorm""" ) return name def __A ( lowerCamelCase_ , lowerCamelCase_ ): """simple docstring""" for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : List[str] = orig_state_dict.pop(_UpperCamelCase ) if "qkv" in key: SCREAMING_SNAKE_CASE : Optional[int] = key.split(""".""" ) SCREAMING_SNAKE_CASE : Optional[int] = int(key_split[2] ) SCREAMING_SNAKE_CASE : int = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE : Dict = val[:dim, :] SCREAMING_SNAKE_CASE : Dict = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE : List[str] = val[-dim:, :] else: SCREAMING_SNAKE_CASE : int = val[:dim] SCREAMING_SNAKE_CASE : Optional[int] = val[dim : dim * 2] SCREAMING_SNAKE_CASE : Optional[int] = val[-dim:] else: SCREAMING_SNAKE_CASE : List[Any] = val return orig_state_dict def __A ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : int = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im @torch.no_grad() def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = False ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = get_yolos_config(_UpperCamelCase ) # load original state_dict SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(_UpperCamelCase , map_location="""cpu""" )['''model'''] # load 🤗 model SCREAMING_SNAKE_CASE : int = YolosForObjectDetection(_UpperCamelCase ) model.eval() SCREAMING_SNAKE_CASE : str = convert_state_dict(_UpperCamelCase , _UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # Check outputs on an image, prepared by YolosImageProcessor SCREAMING_SNAKE_CASE : str = 8_00 if yolos_name != '''yolos_ti''' else 5_12 SCREAMING_SNAKE_CASE : Tuple = YolosImageProcessor(format="""coco_detection""" , size=_UpperCamelCase ) SCREAMING_SNAKE_CASE : Any = image_processor(images=prepare_img() , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE : Tuple = model(**_UpperCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = outputs.logits, outputs.pred_boxes SCREAMING_SNAKE_CASE : List[Any] = None, None if yolos_name == "yolos_ti": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[-39.5_022, -11.9_820, -17.6_888], [-29.9_574, -9.9_769, -17.7_691], [-42.3_281, -20.7_200, -30.6_294]] ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[0.4_021, 0.0_836, 0.7_979], [0.0_184, 0.2_609, 0.0_364], [0.1_781, 0.2_004, 0.2_095]] ) elif yolos_name == "yolos_s_200_pre": SCREAMING_SNAKE_CASE : str = torch.tensor( [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]] ) SCREAMING_SNAKE_CASE : int = torch.tensor( [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]] ) elif yolos_name == "yolos_s_300_pre": SCREAMING_SNAKE_CASE : str = torch.tensor( [[-36.2_220, -14.4_385, -23.5_457], [-35.6_970, -14.7_583, -21.3_935], [-31.5_939, -13.6_042, -16.8_049]] ) SCREAMING_SNAKE_CASE : int = torch.tensor( [[0.7_614, 0.2_316, 0.4_728], [0.7_168, 0.4_495, 0.3_855], [0.4_996, 0.1_466, 0.9_996]] ) elif yolos_name == "yolos_s_dWr": SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[-42.8_668, -24.1_049, -41.1_690], [-34.7_456, -14.1_274, -24.9_194], [-33.7_898, -12.1_946, -25.6_495]] ) SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.5_587, 0.2_773, 0.0_605], [0.5_004, 0.3_014, 0.9_994], [0.4_999, 0.1_548, 0.9_994]] ) elif yolos_name == "yolos_base": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[-40.6_064, -24.3_084, -32.6_447], [-55.1_990, -30.7_719, -35.5_877], [-51.4_311, -33.3_507, -35.6_462]] ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [[0.5_555, 0.2_794, 0.0_655], [0.9_049, 0.2_664, 0.1_894], [0.9_183, 0.1_984, 0.1_635]] ) else: raise ValueError(f'''Unknown yolos_name: {yolos_name}''' ) assert torch.allclose(logits[0, :3, :3] , _UpperCamelCase , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , _UpperCamelCase , atol=1E-4 ) Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) print(f'''Saving model {yolos_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_UpperCamelCase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(_UpperCamelCase ) if push_to_hub: SCREAMING_SNAKE_CASE : Optional[Any] = { '''yolos_ti''': '''yolos-tiny''', '''yolos_s_200_pre''': '''yolos-small''', '''yolos_s_300_pre''': '''yolos-small-300''', '''yolos_s_dWr''': '''yolos-small-dwr''', '''yolos_base''': '''yolos-base''', } print("""Pushing to the hub...""" ) SCREAMING_SNAKE_CASE : List[str] = model_mapping[yolos_name] image_processor.push_to_hub(_UpperCamelCase , organization="""hustvl""" ) model.push_to_hub(_UpperCamelCase , organization="""hustvl""" ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--yolos_name""", default="""yolos_s_200_pre""", type=str, help=( """Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',""" """ \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.""" ), ) parser.add_argument( """--checkpoint_path""", default=None, type=str, help="""Path to the original state dict (.pth file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) __UpperCAmelCase = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
323
from math import factorial lowerCAmelCase_ = {str(digit): factorial(digit) for digit in range(1_0)} def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError('''Parameter number must be int''' ) if number < 0: raise ValueError('''Parameter number must be greater than or equal to 0''' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCamelCase ) ) def lowerCamelCase_ ( _UpperCamelCase = 60 , _UpperCamelCase = 1_000_000 ) -> int: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ) or not isinstance(_UpperCamelCase , _UpperCamelCase ): raise TypeError('''Parameters chain_length and number_limit must be int''' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( '''Parameters chain_length and number_limit must be greater than 0''' ) # the counter for the chains with the exact desired length snake_case_ : Optional[Any] = 0 # the cached sizes of the previous chains snake_case_ : dict[int, int] = {} for start_chain_element in range(1 , _UpperCamelCase ): # The temporary set will contain the elements of the chain snake_case_ : List[str] = set() snake_case_ : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. snake_case_ : Any = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCamelCase ) chain_set_length += 1 snake_case_ : List[Any] = digit_factorial_sum(_UpperCamelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] snake_case_ : List[str] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F'''{solution()}''')
279
0
"""simple docstring""" import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets __SCREAMING_SNAKE_CASE =datasets.logging.get_logger(__name__) __SCREAMING_SNAKE_CASE ="\\n@inproceedings{bleurt,\n title={BLEURT: Learning Robust Metrics for Text Generation},\n author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},\n booktitle={ACL},\n year={2020},\n url={https://arxiv.org/abs/2004.04696}\n}\n" __SCREAMING_SNAKE_CASE ="\\nBLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)\nand then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune\nit for your specific application (the latter is expected to perform better).\n\nSee the project\'s README at https://github.com/google-research/bleurt#readme for more information.\n" __SCREAMING_SNAKE_CASE ="\nBLEURT score.\n\nArgs:\n `predictions` (list of str): prediction/candidate sentences\n `references` (list of str): reference sentences\n `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.\n\nReturns:\n \'scores\': List of scores.\nExamples:\n\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> bleurt = datasets.load_metric(\"bleurt\")\n >>> results = bleurt.compute(predictions=predictions, references=references)\n >>> print([round(v, 2) for v in results[\"scores\"]])\n [1.03, 1.04]\n" __SCREAMING_SNAKE_CASE ={ "bleurt-tiny-128": "https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip", "bleurt-tiny-512": "https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip", "bleurt-base-128": "https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip", "bleurt-base-512": "https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip", "bleurt-large-128": "https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip", "bleurt-large-512": "https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip", "BLEURT-20-D3": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip", "BLEURT-20-D6": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip", "BLEURT-20-D12": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip", "BLEURT-20": "https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip", } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase ( datasets.Metric ): def _UpperCAmelCase ( self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/google-research/bleurt' ,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/bleurt'] ,reference_urls=['https://github.com/google-research/bleurt', 'https://arxiv.org/abs/2004.04696'] ,) def _UpperCAmelCase ( self ,__UpperCamelCase ) -> List[Any]: '''simple docstring''' if self.config_name == "default": logger.warning( 'Using default BLEURT-Base checkpoint for sequence maximum length 128. ' 'You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').' ) lowercase_ : Dict = '''bleurt-base-128''' if self.config_name.lower() in CHECKPOINT_URLS: lowercase_ : Optional[int] = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: lowercase_ : Union[str, Any] = self.config_name.upper() else: raise KeyError( f'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}''' ) # download the model checkpoint specified by self.config_name and set up the scorer lowercase_ : Any = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) lowercase_ : Dict = score.BleurtScorer(os.path.join(__UpperCamelCase ,__UpperCamelCase ) ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> Union[str, Any]: '''simple docstring''' lowercase_ : Dict = self.scorer.score(references=__UpperCamelCase ,candidates=__UpperCamelCase ) return {"scores": scores}
213
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class __lowerCAmelCase ( _a ): lowerCamelCase_ : int = '''''' lowerCamelCase_ : str = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) lowerCamelCase_ : str = None # compression type in fsspec. ex: "gzip" lowerCamelCase_ : str = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__(self , __magic_name__ = "" , __magic_name__ = None , __magic_name__ = None , **__magic_name__ ) -> Any: '''simple docstring''' super().__init__(self , **__magic_name__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode snake_case_ : Union[str, Any] = fsspec.open( __magic_name__ , mode='''rb''' , protocol=__magic_name__ , compression=self.compression , client_kwargs={ '''requote_redirect_url''': False, # see https://github.com/huggingface/datasets/pull/5459 '''trust_env''': True, # Enable reading proxy env variables. **(target_options or {}).pop('''client_kwargs''' , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) snake_case_ : Tuple = os.path.basename(self.file.path.split('''::''' )[0] ) snake_case_ : Optional[Any] = ( self.compressed_name[: self.compressed_name.rindex('''.''' )] if '''.''' in self.compressed_name else self.compressed_name ) snake_case_ : Dict = None @classmethod def lowerCamelCase (cls , __magic_name__ ) -> Optional[int]: '''simple docstring''' return super()._strip_protocol(__magic_name__ ).lstrip('''/''' ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' if self.dir_cache is None: snake_case_ : Optional[int] = {**self.file.fs.info(self.file.path ), '''name''': self.uncompressed_name} snake_case_ : List[str] = {f['''name''']: f} def lowerCamelCase (self , __magic_name__ ) -> Optional[Any]: '''simple docstring''' return self.file.open().read() def lowerCamelCase (self , __magic_name__ , __magic_name__ = "rb" , __magic_name__=None , __magic_name__=True , __magic_name__=None , **__magic_name__ , ) -> int: '''simple docstring''' snake_case_ : Union[str, Any] = self._strip_protocol(__magic_name__ ) if mode != "rb": raise ValueError(F'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''bz2''' lowerCamelCase_ : Any = '''bz2''' lowerCamelCase_ : int = '''.bz2''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''gzip''' lowerCamelCase_ : Dict = '''gzip''' lowerCamelCase_ : int = '''.gz''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''lz4''' lowerCamelCase_ : Any = '''lz4''' lowerCamelCase_ : Optional[Any] = '''.lz4''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''xz''' lowerCamelCase_ : Any = '''xz''' lowerCamelCase_ : int = '''.xz''' class __lowerCAmelCase ( _a ): lowerCamelCase_ : Union[str, Any] = '''zstd''' lowerCamelCase_ : Tuple = '''zstd''' lowerCamelCase_ : Any = '''.zst''' def __init__(self , __magic_name__ , __magic_name__ = "rb" , __magic_name__ = None , __magic_name__ = None , __magic_name__ = DEFAULT_BLOCK_SIZE , **__magic_name__ , ) -> Tuple: '''simple docstring''' super().__init__( fo=__magic_name__ , mode=__magic_name__ , target_protocol=__magic_name__ , target_options=__magic_name__ , block_size=__magic_name__ , **__magic_name__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 snake_case_ : Dict = self.file.__enter__ class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : str = file_ def __enter__(self ) -> List[Any]: '''simple docstring''' self._file.__enter__() return self def __exit__(self , *__magic_name__ , **__magic_name__ ) -> int: '''simple docstring''' self._file.__exit__(*__magic_name__ , **__magic_name__ ) def __iter__(self ) -> Optional[int]: '''simple docstring''' return iter(self._file ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' return next(self._file ) def __getattr__(self , __magic_name__ ) -> str: '''simple docstring''' return getattr(self._file , __magic_name__ ) def fixed_enter(*__magic_name__ , **__magic_name__ ): return WrappedFile(_enter(*__magic_name__ , **__magic_name__ ) ) snake_case_ : Tuple = fixed_enter
279
0
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration __snake_case = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def lowerCAmelCase_ ( __lowerCAmelCase )-> List[Any]: '''simple docstring''' UpperCAmelCase : List[str] =['''layers''', '''blocks'''] for k in ignore_keys: state_dict.pop(_UpperCamelCase , _UpperCamelCase ) __snake_case = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def lowerCAmelCase_ ( __lowerCAmelCase )-> int: '''simple docstring''' UpperCAmelCase : str =list(s_dict.keys() ) for key in keys: UpperCAmelCase : Optional[int] =key for k, v in WHISPER_MAPPING.items(): if k in key: UpperCAmelCase : List[str] =new_key.replace(_UpperCamelCase , _UpperCamelCase ) print(f'''{key} -> {new_key}''' ) UpperCAmelCase : Tuple =s_dict.pop(_UpperCamelCase ) return s_dict def lowerCAmelCase_ ( __lowerCAmelCase )-> int: '''simple docstring''' UpperCAmelCase : Dict =emb.weight.shape UpperCAmelCase : Tuple =nn.Linear(_UpperCamelCase , _UpperCamelCase , bias=_UpperCamelCase ) UpperCAmelCase : Any =emb.weight.data return lin_layer def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> bytes: '''simple docstring''' os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase ) UpperCAmelCase : List[Any] =os.path.basename(_UpperCamelCase ) UpperCAmelCase : Any =url.split('''/''' )[-2] UpperCAmelCase : str =os.path.join(_UpperCamelCase , _UpperCamelCase ) if os.path.exists(_UpperCamelCase ) and not os.path.isfile(_UpperCamelCase ): raise RuntimeError(f'''{download_target} exists and is not a regular file''' ) if os.path.isfile(_UpperCamelCase ): UpperCAmelCase : Union[str, Any] =open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file''' ) with urllib.request.urlopen(_UpperCamelCase ) as source, open(_UpperCamelCase , '''wb''' ) as output: with tqdm( total=int(source.info().get('''Content-Length''' ) ) , ncols=80 , unit='''iB''' , unit_scale=_UpperCamelCase , unit_divisor=10_24 ) as loop: while True: UpperCAmelCase : Dict =source.read(81_92 ) if not buffer: break output.write(_UpperCamelCase ) loop.update(len(_UpperCamelCase ) ) UpperCAmelCase : Any =open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() != expected_shaaaa: raise RuntimeError( '''Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.''' ) return model_bytes def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> int: '''simple docstring''' if ".pt" not in checkpoint_path: UpperCAmelCase : str =_download(_MODELS[checkpoint_path] ) else: UpperCAmelCase : Union[str, Any] =torch.load(_UpperCamelCase , map_location='''cpu''' ) UpperCAmelCase : int =original_checkpoint['''dims'''] UpperCAmelCase : List[str] =original_checkpoint['''model_state_dict'''] UpperCAmelCase : str =state_dict['''decoder.token_embedding.weight'''] remove_ignore_keys_(_UpperCamelCase ) rename_keys(_UpperCamelCase ) UpperCAmelCase : Optional[int] =True UpperCAmelCase : int =state_dict['''decoder.layers.0.fc1.weight'''].shape[0] UpperCAmelCase : List[str] =WhisperConfig( vocab_size=dimensions['''n_vocab'''] , encoder_ffn_dim=_UpperCamelCase , decoder_ffn_dim=_UpperCamelCase , num_mel_bins=dimensions['''n_mels'''] , d_model=dimensions['''n_audio_state'''] , max_target_positions=dimensions['''n_text_ctx'''] , encoder_layers=dimensions['''n_audio_layer'''] , encoder_attention_heads=dimensions['''n_audio_head'''] , decoder_layers=dimensions['''n_text_layer'''] , decoder_attention_heads=dimensions['''n_text_state'''] , max_source_positions=dimensions['''n_audio_ctx'''] , ) UpperCAmelCase : Union[str, Any] =WhisperForConditionalGeneration(_UpperCamelCase ) UpperCAmelCase : List[Any] =model.model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) if len(_UpperCamelCase ) > 0 and not set(_UpperCamelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' f''' but all the following weights are missing {missing}''' ) if tie_embeds: UpperCAmelCase : List[str] =make_linear_from_emb(model.model.decoder.embed_tokens ) else: UpperCAmelCase : Any =proj_out_weights model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') __snake_case = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
348
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase ( _a ): lowerCamelCase_ : Any = '''megatron-bert''' def __init__(self , __magic_name__=2_9056 , __magic_name__=1024 , __magic_name__=24 , __magic_name__=16 , __magic_name__=4096 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=512 , __magic_name__=2 , __magic_name__=0.02 , __magic_name__=1e-12 , __magic_name__=0 , __magic_name__="absolute" , __magic_name__=True , **__magic_name__ , ) -> Any: '''simple docstring''' super().__init__(pad_token_id=__magic_name__ , **__magic_name__ ) snake_case_ : Union[str, Any] = vocab_size snake_case_ : Dict = hidden_size snake_case_ : Dict = num_hidden_layers snake_case_ : Optional[int] = num_attention_heads snake_case_ : int = hidden_act snake_case_ : List[str] = intermediate_size snake_case_ : Dict = hidden_dropout_prob snake_case_ : str = attention_probs_dropout_prob snake_case_ : str = max_position_embeddings snake_case_ : Any = type_vocab_size snake_case_ : int = initializer_range snake_case_ : int = layer_norm_eps snake_case_ : List[str] = position_embedding_type snake_case_ : Dict = use_cache
279
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a__ : Tuple = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[int] = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
161
import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch lowerCAmelCase_ = random.Random() def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase=1.0 , _UpperCamelCase=None , _UpperCamelCase=None ) -> List[Any]: """simple docstring""" if rng is None: snake_case_ : str = global_rng snake_case_ : Any = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __lowerCAmelCase ( unittest.TestCase ): def __init__(self , __magic_name__ , __magic_name__=7 , __magic_name__=400 , __magic_name__=2000 , __magic_name__=10 , __magic_name__=160 , __magic_name__=8 , __magic_name__=0.0 , __magic_name__=4000 , __magic_name__=False , __magic_name__=True , ) -> List[str]: '''simple docstring''' snake_case_ : Tuple = parent snake_case_ : str = batch_size snake_case_ : Union[str, Any] = min_seq_length snake_case_ : Tuple = max_seq_length snake_case_ : Optional[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) snake_case_ : Optional[int] = padding_value snake_case_ : Union[str, Any] = sampling_rate snake_case_ : Optional[int] = return_attention_mask snake_case_ : str = do_normalize snake_case_ : str = feature_size snake_case_ : Optional[Any] = chunk_length snake_case_ : Union[str, Any] = hop_length def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def lowerCamelCase (self , __magic_name__=False , __magic_name__=False ) -> Optional[Any]: '''simple docstring''' def _flatten(__magic_name__ ): return list(itertools.chain(*__magic_name__ ) ) if equal_length: snake_case_ : int = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size snake_case_ : int = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: snake_case_ : str = [np.asarray(__magic_name__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[Any] = WhisperFeatureExtractor if is_speech_available() else None def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[str] = WhisperFeatureExtractionTester(self ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : Union[str, Any] = feat_extract_first.save_pretrained(__magic_name__ )[0] check_json_file_has_correct_format(__magic_name__ ) snake_case_ : List[Any] = self.feature_extraction_class.from_pretrained(__magic_name__ ) snake_case_ : Optional[int] = feat_extract_first.to_dict() snake_case_ : Dict = feat_extract_second.to_dict() snake_case_ : List[str] = feat_extract_first.mel_filters snake_case_ : Union[str, Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(__magic_name__ , __magic_name__ ) ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ : List[Any] = os.path.join(__magic_name__ , '''feat_extract.json''' ) feat_extract_first.to_json_file(__magic_name__ ) snake_case_ : Optional[int] = self.feature_extraction_class.from_json_file(__magic_name__ ) snake_case_ : int = feat_extract_first.to_dict() snake_case_ : Optional[int] = feat_extract_second.to_dict() snake_case_ : Union[str, Any] = feat_extract_first.mel_filters snake_case_ : str = feat_extract_second.mel_filters self.assertTrue(np.allclose(__magic_name__ , __magic_name__ ) ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 snake_case_ : Any = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] snake_case_ : str = [np.asarray(__magic_name__ ) for speech_input in speech_inputs] # Test feature size snake_case_ : str = feature_extractor(__magic_name__ , padding='''max_length''' , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input snake_case_ : Dict = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features snake_case_ : Optional[int] = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test batched snake_case_ : int = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : Union[str, Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. snake_case_ : Union[str, Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] snake_case_ : List[str] = np.asarray(__magic_name__ ) snake_case_ : List[Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : Dict = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) # Test truncation required snake_case_ : Any = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] snake_case_ : Union[str, Any] = [np.asarray(__magic_name__ ) for speech_input in speech_inputs] snake_case_ : Tuple = [x[: feature_extractor.n_samples] for x in speech_inputs] snake_case_ : Optional[Any] = [np.asarray(__magic_name__ ) for speech_input in speech_inputs_truncated] snake_case_ : Any = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features snake_case_ : List[Any] = feature_extractor(__magic_name__ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__magic_name__ , __magic_name__ ): self.assertTrue(np.allclose(__magic_name__ , __magic_name__ , atol=1e-3 ) ) def lowerCamelCase (self ) -> int: '''simple docstring''' import torch snake_case_ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case_ : Union[str, Any] = np.random.rand(100 , 32 ).astype(np.floataa ) snake_case_ : Dict = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: snake_case_ : Optional[Any] = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) snake_case_ : Optional[Any] = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Optional[Any] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech snake_case_ : Optional[Any] = ds.sort('''id''' ).select(range(__magic_name__ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : str = torch.tensor( [ 0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951, 0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678, 0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554, -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854 ] ) # fmt: on snake_case_ : List[Any] = self._load_datasamples(1 ) snake_case_ : Union[str, Any] = WhisperFeatureExtractor() snake_case_ : Union[str, Any] = feature_extractor(__magic_name__ , return_tensors='''pt''' ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __magic_name__ , atol=1e-4 ) ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case_ : Optional[int] = self._load_datasamples(1 )[0] snake_case_ : List[str] = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue snake_case_ : Optional[Any] = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__magic_name__ )[0] self.assertTrue(np.all(np.mean(__magic_name__ ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(__magic_name__ ) - 1 ) < 1e-3 ) )
279
0
import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class lowercase__( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : str=2 , SCREAMING_SNAKE_CASE_ : Dict=5_6 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : str=True , SCREAMING_SNAKE_CASE_ : Any=9_9 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=3_2 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE_ : int=2 , SCREAMING_SNAKE_CASE_ : List[Any]=7 , SCREAMING_SNAKE_CASE_ : Optional[Any]="gelu_new" , SCREAMING_SNAKE_CASE_ : str=0.1 , SCREAMING_SNAKE_CASE_ : int=0.1 , SCREAMING_SNAKE_CASE_ : Optional[int]=5_1_2 , SCREAMING_SNAKE_CASE_ : int=1_6 , SCREAMING_SNAKE_CASE_ : Optional[Any]=2 , SCREAMING_SNAKE_CASE_ : Any=0.02 , SCREAMING_SNAKE_CASE_ : Optional[Any]=4 , SCREAMING_SNAKE_CASE_ : str="block_sparse" , SCREAMING_SNAKE_CASE_ : Optional[Any]=True , SCREAMING_SNAKE_CASE_ : Optional[int]=False , SCREAMING_SNAKE_CASE_ : List[Any]=2 , SCREAMING_SNAKE_CASE_ : Dict=3 , ) -> Union[str, Any]: lowercase_ = parent lowercase_ = batch_size lowercase_ = seq_length lowercase_ = is_training lowercase_ = use_attention_mask lowercase_ = use_token_type_ids lowercase_ = use_labels lowercase_ = vocab_size lowercase_ = hidden_size lowercase_ = num_hidden_layers lowercase_ = num_attention_heads lowercase_ = intermediate_size lowercase_ = hidden_act lowercase_ = hidden_dropout_prob lowercase_ = attention_probs_dropout_prob lowercase_ = max_position_embeddings lowercase_ = type_vocab_size lowercase_ = type_sequence_label_size lowercase_ = initializer_range lowercase_ = num_choices lowercase_ = rescale_embeddings lowercase_ = attention_type lowercase_ = use_bias lowercase_ = block_size lowercase_ = num_random_blocks def _lowercase ( self : Dict ) -> Optional[int]: lowercase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase_ = None if self.use_attention_mask: lowercase_ = random_attention_mask([self.batch_size, self.seq_length] ) lowercase_ = None if self.use_token_type_ids: lowercase_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase_ = BigBirdConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , ) return config, input_ids, token_type_ids, attention_mask def _lowercase ( self : Tuple ) -> Dict: lowercase_ = self.prepare_config_and_inputs() lowercase_ = config_and_inputs lowercase_ = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask, } return config, inputs_dict @require_flax class lowercase__( _a , unittest.TestCase ): """simple docstring""" a :str = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) a :Any = False a :List[str] = False def _lowercase ( self : int ) -> Union[str, Any]: lowercase_ = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def _lowercase ( self : Any ) -> Dict: super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def _lowercase ( self : List[str] ) -> List[str]: super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def _lowercase ( self : List[Any] ) -> Tuple: super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def _lowercase ( self : Tuple ) -> Any: super().test_hidden_states_output() @slow def _lowercase ( self : List[Any] ) -> Dict: for model_class_name in self.all_model_classes: lowercase_ = model_class_name.from_pretrained('''google/bigbird-roberta-base''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : List[Any] ) -> int: if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def _lowercase ( self : Tuple ) -> Tuple: lowercase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase_ = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowercase_ = model_class(SCREAMING_SNAKE_CASE_ ) @jax.jit def model_jitted(SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any]=None , **SCREAMING_SNAKE_CASE_ : List[Any] ): return model(input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) with self.subTest('''JIT Enabled''' ): lowercase_ = model_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowercase_ = model_jitted(**SCREAMING_SNAKE_CASE_ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(jitted_output.shape , output.shape ) def _lowercase ( self : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict=1e-5 , SCREAMING_SNAKE_CASE_ : Dict="outputs" , SCREAMING_SNAKE_CASE_ : Optional[int]=None ) -> List[str]: if name.startswith('''outputs.attentions''' ): return else: super().check_pt_flax_outputs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
30
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase_ = logging.getLogger(__name__) def lowerCamelCase_ ( ) -> Optional[Any]: """simple docstring""" snake_case_ : List[str] = argparse.ArgumentParser( description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' ) parser.add_argument( '''--dataset_name''' , type=_UpperCamelCase , default='''wikitext''' , help='''Name of the training. Explore datasets at: hf.co/datasets.''' , ) parser.add_argument( '''--dataset_config''' , type=_UpperCamelCase , default='''wikitext-103-raw-v1''' , help='''Configuration name of the dataset.''' ) parser.add_argument( '''--tokenizer_name_or_path''' , type=_UpperCamelCase , default='''sayakpaul/unigram-tokenizer-wikitext''' , help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' , ) parser.add_argument( '''--shard_size''' , type=_UpperCamelCase , default=1_000 , help='''Number of entries to go in a single shard.''' , ) parser.add_argument('''--split''' , type=_UpperCamelCase , default='''train''' , choices=['''train''', '''test''', '''validation'''] ) parser.add_argument( '''--limit''' , default=_UpperCamelCase , type=_UpperCamelCase , help='''Limit the number of shards (used for debugging).''' , ) parser.add_argument( '''--max_length''' , type=_UpperCamelCase , default=512 , help='''Maximum sequence length. For training on TPUs, it helps to have a maximum''' ''' sequence length that is a multiple of 8.''' , ) parser.add_argument( '''--output_dir''' , default='''tf-tpu''' , type=_UpperCamelCase , help='''Output directory where the TFRecord shards will be saved. If the''' ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord''' ''' shards will be directly saved to a Google Cloud Storage bucket.''' , ) snake_case_ : List[Any] = parser.parse_args() return args def lowerCamelCase_ ( _UpperCamelCase ) -> Tuple: """simple docstring""" def fn(_UpperCamelCase ): return tokenizer(examples['''text'''] ) return fn def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : Any = [] for i in range(len(tokenized_data['''input_ids'''] ) ): snake_case_ : Any = { '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ), '''attention_mask''': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ), } snake_case_ : Optional[int] = tf.train.Features(feature=_UpperCamelCase ) snake_case_ : Optional[Any] = tf.train.Example(features=_UpperCamelCase ) snake_case_ : Optional[Any] = example.SerializeToString() records.append(_UpperCamelCase ) return records def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[int]: """simple docstring""" snake_case_ : int = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: snake_case_ : Union[str, Any] = min(len(_UpperCamelCase ) , args.limit ) snake_case_ : int = dataset.select(range(_UpperCamelCase ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) snake_case_ : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) snake_case_ : str = os.path.join(args.output_dir , args.split ) if not os.path.exists(_UpperCamelCase ): os.makedirs(_UpperCamelCase ) else: snake_case_ : Optional[Any] = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. snake_case_ : Optional[Any] = tokenize_function(_UpperCamelCase ) snake_case_ : List[Any] = dataset.map(_UpperCamelCase , batched=_UpperCamelCase , num_proc=4 , remove_columns=['''text'''] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(_UpperCamelCase ): # Concatenate all texts. snake_case_ : Tuple = {k: sum(examples[k] , [] ) for k in examples.keys()} snake_case_ : List[str] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 snake_case_ : int = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. snake_case_ : Union[str, Any] = { k: [t[i : i + args.max_length] for i in range(0 , _UpperCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result snake_case_ : int = dataset_tokenized.map(_UpperCamelCase , batched=_UpperCamelCase , batch_size=1_000 , num_proc=4 ) snake_case_ : str = 0 snake_case_ : Optional[Any] = 0 for shard in range(0 , len(_UpperCamelCase ) , args.shard_size ): snake_case_ : Any = grouped_dataset[shard : shard + args.shard_size] snake_case_ : str = len(dataset_snapshot['''input_ids'''] ) snake_case_ : Union[str, Any] = os.path.join(_UpperCamelCase , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) snake_case_ : Dict = get_serialized_examples(_UpperCamelCase ) with tf.io.TFRecordWriter(_UpperCamelCase ) as out_file: for i in range(len(_UpperCamelCase ) ): snake_case_ : List[str] = serialized_examples[i] out_file.write(_UpperCamelCase ) print('''Wrote file {} containing {} records'''.format(_UpperCamelCase , _UpperCamelCase ) ) shard_count += 1 total_records += records_containing with open(f'''split-{args.split}-records-count.txt''' , '''w''' ) as f: print(f'''Total {args.split} records: {total_records}''' , file=_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = parse_args() main(args)
279
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = {"""configuration_vit_msn""": ["""VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTMSNConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ """VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST""", """ViTMSNModel""", """ViTMSNForImageClassification""", """ViTMSNPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
330
import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Any = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Any = hf_hub_download( repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : List[Any] = VideoClassificationPipeline(model=__magic_name__ , image_processor=__magic_name__ , top_k=2 ) snake_case_ : str = [ example_video_filepath, '''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''', ] return video_classifier, examples def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Any: '''simple docstring''' for example in examples: snake_case_ : Union[str, Any] = video_classifier(__magic_name__ ) self.assertEqual( __magic_name__ , [ {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, {'''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ )}, ] , ) @require_torch def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Any = '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification''' snake_case_ : str = VideoMAEFeatureExtractor( size={'''shortest_edge''': 10} , crop_size={'''height''': 10, '''width''': 10} ) snake_case_ : int = pipeline( '''video-classification''' , model=__magic_name__ , feature_extractor=__magic_name__ , frame_sampling_rate=4 ) snake_case_ : List[str] = hf_hub_download(repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) snake_case_ : Union[str, Any] = video_classifier(__magic_name__ , top_k=2 ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}] , ) snake_case_ : int = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], ] , ) @require_tf def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' pass
279
0
'''simple docstring''' from math import isclose, sqrt def _A (lowerCAmelCase__ :int , lowerCAmelCase__ :List[Any] , lowerCAmelCase__ :List[str] ) -> tuple[float, float, float]: '''simple docstring''' _a = point_y / 4 / point_x _a = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) _a = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) _a = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 _a = outgoing_gradient**2 + 4 _a = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) _a = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 _a = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) _a = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point _a = x_minus if isclose(_UpperCamelCase , _UpperCamelCase ) else x_plus _a = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def _A (lowerCAmelCase__ :List[Any] = 1.4 , lowerCAmelCase__ :List[Any] = -9.6 ) -> int: '''simple docstring''' _a = 0 _a = first_x_coord _a = first_y_coord _a = (1_0.1 - point_y) / (0.0 - point_x) while not (-0.0_1 <= point_x <= 0.0_1 and point_y > 0): _a = next_point(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f'''{solution() = }''')
168
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" return "\n".join( f'''{number} * {i} = {number * i}''' for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=1_0))
279
0
import numpy as np class SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] ): '''simple docstring''' __a = (0, 0) __a = None __a = 0 __a = 0 __a = 0 def __eq__( self : Tuple , __lowercase : Optional[Any] ): '''simple docstring''' return self.position == cell.position def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' print(self.position ) class SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , __lowercase : Any=(5, 5) ): '''simple docstring''' __a = np.zeros(__lowercase ) __a = world_size[0] __a = world_size[1] def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' print(self.w ) def UpperCamelCase_ ( self : Optional[Any] , __lowercase : List[str] ): '''simple docstring''' __a = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __a = cell.position[0] __a = cell.position[1] __a = [] for n in neughbour_cord: __a = current_x + n[0] __a = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __a = Cell() __a = (x, y) __a = cell neighbours.append(__lowercase ) return neighbours def lowerCAmelCase__ ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" __a = [] __a = [] _open.append(_UpperCamelCase ) while _open: __a = np.argmin([n.f for n in _open] ) __a = _open[min_f] _closed.append(_open.pop(_UpperCamelCase ) ) if current == goal: break for n in world.get_neigbours(_UpperCamelCase ): for c in _closed: if c == n: continue __a = current.g + 1 __a = n.position __a = goal.position __a = (ya - ya) ** 2 + (xa - xa) ** 2 __a = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(_UpperCamelCase ) __a = [] while current.parent is not None: path.append(current.position ) __a = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowerCamelCase__ = Gridworld() # Start position and goal lowerCamelCase__ = Cell() lowerCamelCase__ = (0, 0) lowerCamelCase__ = Cell() lowerCamelCase__ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowerCamelCase__ = astar(world, start, goal) # Just for visual reasons. for i in s: lowerCamelCase__ = 1 print(world.w)
302
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCAmelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def lowerCamelCase_ ( _UpperCamelCase ) -> List[Any]: """simple docstring""" snake_case_ : List[str] = ['''layers''', '''blocks'''] for k in ignore_keys: state_dict.pop(_UpperCamelCase , _UpperCamelCase ) lowerCAmelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" snake_case_ : str = list(s_dict.keys() ) for key in keys: snake_case_ : Optional[int] = key for k, v in WHISPER_MAPPING.items(): if k in key: snake_case_ : List[str] = new_key.replace(_UpperCamelCase , _UpperCamelCase ) print(f'''{key} -> {new_key}''' ) snake_case_ : Tuple = s_dict.pop(_UpperCamelCase ) return s_dict def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" snake_case_ , snake_case_ : Dict = emb.weight.shape snake_case_ : Tuple = nn.Linear(_UpperCamelCase , _UpperCamelCase , bias=_UpperCamelCase ) snake_case_ : Any = emb.weight.data return lin_layer def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> bytes: """simple docstring""" os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase ) snake_case_ : List[Any] = os.path.basename(_UpperCamelCase ) snake_case_ : Any = url.split('''/''' )[-2] snake_case_ : str = os.path.join(_UpperCamelCase , _UpperCamelCase ) if os.path.exists(_UpperCamelCase ) and not os.path.isfile(_UpperCamelCase ): raise RuntimeError(f'''{download_target} exists and is not a regular file''' ) if os.path.isfile(_UpperCamelCase ): snake_case_ : Union[str, Any] = open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f'''{download_target} exists, but the SHA256 checksum does not match; re-downloading the file''' ) with urllib.request.urlopen(_UpperCamelCase ) as source, open(_UpperCamelCase , '''wb''' ) as output: with tqdm( total=int(source.info().get('''Content-Length''' ) ) , ncols=80 , unit='''iB''' , unit_scale=_UpperCamelCase , unit_divisor=1_024 ) as loop: while True: snake_case_ : Dict = source.read(8_192 ) if not buffer: break output.write(_UpperCamelCase ) loop.update(len(_UpperCamelCase ) ) snake_case_ : Any = open(_UpperCamelCase , '''rb''' ).read() if hashlib.shaaaa(_UpperCamelCase ).hexdigest() != expected_shaaaa: raise RuntimeError( '''Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.''' ) return model_bytes def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" if ".pt" not in checkpoint_path: snake_case_ : str = _download(_MODELS[checkpoint_path] ) else: snake_case_ : Union[str, Any] = torch.load(_UpperCamelCase , map_location='''cpu''' ) snake_case_ : int = original_checkpoint['''dims'''] snake_case_ : List[str] = original_checkpoint['''model_state_dict'''] snake_case_ : str = state_dict['''decoder.token_embedding.weight'''] remove_ignore_keys_(_UpperCamelCase ) rename_keys(_UpperCamelCase ) snake_case_ : Optional[int] = True snake_case_ : int = state_dict['''decoder.layers.0.fc1.weight'''].shape[0] snake_case_ : List[str] = WhisperConfig( vocab_size=dimensions['''n_vocab'''] , encoder_ffn_dim=_UpperCamelCase , decoder_ffn_dim=_UpperCamelCase , num_mel_bins=dimensions['''n_mels'''] , d_model=dimensions['''n_audio_state'''] , max_target_positions=dimensions['''n_text_ctx'''] , encoder_layers=dimensions['''n_audio_layer'''] , encoder_attention_heads=dimensions['''n_audio_head'''] , decoder_layers=dimensions['''n_text_layer'''] , decoder_attention_heads=dimensions['''n_text_state'''] , max_source_positions=dimensions['''n_audio_ctx'''] , ) snake_case_ : Union[str, Any] = WhisperForConditionalGeneration(_UpperCamelCase ) snake_case_ , snake_case_ : List[Any] = model.model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) if len(_UpperCamelCase ) > 0 and not set(_UpperCamelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' f''' but all the following weights are missing {missing}''' ) if tie_embeds: snake_case_ : List[str] = make_linear_from_emb(model.model.decoder.embed_tokens ) else: snake_case_ : Any = proj_out_weights model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCAmelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCAmelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
279
0
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # General docstring _SCREAMING_SNAKE_CASE = """MobileNetV1Config""" # Base docstring _SCREAMING_SNAKE_CASE = """google/mobilenet_v1_1.0_224""" _SCREAMING_SNAKE_CASE = [1, 10_24, 7, 7] # Image classification docstring _SCREAMING_SNAKE_CASE = """google/mobilenet_v1_1.0_224""" _SCREAMING_SNAKE_CASE = """tabby, tabby cat""" _SCREAMING_SNAKE_CASE = [ """google/mobilenet_v1_1.0_224""", """google/mobilenet_v1_0.75_192""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def SCREAMING_SNAKE_CASE__ ( __a , __a , __a=None ): snake_case_ : Union[str, Any] = {} if isinstance(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Optional[Any] = model.mobilenet_va else: snake_case_ : Optional[Any] = model snake_case_ : Optional[int] = '''MobilenetV1/Conv2d_0/''' snake_case_ : List[str] = backbone.conv_stem.convolution.weight snake_case_ : Any = backbone.conv_stem.normalization.bias snake_case_ : List[str] = backbone.conv_stem.normalization.weight snake_case_ : Dict = backbone.conv_stem.normalization.running_mean snake_case_ : Optional[int] = backbone.conv_stem.normalization.running_var for i in range(13 ): snake_case_ : str = i + 1 snake_case_ : List[Any] = i * 2 snake_case_ : Tuple = backbone.layer[pt_index] snake_case_ : List[str] = f"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" snake_case_ : int = pointer.convolution.weight snake_case_ : Tuple = pointer.normalization.bias snake_case_ : Optional[int] = pointer.normalization.weight snake_case_ : int = pointer.normalization.running_mean snake_case_ : List[Any] = pointer.normalization.running_var snake_case_ : List[Any] = backbone.layer[pt_index + 1] snake_case_ : Dict = f"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" snake_case_ : List[Any] = pointer.convolution.weight snake_case_ : Optional[int] = pointer.normalization.bias snake_case_ : List[str] = pointer.normalization.weight snake_case_ : Union[str, Any] = pointer.normalization.running_mean snake_case_ : Optional[Any] = pointer.normalization.running_var if isinstance(_UpperCamelCase , _UpperCamelCase ): snake_case_ : Optional[int] = '''MobilenetV1/Logits/Conv2d_1c_1x1/''' snake_case_ : int = model.classifier.weight snake_case_ : Tuple = model.classifier.bias return tf_to_pt_map def SCREAMING_SNAKE_CASE__ ( __a , __a , __a ): try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.' ) raise # Load weights from TF model snake_case_ : List[str] = tf.train.list_variables(_UpperCamelCase ) snake_case_ : Dict = {} for name, shape in init_vars: logger.info(f"""Loading TF weight {name} with shape {shape}""" ) snake_case_ : Dict = tf.train.load_variable(_UpperCamelCase , _UpperCamelCase ) snake_case_ : Optional[int] = array # Build TF to PyTorch weights loading map snake_case_ : str = _build_tf_to_pytorch_map(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) for name, pointer in tf_to_pt_map.items(): logger.info(f"""Importing {name}""" ) if name not in tf_weights: logger.info(f"""{name} not in tf pre-trained weights, skipping""" ) continue snake_case_ : str = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise' ) snake_case_ : List[str] = np.transpose(_UpperCamelCase , (2, 3, 0, 1) ) elif "weights" in name: logger.info('Transposing' ) if len(pointer.shape ) == 2: # copying into linear layer snake_case_ : int = array.squeeze().transpose() else: snake_case_ : Union[str, Any] = np.transpose(_UpperCamelCase , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(f"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(f"""Initialize PyTorch weight {name} {array.shape}""" ) snake_case_ : Any = torch.from_numpy(_UpperCamelCase ) tf_weights.pop(_UpperCamelCase , _UpperCamelCase ) tf_weights.pop(name + '/RMSProp' , _UpperCamelCase ) tf_weights.pop(name + '/RMSProp_1' , _UpperCamelCase ) tf_weights.pop(name + '/ExponentialMovingAverage' , _UpperCamelCase ) logger.info(f"""Weights not copied to PyTorch model: {', '.join(tf_weights.keys() )}""" ) return model def SCREAMING_SNAKE_CASE__ ( __a , __a ): snake_case_ : Any = features.shape[-2:] snake_case_ : str = conv_layer.stride snake_case_ : List[Any] = conv_layer.kernel_size if in_height % stride_height == 0: snake_case_ : Tuple = max(kernel_height - stride_height , 0 ) else: snake_case_ : Union[str, Any] = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: snake_case_ : Optional[int] = max(kernel_width - stride_width , 0 ) else: snake_case_ : Dict = max(kernel_width - (in_width % stride_width) , 0 ) snake_case_ : Union[str, Any] = pad_along_width // 2 snake_case_ : Optional[Any] = pad_along_width - pad_left snake_case_ : Optional[Any] = pad_along_height // 2 snake_case_ : Union[str, Any] = pad_along_height - pad_top snake_case_ : Tuple = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(_UpperCamelCase , _UpperCamelCase , 'constant' , 0.0 ) class SCREAMING_SNAKE_CASE_ ( nn.Module ): def __init__( self : Any , _A : Dict , _A : List[Any] , _A : List[str] , _A : List[Any] , _A : Optional[int] = 1 , _A : List[Any] = 1 , _A : Tuple = False , _A : Optional[int] = True , _A : Optional[Any] = True , ) -> None: """simple docstring""" super().__init__() snake_case_ : Optional[Any] = config if in_channels % groups != 0: raise ValueError(F"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(F"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) snake_case_ : List[str] = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) snake_case_ : List[str] = nn.Convad( in_channels=_A , out_channels=_A , kernel_size=_A , stride=_A , padding=_A , groups=_A , bias=_A , padding_mode='zeros' , ) if use_normalization: snake_case_ : Tuple = nn.BatchNormad( num_features=_A , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=_A , track_running_stats=_A , ) else: snake_case_ : str = None if use_activation: if isinstance(_A , _A ): snake_case_ : Optional[Any] = ACTaFN[use_activation] elif isinstance(config.hidden_act , _A ): snake_case_ : Any = ACTaFN[config.hidden_act] else: snake_case_ : List[str] = config.hidden_act else: snake_case_ : Any = None def UpperCAmelCase_ ( self : Dict , _A : Any ) -> torch.Tensor: """simple docstring""" if self.config.tf_padding: snake_case_ : Union[str, Any] = apply_tf_padding(_A , self.convolution ) snake_case_ : Union[str, Any] = self.convolution(_A ) if self.normalization is not None: snake_case_ : int = self.normalization(_A ) if self.activation is not None: snake_case_ : List[Any] = self.activation(_A ) return features class SCREAMING_SNAKE_CASE_ ( _a ): __magic_name__: Tuple = MobileNetVaConfig __magic_name__: Optional[int] = load_tf_weights_in_mobilenet_va __magic_name__: int = '''mobilenet_v1''' __magic_name__: str = '''pixel_values''' __magic_name__: List[str] = False def UpperCAmelCase_ ( self : List[str] , _A : Tuple ) -> None: """simple docstring""" if isinstance(_A , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_A , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) _SCREAMING_SNAKE_CASE = R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ _SCREAMING_SNAKE_CASE = R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare MobileNetV1 model outputting raw hidden-states without any specific head on top." , _a , ) class SCREAMING_SNAKE_CASE_ ( _a ): def __init__( self : Tuple , _A : Dict , _A : Dict = True ) -> List[Any]: """simple docstring""" super().__init__(_A ) snake_case_ : Union[str, Any] = config snake_case_ : str = 32 snake_case_ : Optional[int] = max(int(depth * config.depth_multiplier ) , config.min_depth ) snake_case_ : List[str] = MobileNetVaConvLayer( _A , in_channels=config.num_channels , out_channels=_A , kernel_size=3 , stride=2 , ) snake_case_ : Any = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] snake_case_ : Union[str, Any] = nn.ModuleList() for i in range(13 ): snake_case_ : List[str] = out_channels if strides[i] == 2 or i == 0: depth *= 2 snake_case_ : Dict = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( _A , in_channels=_A , out_channels=_A , kernel_size=3 , stride=strides[i] , groups=_A , ) ) self.layer.append( MobileNetVaConvLayer( _A , in_channels=_A , out_channels=_A , kernel_size=1 , ) ) snake_case_ : List[str] = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def UpperCAmelCase_ ( self : Tuple , _A : Tuple ) -> Dict: """simple docstring""" raise NotImplementedError @add_start_docstrings_to_model_forward(_A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_A , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : Tuple , _A : Optional[int] = None , _A : Any = None , _A : Dict = None , ) -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: """simple docstring""" snake_case_ : Tuple = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case_ : Dict = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) snake_case_ : Union[str, Any] = self.conv_stem(_A ) snake_case_ : Union[str, Any] = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): snake_case_ : List[str] = layer_module(_A ) if output_hidden_states: snake_case_ : Union[str, Any] = all_hidden_states + (hidden_states,) snake_case_ : Any = hidden_states if self.pooler is not None: snake_case_ : Optional[int] = torch.flatten(self.pooler(_A ) , start_dim=1 ) else: snake_case_ : Tuple = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_A , pooler_output=_A , hidden_states=_A , ) @add_start_docstrings( "\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , _a , ) class SCREAMING_SNAKE_CASE_ ( _a ): def __init__( self : Any , _A : Optional[int] ) -> None: """simple docstring""" super().__init__(_A ) snake_case_ : Dict = config.num_labels snake_case_ : List[str] = MobileNetVaModel(_A ) snake_case_ : Optional[int] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head snake_case_ : Union[str, Any] = nn.Dropout(config.classifier_dropout_prob , inplace=_A ) snake_case_ : Any = nn.Linear(_A , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Optional[int] , _A : Optional[Any] = None , _A : List[Any] = None , _A : Optional[Any] = None , _A : List[str] = None , ) -> Union[tuple, ImageClassifierOutputWithNoAttention]: """simple docstring""" snake_case_ : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict snake_case_ : Any = self.mobilenet_va(_A , output_hidden_states=_A , return_dict=_A ) snake_case_ : Optional[Any] = outputs.pooler_output if return_dict else outputs[1] snake_case_ : List[Any] = self.classifier(self.dropout(_A ) ) snake_case_ : Optional[Any] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: snake_case_ : List[str] = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): snake_case_ : List[str] = '''single_label_classification''' else: snake_case_ : Optional[Any] = '''multi_label_classification''' if self.config.problem_type == "regression": snake_case_ : Optional[Any] = MSELoss() if self.num_labels == 1: snake_case_ : str = loss_fct(logits.squeeze() , labels.squeeze() ) else: snake_case_ : str = loss_fct(_A , _A ) elif self.config.problem_type == "single_label_classification": snake_case_ : List[str] = CrossEntropyLoss() snake_case_ : Union[str, Any] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": snake_case_ : Tuple = BCEWithLogitsLoss() snake_case_ : Optional[Any] = loss_fct(_A , _A ) if not return_dict: snake_case_ : int = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=_A , logits=_A , hidden_states=outputs.hidden_states , )
327
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCAmelCase_ = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) lowerCAmelCase_ = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 1_4]), ('''2H 5D 3C AS 5S''', False, [1_4, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [1_4, 1_3, 1_2, 1_1, 1_0]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 2_3), ('''JH 9H TH KH QH''', 2_2), ('''JC KH JS JD JH''', 2_1), ('''KH KC 3S 3H 3D''', 2_0), ('''8C 9C 5C 3C TC''', 1_9), ('''JS QS 9H TS KH''', 1_8), ('''7C 7S KH 2H 7H''', 1_7), ('''3C KH 5D 5S KH''', 1_6), ('''QH 8H KD JH 8S''', 1_5), ('''2D 6D 9D TH 7D''', 1_4), ) def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ , snake_case_ : Any = randrange(len(_UpperCamelCase ) ), randrange(len(_UpperCamelCase ) ) snake_case_ : Any = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] snake_case_ , snake_case_ : Tuple = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def lowerCamelCase_ ( _UpperCamelCase = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(_UpperCamelCase )) @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : str = PokerHand(_UpperCamelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[Any]: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = [PokerHand(_UpperCamelCase ) for hand in SORTED_HANDS] snake_case_ : str = poker_hands.copy() shuffle(_UpperCamelCase ) snake_case_ : List[str] = chain(sorted(_UpperCamelCase ) ) for index, hand in enumerate(_UpperCamelCase ): assert hand == poker_hands[index] def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ : Union[str, Any] = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=_UpperCamelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = PokerHand('''2C 4S AS 3D 5C''' ) snake_case_ : str = True snake_case_ : Tuple = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def lowerCamelCase_ ( ) -> List[str]: """simple docstring""" snake_case_ : List[str] = 0 snake_case_ : Union[str, Any] = os.path.abspath(os.path.dirname(_UpperCamelCase ) ) snake_case_ : Dict = os.path.join(_UpperCamelCase , '''poker_hands.txt''' ) with open(_UpperCamelCase ) as file_hand: for line in file_hand: snake_case_ : Dict = line[:14].strip() snake_case_ : List[str] = line[15:].strip() snake_case_ , snake_case_ : str = PokerHand(_UpperCamelCase ), PokerHand(_UpperCamelCase ) snake_case_ : int = player.compare_with(_UpperCamelCase ) if output == "Win": answer += 1 assert answer == 376
279
0
'''simple docstring''' from cva import destroyAllWindows, imread, imshow, waitKey def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ) -> int: _a : List[Any] =img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): _a : Dict =[255, 255, 255] - img[i][j] return img if __name__ == "__main__": # read original image A__: List[Any] = imread('''image_data/lena.jpg''', 1) # convert to its negative A__: Union[str, Any] = convert_to_negative(img) # show result image imshow('''negative of original image''', img) waitKey(0) destroyAllWindows()
276
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available lowerCAmelCase_ = logging.getLogger(__name__) @dataclass class __lowerCAmelCase : lowerCamelCase_ : str lowerCamelCase_ : List[str] lowerCamelCase_ : Optional[List[str]] @dataclass class __lowerCAmelCase : lowerCamelCase_ : List[int] lowerCamelCase_ : List[int] lowerCamelCase_ : Optional[List[int]] = None lowerCamelCase_ : Optional[List[int]] = None class __lowerCAmelCase ( _a ): lowerCamelCase_ : str = '''train''' lowerCamelCase_ : List[str] = '''dev''' lowerCamelCase_ : List[Any] = '''test''' class __lowerCAmelCase : @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def lowerCamelCase (__magic_name__ ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def lowerCamelCase (__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=False , __magic_name__="[CLS]" , __magic_name__=1 , __magic_name__="[SEP]" , __magic_name__=False , __magic_name__=False , __magic_name__=0 , __magic_name__=0 , __magic_name__=-100 , __magic_name__=0 , __magic_name__=True , ) -> List[InputFeatures]: '''simple docstring''' snake_case_ : Optional[int] = {label: i for i, label in enumerate(__magic_name__ )} snake_case_ : Dict = [] for ex_index, example in enumerate(__magic_name__ ): if ex_index % 1_0000 == 0: logger.info('''Writing example %d of %d''' , __magic_name__ , len(__magic_name__ ) ) snake_case_ : List[str] = [] snake_case_ : List[str] = [] for word, label in zip(example.words , example.labels ): snake_case_ : Optional[Any] = tokenizer.tokenize(__magic_name__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(__magic_name__ ) > 0: tokens.extend(__magic_name__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(__magic_name__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. snake_case_ : Union[str, Any] = tokenizer.num_special_tokens_to_add() if len(__magic_name__ ) > max_seq_length - special_tokens_count: snake_case_ : str = tokens[: (max_seq_length - special_tokens_count)] snake_case_ : Any = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] snake_case_ : Union[str, Any] = [sequence_a_segment_id] * len(__magic_name__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: snake_case_ : Union[str, Any] = [cls_token] + tokens snake_case_ : List[Any] = [pad_token_label_id] + label_ids snake_case_ : Optional[Any] = [cls_token_segment_id] + segment_ids snake_case_ : Optional[Any] = tokenizer.convert_tokens_to_ids(__magic_name__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. snake_case_ : int = [1 if mask_padding_with_zero else 0] * len(__magic_name__ ) # Zero-pad up to the sequence length. snake_case_ : Optional[int] = max_seq_length - len(__magic_name__ ) if pad_on_left: snake_case_ : Optional[Any] = ([pad_token] * padding_length) + input_ids snake_case_ : Optional[int] = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask snake_case_ : Optional[Any] = ([pad_token_segment_id] * padding_length) + segment_ids snake_case_ : Dict = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length assert len(__magic_name__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(__magic_name__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(__magic_name__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(__magic_name__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: snake_case_ : int = None features.append( InputFeatures( input_ids=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , label_ids=__magic_name__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class __lowerCAmelCase ( _a ): lowerCamelCase_ : List[InputFeatures] lowerCamelCase_ : int = nn.CrossEntropyLoss().ignore_index def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=False , __magic_name__ = Split.train , ) -> Union[str, Any]: '''simple docstring''' snake_case_ : List[str] = os.path.join( __magic_name__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(__magic_name__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case_ : Dict = cached_features_file + '''.lock''' with FileLock(__magic_name__ ): if os.path.exists(__magic_name__ ) and not overwrite_cache: logger.info(F'''Loading features from cached file {cached_features_file}''' ) snake_case_ : Dict = torch.load(__magic_name__ ) else: logger.info(F'''Creating features from dataset file at {data_dir}''' ) snake_case_ : Any = token_classification_task.read_examples_from_file(__magic_name__ , __magic_name__ ) # TODO clean up all this to leverage built-in features of tokenizers snake_case_ : int = token_classification_task.convert_examples_to_features( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , __magic_name__ ) def __len__(self ) -> Optional[Any]: '''simple docstring''' return len(self.features ) def __getitem__(self , __magic_name__ ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class __lowerCAmelCase : lowerCamelCase_ : List[InputFeatures] lowerCamelCase_ : int = -100 def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = None , __magic_name__=False , __magic_name__ = Split.train , ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[int] = token_classification_task.read_examples_from_file(__magic_name__ , __magic_name__ ) # TODO clean up all this to leverage built-in features of tokenizers snake_case_ : int = token_classification_task.convert_examples_to_features( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=__magic_name__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: snake_case_ : Optional[Any] = tf.data.Dataset.from_generator( __magic_name__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: snake_case_ : int = tf.data.Dataset.from_generator( __magic_name__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[Any] = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__(self ) -> str: '''simple docstring''' return len(self.features ) def __getitem__(self , __magic_name__ ) -> InputFeatures: '''simple docstring''' return self.features[i]
279
0
"""simple docstring""" import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=4 , ) -> Optional[Any]: __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = seq_length __lowerCAmelCase = is_training __lowerCAmelCase = use_attention_mask __lowerCAmelCase = use_token_type_ids __lowerCAmelCase = use_labels __lowerCAmelCase = vocab_size __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = max_position_embeddings __lowerCAmelCase = type_vocab_size __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = num_choices def A__ ( self ) -> Tuple: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase = None if self.use_attention_mask: __lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase = None if self.use_token_type_ids: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase = AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case_ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def A__ ( self ) -> int: __lowerCAmelCase = self.prepare_config_and_inputs() __lowerCAmelCase = config_and_inputs __lowerCAmelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class lowerCAmelCase_ ( _a , unittest.TestCase ): '''simple docstring''' _snake_case = ( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def A__ ( self ) -> List[Any]: __lowerCAmelCase = FlaxAlbertModelTester(self ) @slow def A__ ( self ) -> List[Any]: for model_class_name in self.all_model_classes: __lowerCAmelCase = model_class_name.from_pretrained("""albert-base-v2""" ) __lowerCAmelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(snake_case_ ) @require_flax class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def A__ ( self ) -> Any: __lowerCAmelCase = FlaxAlbertModel.from_pretrained("""albert-base-v2""" ) __lowerCAmelCase = np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) __lowerCAmelCase = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) __lowerCAmelCase = model(snake_case_ , attention_mask=snake_case_ )[0] __lowerCAmelCase = (1, 11, 768) self.assertEqual(output.shape , snake_case_ ) __lowerCAmelCase = np.array( [[[-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(jnp.allclose(output[:, 1:4, 1:4] , snake_case_ , atol=1e-4 ) )
301
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase_ = get_tests_dir('''fixtures/test_sentencepiece_bpe_char.model''') @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( _a, unittest.TestCase ): lowerCamelCase_ : Optional[int] = SpeechTaTokenizer lowerCamelCase_ : int = False lowerCamelCase_ : Dict = True def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing snake_case_ : Tuple = SpeechTaTokenizer(__magic_name__ ) snake_case_ : Any = AddedToken('''<mask>''' , lstrip=__magic_name__ , rstrip=__magic_name__ ) snake_case_ : int = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Dict = '''this is a test''' snake_case_ : int = '''this is a test''' return input_text, output_text def lowerCamelCase (self , __magic_name__ , __magic_name__=False , __magic_name__=20 , __magic_name__=5 ) -> List[Any]: '''simple docstring''' snake_case_ , snake_case_ : int = self.get_input_output_texts(__magic_name__ ) snake_case_ : Optional[Any] = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) snake_case_ : Any = tokenizer.decode(__magic_name__ , clean_up_tokenization_spaces=__magic_name__ ) return text, ids def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[str] = '''<pad>''' snake_case_ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(__magic_name__ ) , 81 ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : int = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): snake_case_ : int = tokenizer.vocab_size snake_case_ : Optional[Any] = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case_ : List[Any] = ['''aaaaa bbbbbb''', '''cccccccccdddddddd'''] snake_case_ : List[Any] = tokenizer.add_tokens(__magic_name__ ) snake_case_ : Dict = tokenizer.vocab_size snake_case_ : Optional[Any] = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size + len(__magic_name__ ) ) snake_case_ : Union[str, Any] = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case_ : Union[str, Any] = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''} snake_case_ : List[str] = tokenizer.add_special_tokens(__magic_name__ ) snake_case_ : Dict = tokenizer.vocab_size snake_case_ : Dict = len(__magic_name__ ) self.assertNotEqual(__magic_name__ , 0 ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertEqual(__magic_name__ , len(__magic_name__ ) ) self.assertEqual(__magic_name__ , all_size_a + len(__magic_name__ ) ) snake_case_ : Tuple = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__magic_name__ ) self.assertGreaterEqual(len(__magic_name__ ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> List[str]: '''simple docstring''' pass def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Dict = self.get_tokenizer() snake_case_ : Optional[Any] = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(__magic_name__ , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case_ : List[Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) snake_case_ : List[str] = tokenizer.convert_tokens_to_ids(__magic_name__ ) # fmt: off self.assertListEqual(__magic_name__ , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case_ : int = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' snake_case_ : Tuple = [ '''Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides ''' '''general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural ''' '''Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained ''' '''models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.''', '''BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly ''' '''conditioning on both left and right context in all layers.''', '''The quick brown fox jumps over the lazy dog.''', ] # fmt: off snake_case_ : List[Any] = { '''input_ids''': [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=__magic_name__ , )
279
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { """facebook/vit-mae-base""": """https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json""", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class UpperCamelCase__ ( _a ): """simple docstring""" SCREAMING_SNAKE_CASE__ = '''vit_mae''' def __init__( self : str , lowerCamelCase_ : Optional[Any]=7_68 , lowerCamelCase_ : Union[str, Any]=12 , lowerCamelCase_ : Optional[int]=12 , lowerCamelCase_ : Any=30_72 , lowerCamelCase_ : List[str]="gelu" , lowerCamelCase_ : int=0.0 , lowerCamelCase_ : Dict=0.0 , lowerCamelCase_ : Any=0.02 , lowerCamelCase_ : int=1e-12 , lowerCamelCase_ : Optional[Any]=2_24 , lowerCamelCase_ : Union[str, Any]=16 , lowerCamelCase_ : Any=3 , lowerCamelCase_ : Optional[Any]=True , lowerCamelCase_ : List[Any]=16 , lowerCamelCase_ : List[Any]=5_12 , lowerCamelCase_ : Dict=8 , lowerCamelCase_ : Optional[int]=20_48 , lowerCamelCase_ : Optional[Any]=0.75 , lowerCamelCase_ : Union[str, Any]=False , **lowerCamelCase_ : Union[str, Any] , ): '''simple docstring''' super().__init__(**lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE : int = num_hidden_layers SCREAMING_SNAKE_CASE : str = num_attention_heads SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : int = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Any = initializer_range SCREAMING_SNAKE_CASE : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE : Optional[int] = image_size SCREAMING_SNAKE_CASE : List[Any] = patch_size SCREAMING_SNAKE_CASE : str = num_channels SCREAMING_SNAKE_CASE : Tuple = qkv_bias SCREAMING_SNAKE_CASE : List[Any] = decoder_num_attention_heads SCREAMING_SNAKE_CASE : int = decoder_hidden_size SCREAMING_SNAKE_CASE : Dict = decoder_num_hidden_layers SCREAMING_SNAKE_CASE : Any = decoder_intermediate_size SCREAMING_SNAKE_CASE : Optional[int] = mask_ratio SCREAMING_SNAKE_CASE : Optional[Any] = norm_pix_loss
323
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: """simple docstring""" print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' ) for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): if dist[i][j] != float('''inf''' ): print(int(dist[i][j] ) , end='''\t''' ) else: print('''INF''' , end='''\t''' ) print() def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" snake_case_ : int = [[float('''inf''' ) for _ in range(_UpperCamelCase )] for _ in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): for j in range(_UpperCamelCase ): snake_case_ : Dict = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(_UpperCamelCase ): # looping through rows of graph array for i in range(_UpperCamelCase ): # looping through columns of graph array for j in range(_UpperCamelCase ): if ( dist[i][k] != float('''inf''' ) and dist[k][j] != float('''inf''' ) and dist[i][k] + dist[k][j] < dist[i][j] ): snake_case_ : List[Any] = dist[i][k] + dist[k][j] _print_dist(_UpperCamelCase , _UpperCamelCase ) return dist, v if __name__ == "__main__": lowerCAmelCase_ = int(input('''Enter number of vertices: ''')) lowerCAmelCase_ = int(input('''Enter number of edges: ''')) lowerCAmelCase_ = [[float('''inf''') for i in range(v)] for j in range(v)] for i in range(v): lowerCAmelCase_ = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print('''\nEdge ''', i + 1) lowerCAmelCase_ = int(input('''Enter source:''')) lowerCAmelCase_ = int(input('''Enter destination:''')) lowerCAmelCase_ = float(input('''Enter weight:''')) lowerCAmelCase_ = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
279
0
"""simple docstring""" # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers __SCREAMING_SNAKE_CASE =float("nan") class UpperCamelCase : def __init__( self ,__UpperCamelCase ) -> int: '''simple docstring''' lowercase_ : List[Any] = sys.stdout lowercase_ : int = open(__UpperCamelCase ,'a' ) def __getattr__( self ,__UpperCamelCase ) -> Dict: '''simple docstring''' return getattr(self.stdout ,__UpperCamelCase ) def _UpperCAmelCase ( self ,__UpperCamelCase ) -> int: '''simple docstring''' self.stdout.write(__UpperCamelCase ) # strip tqdm codes self.file.write(re.sub(r'^.*\r' ,'' ,__UpperCamelCase ,0 ,re.M ) ) def lowercase__( __SCREAMING_SNAKE_CASE : Any=80 , __SCREAMING_SNAKE_CASE : Dict=False ): lowercase_ : str = [] # deal with critical env vars lowercase_ : int = ['''CUDA_VISIBLE_DEVICES'''] for key in env_keys: lowercase_ : Optional[int] = os.environ.get(_UpperCamelCase , _UpperCamelCase ) if val is not None: cmd.append(F'''{key}={val}''' ) # python executable (not always needed if the script is executable) lowercase_ : Optional[int] = sys.executable if full_python_path else sys.executable.split('/' )[-1] cmd.append(_UpperCamelCase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes lowercase_ : Dict = [] lowercase_ : Dict = '''''' while len(_UpperCamelCase ) > 0: current_line += F'''{cmd.pop(0 )} ''' if len(_UpperCamelCase ) == 0 or len(_UpperCamelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(_UpperCamelCase ) lowercase_ : List[Any] = '''''' return "\\\n".join(_UpperCamelCase ) def lowercase__( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] ): lowercase_ : str = re.sub(R'[\\\n]+' , ' ' , args.base_cmd ) # remove --output_dir if any and set our own lowercase_ : Optional[Any] = re.sub('--output_dir\s+[^\s]+' , '' , args.base_cmd ) args.base_cmd += F''' --output_dir {output_dir}''' # ensure we have --overwrite_output_dir lowercase_ : int = re.sub('--overwrite_output_dir\s+' , '' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def lowercase__( __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : List[str] ): if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 1_00 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.2222_2222] )} , ) lowercase_ : Tuple = subprocess.run(_UpperCamelCase , capture_output=_UpperCamelCase , text=_UpperCamelCase ) if verbose: print('STDOUT' , result.stdout ) print('STDERR' , result.stderr ) # save the streams lowercase_ : Any = variation.replace(' ' , '-' ) with open(Path(_UpperCamelCase ) / F'''log.{prefix}.stdout.txt''' , 'w' ) as f: f.write(result.stdout ) with open(Path(_UpperCamelCase ) / F'''log.{prefix}.stderr.txt''' , 'w' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('failed' ) return {target_metric_key: nan} with io.open(F'''{output_dir}/all_results.json''' , 'r' , encoding='utf-8' ) as f: lowercase_ : str = json.load(_UpperCamelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def lowercase__( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Any , ): lowercase_ : Tuple = [] lowercase_ : Any = [] lowercase_ : int = F'''{id}: {variation:<{longest_variation_len}}''' lowercase_ : Optional[Any] = F'''{preamble}: ''' lowercase_ : Optional[int] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(_UpperCamelCase ) , desc=_UpperCamelCase , leave=_UpperCamelCase ): lowercase_ : int = process_run_single( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) lowercase_ : List[str] = single_run_metrics[target_metric_key] if not math.isnan(_UpperCamelCase ): metrics.append(_UpperCamelCase ) results.append(_UpperCamelCase ) outcome += "✓" else: outcome += "✘" lowercase_ : Any = F'''\33[2K\r{outcome}''' if len(_UpperCamelCase ) > 0: lowercase_ : List[Any] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} lowercase_ : Any = round(mean_metrics[target_metric_key] , 2 ) lowercase_ : List[str] = F'''{outcome} {mean_target}''' if len(_UpperCamelCase ) > 1: results_str += F''' {tuple(round(_UpperCamelCase , 2 ) for x in results )}''' print(_UpperCamelCase ) lowercase_ : Optional[int] = variation return mean_metrics else: print(_UpperCamelCase ) return {variation_key: variation, target_metric_key: nan} def lowercase__( ): lowercase_ : Any = torch.cuda.get_device_properties(torch.device('cuda' ) ) return F''' Datetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB ''' def lowercase__( __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] ): lowercase_ : str = pd.DataFrame(_UpperCamelCase ) lowercase_ : Optional[int] = '''variation''' lowercase_ : Union[str, Any] = '''diff_%''' lowercase_ : Optional[int] = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan lowercase_ : Optional[Any] = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(_UpperCamelCase ): # as a fallback, use the minimal value as the sentinel lowercase_ : Any = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(_UpperCamelCase ): lowercase_ : Dict = df.apply( lambda __SCREAMING_SNAKE_CASE : round(1_00 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='columns' , ) # re-order columns lowercase_ : Dict = [variation_key, target_metric_key, diff_key, *report_metric_keys] lowercase_ : int = df.reindex(_UpperCamelCase , axis='columns' ) # reorder cols # capitalize lowercase_ : Optional[int] = df.rename(str.capitalize , axis='columns' ) # make the cols as narrow as possible lowercase_ : Any = df.rename(lambda __SCREAMING_SNAKE_CASE : c.replace('_' , '<br>' ) , axis='columns' ) lowercase_ : int = df.rename(lambda __SCREAMING_SNAKE_CASE : c.replace('_' , '\n' ) , axis='columns' ) lowercase_ : Tuple = ['''''', '''Copy between the cut-here-lines and paste as is to github or a forum'''] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=_UpperCamelCase , floatfmt='.2f' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=_UpperCamelCase , floatfmt='.2f' )] print('\n\n'.join(_UpperCamelCase ) ) def lowercase__( ): lowercase_ : Any = argparse.ArgumentParser() parser.add_argument( '--base-cmd' , default=_UpperCamelCase , type=_UpperCamelCase , required=_UpperCamelCase , help='Base cmd' , ) parser.add_argument( '--variations' , default=_UpperCamelCase , type=_UpperCamelCase , nargs='+' , required=_UpperCamelCase , help='Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'' , ) parser.add_argument( '--base-variation' , default=_UpperCamelCase , type=_UpperCamelCase , help='Baseline variation to compare to. if None the minimal target value will be used to compare against' , ) parser.add_argument( '--target-metric-key' , default=_UpperCamelCase , type=_UpperCamelCase , required=_UpperCamelCase , help='Target metric key in output_dir/all_results.json, e.g., train_samples_per_second' , ) parser.add_argument( '--report-metric-keys' , default='' , type=_UpperCamelCase , help='Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples' , ) parser.add_argument( '--repeat-times' , default=1 , type=_UpperCamelCase , help='How many times to re-run each variation - an average will be reported' , ) parser.add_argument( '--output_dir' , default='output_benchmark' , type=_UpperCamelCase , help='The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked' , ) parser.add_argument( '--verbose' , default=_UpperCamelCase , action='store_true' , help='Whether to show the outputs of each run or just the benchmark progress' , ) lowercase_ : Tuple = parser.parse_args() lowercase_ : Optional[Any] = args.output_dir Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) lowercase_ : Optional[int] = get_base_command(_UpperCamelCase , _UpperCamelCase ) # split each dimension into its --foo variations lowercase_ : Optional[int] = [list(map(str.strip , re.split(R'\|' , _UpperCamelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty lowercase_ : List[str] = list(map(str.strip , map(' '.join , itertools.product(*_UpperCamelCase ) ) ) ) lowercase_ : Optional[int] = max(len(_UpperCamelCase ) for x in variations ) # split wanted keys lowercase_ : int = args.report_metric_keys.split() # capture prints into a log file for convenience lowercase_ : str = F'''benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt''' print(F'''\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt''' ) print(F'''and this script\'s output is also piped into {report_fn}''' ) lowercase_ : Tuple = Tee(_UpperCamelCase ) print(F'''\n*** Running {len(_UpperCamelCase )} benchmarks:''' ) print(F'''Base command: {" ".join(_UpperCamelCase )}''' ) lowercase_ : List[Any] = '''variation''' lowercase_ : Tuple = [] for id, variation in enumerate(tqdm(_UpperCamelCase , desc='Total completion: ' , leave=_UpperCamelCase ) ): lowercase_ : Optional[Any] = base_cmd + variation.split() results.append( process_run( id + 1 , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , args.target_metric_key , _UpperCamelCase , args.repeat_times , _UpperCamelCase , args.verbose , ) ) process_results(_UpperCamelCase , args.target_metric_key , _UpperCamelCase , args.base_variation , _UpperCamelCase ) if __name__ == "__main__": main()
213
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class __lowerCAmelCase : def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' return None class __lowerCAmelCase : def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' return None class __lowerCAmelCase ( unittest.TestCase ): lowerCamelCase_ : Dict = [ # (model_name, model_kwargs) ('''bert-base-cased''', {}), ('''gpt2''', {'''use_cache''': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__magic_name__ , '''tf''' , 12 , **__magic_name__ ) @require_torch @slow def lowerCamelCase (self ) -> int: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__magic_name__ , '''pt''' , 12 , **__magic_name__ ) @require_torch @slow def lowerCamelCase (self ) -> int: '''simple docstring''' from transformers import BertModel snake_case_ : str = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(__magic_name__ ) ) vocab_file.flush() snake_case_ : Optional[Any] = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: snake_case_ : str = BertModel(BertConfig(vocab_size=len(__magic_name__ ) ) ) model.save_pretrained(__magic_name__ ) self._test_export(__magic_name__ , '''pt''' , 12 , __magic_name__ ) @require_tf @slow def lowerCamelCase (self ) -> Tuple: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ : Tuple = self._test_export(__magic_name__ , '''tf''' , 12 , **__magic_name__ ) snake_case_ : List[str] = quantize(Path(__magic_name__ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__magic_name__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case_ : Any = self._test_export(__magic_name__ , '''pt''' , 12 , **__magic_name__ ) snake_case_ : Any = quantize(__magic_name__ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__magic_name__ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=None , **__magic_name__ ) -> Tuple: '''simple docstring''' try: # Compute path with TemporaryDirectory() as tempdir: snake_case_ : List[str] = Path(__magic_name__ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) return path except Exception as e: self.fail(__magic_name__ ) @require_torch @require_tokenizers @slow def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' from transformers import BertModel snake_case_ : Optional[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case_ : int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(__magic_name__ , __magic_name__ , '''pt''' ) @require_tf @require_tokenizers @slow def lowerCamelCase (self ) -> List[str]: '''simple docstring''' from transformers import TFBertModel snake_case_ : Any = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case_ : str = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(__magic_name__ , __magic_name__ , '''tf''' ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : Tuple = FeatureExtractionPipeline(__magic_name__ , __magic_name__ ) snake_case_ : Optional[int] = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] snake_case_ , snake_case_ , snake_case_ , snake_case_ : Optional[int] = infer_shapes(__magic_name__ , __magic_name__ ) # Assert all variables are present self.assertEqual(len(__magic_name__ ) , len(__magic_name__ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __magic_name__ ) self.assertSequenceEqual(variable_names[3:] , __magic_name__ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : Tuple = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] snake_case_ : List[str] = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} snake_case_ , snake_case_ : Tuple = ensure_valid_input(FuncContiguousArgs() , __magic_name__ , __magic_name__ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__magic_name__ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__magic_name__ ) , set(__magic_name__ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__magic_name__ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) snake_case_ , snake_case_ : Dict = ensure_valid_input(FuncNonContiguousArgs() , __magic_name__ , __magic_name__ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__magic_name__ ) , 1 ) self.assertEqual(len(__magic_name__ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : Optional[int] = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
279
0
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __snake_case ( _a , unittest.TestCase ): __lowerCamelCase : Tuple = CLIPTokenizer __lowerCamelCase : Tuple = CLIPTokenizerFast __lowerCamelCase : List[str] = True __lowerCamelCase : Tuple = {} __lowerCamelCase : Any = False def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' super().setUp() # fmt: off UpperCAmelCase : Optional[int] =['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on UpperCAmelCase : str =dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) UpperCAmelCase : Optional[int] =['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>'''] UpperCAmelCase : Dict ={'''unk_token''': '''<unk>'''} UpperCAmelCase : int =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase : List[Any] =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 UpperCAmelCase__ ( self , **snake_case__ ) -> Union[str, Any]: '''simple docstring''' kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **snake_case__ ) def UpperCAmelCase__ ( self , **snake_case__ ) -> Any: '''simple docstring''' kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **snake_case__ ) def UpperCAmelCase__ ( self , snake_case__ ) -> Any: '''simple docstring''' UpperCAmelCase : Dict ='''lower newer''' UpperCAmelCase : Union[str, Any] ='''lower newer''' return input_text, output_text def UpperCAmelCase__ ( self ) -> str: '''simple docstring''' UpperCAmelCase : Dict =CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCAmelCase : Union[str, Any] ='''lower newer''' UpperCAmelCase : Union[str, Any] =['''lo''', '''w''', '''er</w>''', '''n''', '''e''', '''w''', '''er</w>'''] UpperCAmelCase : Union[str, Any] =tokenizer.tokenize(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) UpperCAmelCase : int =tokens + [tokenizer.unk_token] UpperCAmelCase : Any =[10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case__ ) , snake_case__ ) @require_ftfy def UpperCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCAmelCase : List[str] =self.tokenizer_class.from_pretrained(snake_case__ , **snake_case__ ) UpperCAmelCase : int =self.rust_tokenizer_class.from_pretrained(snake_case__ , **snake_case__ ) UpperCAmelCase : Union[str, Any] ='''A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.''' UpperCAmelCase : Any =tokenizer_s.tokenize(snake_case__ ) UpperCAmelCase : List[Any] =tokenizer_r.tokenize(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways UpperCAmelCase : Optional[Any] ='''xa\u0303y''' + ''' ''' + '''x\xe3y''' UpperCAmelCase : int =tokenizer_s.tokenize(snake_case__ ) UpperCAmelCase : Any =tokenizer_r.tokenize(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) # Test that the tokenization is identical on unicode of space type UpperCAmelCase : int =[ '''\u0009''', # (horizontal tab, '\t') '''\u000B''', # (vertical tab) '''\u000C''', # (form feed) '''\u0020''', # (space, ' ') '''\u200E''', # (left-to-right mark):w '''\u200F''', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: UpperCAmelCase : List[str] =tokenizer_s.tokenize(snake_case__ ) UpperCAmelCase : Optional[int] =tokenizer_r.tokenize(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) # Test that the tokenization is identical on unicode of line break type UpperCAmelCase : int =[ '''\u000A''', # (line feed, '\n') '''\r\n''', # (carriage return and line feed, '\r\n') '''\u000D''', # (carriage return, '\r') '''\r''', # (carriage return, '\r') '''\u000D''', # (carriage return, '\r') '''\u2028''', # (line separator) '''\u2029''', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: UpperCAmelCase : str =tokenizer_s.tokenize(snake_case__ ) UpperCAmelCase : Tuple =tokenizer_r.tokenize(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) def UpperCAmelCase__ ( self ) -> List[str]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCAmelCase : Optional[Any] ='''hello''' # `hello` is a token in the vocabulary of `pretrained_name` UpperCAmelCase : str =f'''{text_of_1_token} {text_of_1_token}''' UpperCAmelCase : Dict =self.rust_tokenizer_class.from_pretrained( snake_case__ , use_fast=snake_case__ , ) UpperCAmelCase : Any =tokenizer_r(snake_case__ , return_offsets_mapping=snake_case__ , add_special_tokens=snake_case__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(snake_case__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(snake_case__ ) + 1, len(snake_case__ ) + 1 + len(snake_case__ )) , ) UpperCAmelCase : Any =f''' {text}''' UpperCAmelCase : str =self.rust_tokenizer_class.from_pretrained( snake_case__ , use_fast=snake_case__ , ) UpperCAmelCase : Optional[Any] =tokenizer_r(snake_case__ , return_offsets_mapping=snake_case__ , add_special_tokens=snake_case__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(snake_case__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(snake_case__ ) + 1, 1 + len(snake_case__ ) + 1 + len(snake_case__ )) , ) def UpperCAmelCase__ ( self ) -> str: '''simple docstring''' with self.assertRaises(snake_case__ ) as context: self.rust_tokenizer_class.from_pretrained('''robot-test/old-clip-tokenizer''' ) self.assertTrue( context.exception.args[0].startswith( '''The `backend_tokenizer` provided does not match the expected format.''' ) ) @require_ftfy def UpperCAmelCase__ ( self ) -> Any: '''simple docstring''' super().test_tokenization_python_rust_equals() def UpperCAmelCase__ ( self ) -> Dict: '''simple docstring''' pass
348
lowerCAmelCase_ = { "joule": 1.0, "kilojoule": 1_0_0_0, "megajoule": 1_0_0_0_0_0_0, "gigajoule": 1_0_0_0_0_0_0_0_0_0, "wattsecond": 1.0, "watthour": 3_6_0_0, "kilowatthour": 3_6_0_0_0_0_0, "newtonmeter": 1.0, "calorie_nutr": 4_1_8_6.8, "kilocalorie_nutr": 4_1_8_6_8_0_0.0_0, "electronvolt": 1.602_176_634e-19, "britishthermalunit_it": 1_0_5_5.0_5_5_8_5, "footpound": 1.355_818, } def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> float: """simple docstring""" if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: snake_case_ : str = ( f'''Incorrect \'from_type\' or \'to_type\' value: {from_type!r}, {to_type!r}\n''' f'''Valid values are: {", ".join(_UpperCamelCase )}''' ) raise ValueError(_UpperCamelCase ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
279
0
'''simple docstring''' import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() a__ : Union[str, Any] = logging.get_logger(__name__) def snake_case ( UpperCAmelCase )-> Dict: """simple docstring""" __A = SwinConfig.from_pretrained( 'microsoft/swin-tiny-patch4-window7-224' , out_features=['stage1', 'stage2', 'stage3', 'stage4'] ) __A = MaskFormerConfig(backbone_config=_UpperCamelCase ) __A = '''huggingface/label-files''' if "ade20k-full" in model_name: # this should be ok __A = 8_4_7 __A = '''maskformer-ade20k-full-id2label.json''' elif "ade" in model_name: # this should be ok __A = 1_5_0 __A = '''ade20k-id2label.json''' elif "coco-stuff" in model_name: # this should be ok __A = 1_7_1 __A = '''maskformer-coco-stuff-id2label.json''' elif "coco" in model_name: # TODO __A = 1_3_3 __A = '''coco-panoptic-id2label.json''' elif "cityscapes" in model_name: # this should be ok __A = 1_9 __A = '''cityscapes-id2label.json''' elif "vistas" in model_name: # this should be ok __A = 6_5 __A = '''mapillary-vistas-id2label.json''' __A = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type='dataset' ) , 'r' ) ) __A = {int(_UpperCamelCase ): v for k, v in idalabel.items()} return config def snake_case ( UpperCAmelCase )-> Optional[int]: """simple docstring""" __A = [] # stem # fmt: off rename_keys.append(('backbone.patch_embed.proj.weight', 'model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight') ) rename_keys.append(('backbone.patch_embed.proj.bias', 'model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias') ) rename_keys.append(('backbone.patch_embed.norm.weight', 'model.pixel_level_module.encoder.model.embeddings.norm.weight') ) rename_keys.append(('backbone.patch_embed.norm.bias', 'model.pixel_level_module.encoder.model.embeddings.norm.bias') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'backbone.layers.{i}.blocks.{j}.norm1.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.norm1.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.attn.relative_position_index', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.attn.proj.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.attn.proj.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.norm2.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.norm2.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.mlp.fc1.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.mlp.fc1.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.mlp.fc2.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight') ) rename_keys.append((f'backbone.layers.{i}.blocks.{j}.mlp.fc2.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias') ) if i < 3: rename_keys.append((f'backbone.layers.{i}.downsample.reduction.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight') ) rename_keys.append((f'backbone.layers.{i}.downsample.norm.weight', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight') ) rename_keys.append((f'backbone.layers.{i}.downsample.norm.bias', f'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias') ) rename_keys.append((f'backbone.norm{i}.weight', f'model.pixel_level_module.encoder.hidden_states_norms.{i}.weight') ) rename_keys.append((f'backbone.norm{i}.bias', f'model.pixel_level_module.encoder.hidden_states_norms.{i}.bias') ) # FPN rename_keys.append(('sem_seg_head.layer_4.weight', 'model.pixel_level_module.decoder.fpn.stem.0.weight') ) rename_keys.append(('sem_seg_head.layer_4.norm.weight', 'model.pixel_level_module.decoder.fpn.stem.1.weight') ) rename_keys.append(('sem_seg_head.layer_4.norm.bias', 'model.pixel_level_module.decoder.fpn.stem.1.bias') ) for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ): rename_keys.append((f'sem_seg_head.adapter_{source_index}.weight', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight') ) rename_keys.append((f'sem_seg_head.adapter_{source_index}.norm.weight', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight') ) rename_keys.append((f'sem_seg_head.adapter_{source_index}.norm.bias', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias') ) rename_keys.append((f'sem_seg_head.layer_{source_index}.weight', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight') ) rename_keys.append((f'sem_seg_head.layer_{source_index}.norm.weight', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight') ) rename_keys.append((f'sem_seg_head.layer_{source_index}.norm.bias', f'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias') ) rename_keys.append(('sem_seg_head.mask_features.weight', 'model.pixel_level_module.decoder.mask_projection.weight') ) rename_keys.append(('sem_seg_head.mask_features.bias', 'model.pixel_level_module.decoder.mask_projection.bias') ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight', f'model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias', f'model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias') ) # cross-attention out projection rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight', f'model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias', f'model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias') ) # MLP 1 rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight', f'model.transformer_module.decoder.layers.{idx}.fc1.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias', f'model.transformer_module.decoder.layers.{idx}.fc1.bias') ) # MLP 2 rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight', f'model.transformer_module.decoder.layers.{idx}.fc2.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias', f'model.transformer_module.decoder.layers.{idx}.fc2.bias') ) # layernorm 1 (self-attention layernorm) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight', f'model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias', f'model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias') ) # layernorm 2 (cross-attention layernorm) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight', f'model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias', f'model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias') ) # layernorm 3 (final layernorm) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight', f'model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight') ) rename_keys.append((f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias', f'model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias') ) rename_keys.append(('sem_seg_head.predictor.transformer.decoder.norm.weight', 'model.transformer_module.decoder.layernorm.weight') ) rename_keys.append(('sem_seg_head.predictor.transformer.decoder.norm.bias', 'model.transformer_module.decoder.layernorm.bias') ) # heads on top rename_keys.append(('sem_seg_head.predictor.query_embed.weight', 'model.transformer_module.queries_embedder.weight') ) rename_keys.append(('sem_seg_head.predictor.input_proj.weight', 'model.transformer_module.input_projection.weight') ) rename_keys.append(('sem_seg_head.predictor.input_proj.bias', 'model.transformer_module.input_projection.bias') ) rename_keys.append(('sem_seg_head.predictor.class_embed.weight', 'class_predictor.weight') ) rename_keys.append(('sem_seg_head.predictor.class_embed.bias', 'class_predictor.bias') ) for i in range(3 ): rename_keys.append((f'sem_seg_head.predictor.mask_embed.layers.{i}.weight', f'mask_embedder.{i}.0.weight') ) rename_keys.append((f'sem_seg_head.predictor.mask_embed.layers.{i}.bias', f'mask_embedder.{i}.0.bias') ) # fmt: on return rename_keys def snake_case ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )-> Union[str, Any]: """simple docstring""" __A = dct.pop(_UpperCamelCase ) __A = val def snake_case ( UpperCAmelCase , UpperCAmelCase )-> Any: """simple docstring""" __A = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): __A = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) __A = state_dict.pop(f'backbone.layers.{i}.blocks.{j}.attn.qkv.weight' ) __A = state_dict.pop(f'backbone.layers.{i}.blocks.{j}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict __A = in_proj_weight[:dim, :] __A = in_proj_bias[: dim] __A = in_proj_weight[ dim : dim * 2, : ] __A = in_proj_bias[ dim : dim * 2 ] __A = in_proj_weight[ -dim :, : ] __A = in_proj_bias[-dim :] # fmt: on def snake_case ( UpperCAmelCase , UpperCAmelCase )-> str: """simple docstring""" __A = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) __A = state_dict.pop(f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight' ) __A = state_dict.pop(f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict __A = in_proj_weight[: hidden_size, :] __A = in_proj_bias[:config.hidden_size] __A = in_proj_weight[hidden_size : hidden_size * 2, :] __A = in_proj_bias[hidden_size : hidden_size * 2] __A = in_proj_weight[-hidden_size :, :] __A = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) __A = state_dict.pop(f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight' ) __A = state_dict.pop(f'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict __A = in_proj_weight[: hidden_size, :] __A = in_proj_bias[:config.hidden_size] __A = in_proj_weight[hidden_size : hidden_size * 2, :] __A = in_proj_bias[hidden_size : hidden_size * 2] __A = in_proj_weight[-hidden_size :, :] __A = in_proj_bias[-hidden_size :] # fmt: on def snake_case ( )-> torch.Tensor: """simple docstring""" __A = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __A = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im @torch.no_grad() def snake_case ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = False )-> int: """simple docstring""" __A = get_maskformer_config(_UpperCamelCase ) # load original state_dict with open(_UpperCamelCase , 'rb' ) as f: __A = pickle.load(_UpperCamelCase ) __A = data['''model'''] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys __A = create_rename_keys(_UpperCamelCase ) for src, dest in rename_keys: rename_key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) read_in_swin_q_k_v(_UpperCamelCase , config.backbone_config ) read_in_decoder_q_k_v(_UpperCamelCase , _UpperCamelCase ) # update to torch tensors for key, value in state_dict.items(): __A = torch.from_numpy(_UpperCamelCase ) # load 🤗 model __A = MaskFormerForInstanceSegmentation(_UpperCamelCase ) model.eval() for name, param in model.named_parameters(): print(_UpperCamelCase , param.shape ) __A = model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(_UpperCamelCase ) == 0, f'Unexpected keys: {unexpected_keys}' # verify results __A = prepare_img() if "vistas" in model_name: __A = 6_5 elif "cityscapes" in model_name: __A = 6_5_5_3_5 else: __A = 2_5_5 __A = True if '''ade''' in model_name else False __A = MaskFormerImageProcessor(ignore_index=_UpperCamelCase , reduce_labels=_UpperCamelCase ) __A = image_processor(_UpperCamelCase , return_tensors='pt' ) __A = model(**_UpperCamelCase ) print('Logits:' , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": __A = torch.tensor( [[3.6353, -4.4770, -2.6065], [0.5081, -4.2394, -3.5343], [2.1909, -5.0353, -1.9323]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , _UpperCamelCase , atol=1e-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f'Saving model and image processor to {pytorch_dump_folder_path}' ) Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) model.save_pretrained(_UpperCamelCase ) image_processor.save_pretrained(_UpperCamelCase ) if push_to_hub: print('Pushing model and image processor to the hub...' ) model.push_to_hub(f'nielsr/{model_name}' ) image_processor.push_to_hub(f'nielsr/{model_name}' ) if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="maskformer-swin-tiny-ade", type=str, help=("Name of the MaskFormer model you\'d like to convert",), ) parser.add_argument( "--checkpoint_path", default="/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl", type=str, help="Path to the original state dict (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a__ : int = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
161
import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets lowerCAmelCase_ = datasets.logging.get_logger(__name__) lowerCAmelCase_ = '''\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } ''' lowerCAmelCase_ = '''\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project\'s README at https://github.com/google-research/bleurt#readme for more information. ''' lowerCAmelCase_ = ''' BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: \'scores\': List of scores. Examples: >>> predictions = ["hello there", "general kenobi"] >>> references = ["hello there", "general kenobi"] >>> bleurt = datasets.load_metric("bleurt") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results["scores"]]) [1.03, 1.04] ''' lowerCAmelCase_ = { '''bleurt-tiny-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip''', '''bleurt-tiny-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip''', '''bleurt-base-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip''', '''bleurt-base-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip''', '''bleurt-large-128''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip''', '''bleurt-large-512''': '''https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip''', '''BLEURT-20-D3''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip''', '''BLEURT-20-D6''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip''', '''BLEURT-20-D12''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip''', '''BLEURT-20''': '''https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip''', } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/google-research/bleurt''' , 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/bleurt'''] , reference_urls=['''https://github.com/google-research/bleurt''', '''https://arxiv.org/abs/2004.04696'''] , ) def lowerCamelCase (self , __magic_name__ ) -> List[Any]: '''simple docstring''' if self.config_name == "default": logger.warning( '''Using default BLEURT-Base checkpoint for sequence maximum length 128. ''' '''You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').''' ) snake_case_ : Dict = '''bleurt-base-128''' if self.config_name.lower() in CHECKPOINT_URLS: snake_case_ : Optional[int] = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: snake_case_ : Union[str, Any] = self.config_name.upper() else: raise KeyError( F'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}''' ) # download the model checkpoint specified by self.config_name and set up the scorer snake_case_ : Any = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) snake_case_ : Dict = score.BleurtScorer(os.path.join(__magic_name__ , __magic_name__ ) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Dict = self.scorer.score(references=__magic_name__ , candidates=__magic_name__ ) return {"scores": scores}
279
0
import fire from utils import calculate_rouge, save_json def _SCREAMING_SNAKE_CASE ( a , a , a=None , **a ) -> Dict: __A : Optional[int] = [x.strip() for x in open(a ).readlines()] __A : str = [x.strip() for x in open(a ).readlines()][: len(a )] __A : Tuple = calculate_rouge(a , a , **a ) if save_path is not None: save_json(a , a , indent=a ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
280
import argparse import json from tqdm import tqdm def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--src_path' , type=a , default='biencoder-nq-dev.json' , help='Path to raw DPR training data' , ) parser.add_argument( '--evaluation_set' , type=a , help='where to store parsed evaluation_set file' , ) parser.add_argument( '--gold_data_path' , type=a , help='where to store parsed gold_data_path file' , ) __A : Optional[int] = parser.parse_args() with open(args.src_path , 'r' ) as src_file, open(args.evaluation_set , 'w' ) as eval_file, open( args.gold_data_path , 'w' ) as gold_file: __A : List[Any] = json.load(a ) for dpr_record in tqdm(a ): __A : Dict = dpr_record['question'] __A : Any = [context['title'] for context in dpr_record['positive_ctxs']] eval_file.write(question + '\n' ) gold_file.write('\t'.join(a ) + '\n' ) if __name__ == "__main__": main()
280
1