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
'''simple docstring''' import warnings from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging lowerCamelCase : List[str] = logging.get_logger(__name__) lowerCamelCase : Any = { """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/config.json""", # See all BART models at https://huggingface.co/models?filter=bart } class A__ ( UpperCAmelCase__ ): A__ = 'bart' A__ = ['past_key_values'] A__ = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : int , _a : Any=5_0265 , _a : List[str]=1024 , _a : List[Any]=12 , _a : str=4096 , _a : int=16 , _a : Optional[Any]=12 , _a : List[str]=4096 , _a : Optional[Any]=16 , _a : Optional[int]=0.0 , _a : Union[str, Any]=0.0 , _a : Optional[Any]="gelu" , _a : int=1024 , _a : Any=0.1 , _a : Dict=0.0 , _a : Any=0.0 , _a : Union[str, Any]=0.02 , _a : Tuple=0.0 , _a : Tuple=False , _a : str=True , _a : Optional[int]=3 , _a : Optional[int]=1 , _a : Dict=0 , _a : Tuple=2 , _a : Union[str, Any]=True , _a : Dict=2 , _a : Dict=2 , **_a : int , ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =vocab_size _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =decoder_layerdrop _SCREAMING_SNAKE_CASE =classifier_dropout _SCREAMING_SNAKE_CASE =use_cache _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( num_labels=lowercase_ , pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , is_encoder_decoder=lowercase_ , decoder_start_token_id=lowercase_ , forced_eos_token_id=lowercase_ , **lowercase_ , ) # ensure backward compatibility for BART CNN models if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , lowercase_ ): _SCREAMING_SNAKE_CASE =self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " 'The config can simply be saved and uploaded again to be fixed.' ) class A__ ( UpperCAmelCase__ ): @property def A ( self : List[Any] ) -> List[str]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: _SCREAMING_SNAKE_CASE =OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: _SCREAMING_SNAKE_CASE ={0: '''batch'''} _SCREAMING_SNAKE_CASE ={0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: _SCREAMING_SNAKE_CASE ={0: '''batch''', 1: '''decoder_sequence'''} _SCREAMING_SNAKE_CASE ={0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(lowercase_ , direction='inputs' ) elif self.task == "causal-lm": # TODO: figure this case out. _SCREAMING_SNAKE_CASE =OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ] ) if self.use_past: _SCREAMING_SNAKE_CASE =self.num_layers for i in range(lowercase_ ): _SCREAMING_SNAKE_CASE ={0: '''batch''', 2: '''past_sequence + sequence'''} _SCREAMING_SNAKE_CASE ={0: '''batch''', 2: '''past_sequence + sequence'''} else: _SCREAMING_SNAKE_CASE =OrderedDict( [ ('input_ids', {0: 'batch', 1: 'encoder_sequence'}), ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}), ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}), ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}), ] ) return common_inputs @property def A ( self : Dict ) -> List[Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: _SCREAMING_SNAKE_CASE =super().outputs else: _SCREAMING_SNAKE_CASE =super(lowercase_ , self ).outputs if self.use_past: _SCREAMING_SNAKE_CASE =self.num_layers for i in range(lowercase_ ): _SCREAMING_SNAKE_CASE ={0: '''batch''', 2: '''past_sequence + sequence'''} _SCREAMING_SNAKE_CASE ={0: '''batch''', 2: '''past_sequence + sequence'''} return common_outputs def A ( self : Any , _a : PreTrainedTokenizer , _a : int = -1 , _a : int = -1 , _a : bool = False , _a : Optional[TensorType] = None , ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # Generate decoder inputs _SCREAMING_SNAKE_CASE =seq_length if not self.use_past else 1 _SCREAMING_SNAKE_CASE =self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) _SCREAMING_SNAKE_CASE ={f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} _SCREAMING_SNAKE_CASE =dict(**lowercase_ , **lowercase_ ) if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch _SCREAMING_SNAKE_CASE =common_inputs['''input_ids'''].shape _SCREAMING_SNAKE_CASE =common_inputs['''decoder_input_ids'''].shape[1] _SCREAMING_SNAKE_CASE =self.num_attention_heads _SCREAMING_SNAKE_CASE =( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) _SCREAMING_SNAKE_CASE =decoder_seq_length + 3 _SCREAMING_SNAKE_CASE =( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) _SCREAMING_SNAKE_CASE =torch.cat( [common_inputs['decoder_attention_mask'], torch.ones(lowercase_ , lowercase_ )] , dim=1 ) _SCREAMING_SNAKE_CASE =[] # If the number of encoder and decoder layers are present in the model configuration, both are considered _SCREAMING_SNAKE_CASE =self.num_layers _SCREAMING_SNAKE_CASE =min(lowercase_ , lowercase_ ) _SCREAMING_SNAKE_CASE =max(lowercase_ , lowercase_ ) - min_num_layers _SCREAMING_SNAKE_CASE ='''encoder''' if num_encoder_layers > num_decoder_layers else '''decoder''' for _ in range(lowercase_ ): common_inputs["past_key_values"].append( ( torch.zeros(lowercase_ ), torch.zeros(lowercase_ ), torch.zeros(lowercase_ ), torch.zeros(lowercase_ ), ) ) # TODO: test this. _SCREAMING_SNAKE_CASE =encoder_shape if remaining_side_name == '''encoder''' else decoder_shape for _ in range(lowercase_ , lowercase_ ): common_inputs["past_key_values"].append((torch.zeros(lowercase_ ), torch.zeros(lowercase_ )) ) return common_inputs def A ( self : Optional[Any] , _a : PreTrainedTokenizer , _a : int = -1 , _a : int = -1 , _a : bool = False , _a : Optional[TensorType] = None , ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch _SCREAMING_SNAKE_CASE =common_inputs['''input_ids'''].shape # Not using the same length for past_key_values _SCREAMING_SNAKE_CASE =seqlen + 2 _SCREAMING_SNAKE_CASE =self.num_layers _SCREAMING_SNAKE_CASE =self.num_attention_heads _SCREAMING_SNAKE_CASE =( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) _SCREAMING_SNAKE_CASE =common_inputs['''attention_mask'''].dtype _SCREAMING_SNAKE_CASE =torch.cat( [common_inputs['attention_mask'], torch.ones(lowercase_ , lowercase_ , dtype=lowercase_ )] , dim=1 ) _SCREAMING_SNAKE_CASE =[ (torch.zeros(lowercase_ ), torch.zeros(lowercase_ )) for _ in range(lowercase_ ) ] return common_inputs def A ( self : int , _a : PreTrainedTokenizer , _a : int = -1 , _a : int = -1 , _a : bool = False , _a : Optional[TensorType] = None , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =compute_effective_axis_dimension( lowercase_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX _SCREAMING_SNAKE_CASE =tokenizer.num_special_tokens_to_add(lowercase_ ) _SCREAMING_SNAKE_CASE =compute_effective_axis_dimension( lowercase_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowercase_ ) # Generate dummy inputs according to compute batch and sequence _SCREAMING_SNAKE_CASE =[''' '''.join([tokenizer.unk_token] ) * seq_length] * batch_size _SCREAMING_SNAKE_CASE =dict(tokenizer(lowercase_ , return_tensors=lowercase_ ) ) return common_inputs def A ( self : List[str] , _a : PreTrainedTokenizer , _a : int = -1 , _a : int = -1 , _a : bool = False , _a : Optional[TensorType] = None , ) -> List[Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: _SCREAMING_SNAKE_CASE =self._generate_dummy_inputs_for_default_and_seqaseq_lm( lowercase_ , batch_size=lowercase_ , seq_length=lowercase_ , is_pair=lowercase_ , framework=lowercase_ ) elif self.task == "causal-lm": _SCREAMING_SNAKE_CASE =self._generate_dummy_inputs_for_causal_lm( lowercase_ , batch_size=lowercase_ , seq_length=lowercase_ , is_pair=lowercase_ , framework=lowercase_ ) else: _SCREAMING_SNAKE_CASE =self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowercase_ , batch_size=lowercase_ , seq_length=lowercase_ , is_pair=lowercase_ , framework=lowercase_ ) return common_inputs def A ( self : Dict , _a : str , _a : int , _a : Tuple , _a : str ) -> Optional[int]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: _SCREAMING_SNAKE_CASE =super()._flatten_past_key_values_(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) else: _SCREAMING_SNAKE_CASE =super(lowercase_ , self )._flatten_past_key_values_( lowercase_ , lowercase_ , lowercase_ , lowercase_ )
47
"""simple docstring""" import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py UpperCAmelCase_ : Optional[int] = """src/transformers""" UpperCAmelCase_ : Tuple = """docs/source/en""" UpperCAmelCase_ : Optional[Any] = """.""" def _A (__a , __a , __a ) -> Dict: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE_ : List[Any] = 0 while not lines[start_index].startswith(__a ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Tuple = start_index while not lines[end_index].startswith(__a ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCAmelCase_ : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. UpperCAmelCase_ : int = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") UpperCAmelCase_ : Dict = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCAmelCase_ : int = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase_ : Optional[int] = direct_transformers_import(TRANSFORMERS_PATH) def _A (__a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __a ) return [m.group(0 ) for m in matches] def _A (__a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 2 if text == '''✅''' or text == '''❌''' else len(__a ) SCREAMING_SNAKE_CASE_ : Tuple = (width - text_length) // 2 SCREAMING_SNAKE_CASE_ : Tuple = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ : Tuple = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } SCREAMING_SNAKE_CASE_ : List[Any] = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) # Let's lookup through all transformers object (once). for attr_name in dir(__a ): SCREAMING_SNAKE_CASE_ : Any = None if attr_name.endswith('''Tokenizer''' ): SCREAMING_SNAKE_CASE_ : Dict = slow_tokenizers SCREAMING_SNAKE_CASE_ : Dict = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = fast_tokenizers SCREAMING_SNAKE_CASE_ : Optional[Any] = attr_name[:-13] elif _re_tf_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : int = tf_models SCREAMING_SNAKE_CASE_ : Dict = _re_tf_models.match(__a ).groups()[0] elif _re_flax_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : Any = flax_models SCREAMING_SNAKE_CASE_ : Tuple = _re_flax_models.match(__a ).groups()[0] elif _re_pt_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : str = pt_models SCREAMING_SNAKE_CASE_ : int = _re_pt_models.match(__a ).groups()[0] if lookup_dict is not None: while len(__a ) > 0: if attr_name in model_name_to_prefix.values(): SCREAMING_SNAKE_CASE_ : List[str] = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(camel_case_split(__a )[:-1] ) # Let's build that table! SCREAMING_SNAKE_CASE_ : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) SCREAMING_SNAKE_CASE_ : Any = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). SCREAMING_SNAKE_CASE_ : List[str] = [len(__a ) + 2 for c in columns] SCREAMING_SNAKE_CASE_ : str = max([len(__a ) for name in model_names] ) + 2 # Build the table per se SCREAMING_SNAKE_CASE_ : List[Any] = '''|''' + '''|'''.join([_center_text(__a , __a ) for c, w in zip(__a , __a )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" SCREAMING_SNAKE_CASE_ : Union[str, Any] = {True: '''✅''', False: '''❌'''} for name in model_names: SCREAMING_SNAKE_CASE_ : str = model_name_to_prefix[name] SCREAMING_SNAKE_CASE_ : int = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__a , __a ) for l, w in zip(__a , __a )] ) + "|\n" return table def _A (__a=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = _find_text_in_file( filename=os.path.join(__a , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) SCREAMING_SNAKE_CASE_ : Tuple = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__a , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
91
0
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _UpperCAmelCase : Any = logging.get_logger(__name__) _UpperCAmelCase : List[str] = """▁""" _UpperCAmelCase : Tuple = { """vocab_file""": """vocab.json""", """spm_file""": """sentencepiece.bpe.model""", """tokenizer_config_file""": """tokenizer_config.json""", } _UpperCAmelCase : Optional[Any] = { """vocab_file""": { """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json""", """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json""", }, """spm_file""": { """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model""", """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model""", }, """tokenizer_config_file""": { """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json""", """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json""", }, } _UpperCAmelCase : Tuple = { """facebook/m2m100_418M""": 1_024, } # fmt: off _UpperCAmelCase : Optional[Any] = { """m2m100""": ["""af""", """am""", """ar""", """ast""", """az""", """ba""", """be""", """bg""", """bn""", """br""", """bs""", """ca""", """ceb""", """cs""", """cy""", """da""", """de""", """el""", """en""", """es""", """et""", """fa""", """ff""", """fi""", """fr""", """fy""", """ga""", """gd""", """gl""", """gu""", """ha""", """he""", """hi""", """hr""", """ht""", """hu""", """hy""", """id""", """ig""", """ilo""", """is""", """it""", """ja""", """jv""", """ka""", """kk""", """km""", """kn""", """ko""", """lb""", """lg""", """ln""", """lo""", """lt""", """lv""", """mg""", """mk""", """ml""", """mn""", """mr""", """ms""", """my""", """ne""", """nl""", """no""", """ns""", """oc""", """or""", """pa""", """pl""", """ps""", """pt""", """ro""", """ru""", """sd""", """si""", """sk""", """sl""", """so""", """sq""", """sr""", """ss""", """su""", """sv""", """sw""", """ta""", """th""", """tl""", """tn""", """tr""", """uk""", """ur""", """uz""", """vi""", """wo""", """xh""", """yi""", """yo""", """zh""", """zu"""], """wmt21""": ["""en""", """ha""", """is""", """ja""", """cs""", """ru""", """zh""", """de"""] } class lowercase ( UpperCAmelCase__ ): __lowercase : int = VOCAB_FILES_NAMES __lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase : Dict = PRETRAINED_VOCAB_FILES_MAP __lowercase : List[Any] = ["input_ids", "attention_mask"] __lowercase : Union[str, Any] = [] __lowercase : int = [] def __init__( self , A_ , A_ , A_=None , A_=None , A_="<s>" , A_="</s>" , A_="</s>" , A_="<pad>" , A_="<unk>" , A_="m2m100" , A_ = None , A_=8 , **A_ , ) -> str: """simple docstring""" UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs UpperCamelCase = language_codes UpperCamelCase = FAIRSEQ_LANGUAGE_CODES[language_codes] UpperCamelCase = {lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} UpperCamelCase = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(lowercase_ ) for lang_code in fairseq_language_code if self.get_lang_token(lowercase_ ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=lowercase_ , tgt_lang=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , sep_token=lowercase_ , unk_token=lowercase_ , pad_token=lowercase_ , language_codes=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=lowercase_ , **lowercase_ , ) UpperCamelCase = vocab_file UpperCamelCase = load_json(lowercase_ ) UpperCamelCase = {v: k for k, v in self.encoder.items()} UpperCamelCase = spm_file UpperCamelCase = load_spm(lowercase_ , self.sp_model_kwargs ) UpperCamelCase = len(self.encoder ) UpperCamelCase = { self.get_lang_token(lowercase_ ): self.encoder_size + i for i, lang_code in enumerate(lowercase_ ) } UpperCamelCase = {lang_code: self.encoder_size + i for i, lang_code in enumerate(lowercase_ )} UpperCamelCase = {v: k for k, v in self.lang_token_to_id.items()} UpperCamelCase = src_lang if src_lang is not None else '''en''' UpperCamelCase = tgt_lang UpperCamelCase = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) UpperCamelCase = num_madeup_words @property def __UpperCamelCase ( self ) -> Optional[int]: """simple docstring""" return len(self.encoder ) + len(self.lang_token_to_id ) @property def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" return self._src_lang @src_lang.setter def __UpperCamelCase ( self , A_ ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __UpperCamelCase ( self , A_ ) -> List[str]: """simple docstring""" return self.sp_model.encode(lowercase_ , out_type=lowercase_ ) def __UpperCamelCase ( self , A_ ) -> Optional[Any]: """simple docstring""" if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(lowercase_ , self.encoder[self.unk_token] ) def __UpperCamelCase ( self , A_ ) -> Optional[Any]: """simple docstring""" if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(lowercase_ , self.unk_token ) def __UpperCamelCase ( self , A_ ) -> List[str]: """simple docstring""" UpperCamelCase = [] UpperCamelCase = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(lowercase_ ) + token UpperCamelCase = [] else: current_sub_tokens.append(lowercase_ ) out_string += self.sp_model.decode(lowercase_ ) return out_string.strip() def __UpperCamelCase ( self , A_ , A_ = None , A_ = False ) -> Optional[int]: """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_ ) UpperCamelCase = [1] * len(self.prefix_tokens ) UpperCamelCase = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(lowercase_ )) + suffix_ones return prefix_ones + ([0] * len(lowercase_ )) + ([0] * len(lowercase_ )) + suffix_ones def __UpperCamelCase ( self , A_ , A_ = None ) -> Any: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = {self.convert_ids_to_tokens(lowercase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> str: """simple docstring""" UpperCamelCase = self.__dict__.copy() UpperCamelCase = None return state def __setstate__( self , A_ ) -> int: """simple docstring""" UpperCamelCase = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): UpperCamelCase = {} UpperCamelCase = load_spm(self.spm_file , self.sp_model_kwargs ) def __UpperCamelCase ( self , A_ , A_ = None ) -> Any: """simple docstring""" UpperCamelCase = Path(lowercase_ ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) UpperCamelCase = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) UpperCamelCase = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , lowercase_ ) if os.path.abspath(self.spm_file ) != os.path.abspath(lowercase_ ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , lowercase_ ) elif not os.path.isfile(self.spm_file ): with open(lowercase_ , 'wb' ) as fi: UpperCamelCase = self.sp_model.serialized_model_proto() fi.write(lowercase_ ) return (str(lowercase_ ), str(lowercase_ )) def __UpperCamelCase ( self , A_ , A_ = "en" , A_ = None , A_ = "ro" , **A_ , ) -> Dict: """simple docstring""" UpperCamelCase = src_lang UpperCamelCase = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(lowercase_ , lowercase_ , **lowercase_ ) def __UpperCamelCase ( self , A_ , A_ , A_ , **A_ ) -> Union[str, Any]: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) UpperCamelCase = src_lang UpperCamelCase = self(lowercase_ , add_special_tokens=lowercase_ , **lowercase_ ) UpperCamelCase = self.get_lang_id(lowercase_ ) UpperCamelCase = tgt_lang_id return inputs def __UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" self.set_src_lang_special_tokens(self.src_lang ) def __UpperCamelCase ( self ) -> Tuple: """simple docstring""" self.set_tgt_lang_special_tokens(self.tgt_lang ) def __UpperCamelCase ( self , A_ ) -> Optional[int]: """simple docstring""" UpperCamelCase = self.get_lang_token(lowercase_ ) UpperCamelCase = self.lang_token_to_id[lang_token] UpperCamelCase = [self.cur_lang_id] UpperCamelCase = [self.eos_token_id] def __UpperCamelCase ( self , A_ ) -> Any: """simple docstring""" UpperCamelCase = self.get_lang_token(lowercase_ ) UpperCamelCase = self.lang_token_to_id[lang_token] UpperCamelCase = [self.cur_lang_id] UpperCamelCase = [self.eos_token_id] def __UpperCamelCase ( self , A_ ) -> int: """simple docstring""" return self.lang_code_to_token[lang] def __UpperCamelCase ( self , A_ ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self.get_lang_token(lowercase_ ) return self.lang_token_to_id[lang_token] def A ( lowercase , lowercase ) -> sentencepiece.SentencePieceProcessor: '''simple docstring''' UpperCamelCase = sentencepiece.SentencePieceProcessor(**__a ) spm.Load(str(__a ) ) return spm def A ( lowercase ) -> Union[Dict, List]: '''simple docstring''' with open(__a , 'r' ) as f: return json.load(__a ) def A ( lowercase , lowercase ) -> None: '''simple docstring''' with open(__a , 'w' ) as f: json.dump(__a , __a , indent=2 )
222
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : List[str]=13 , lowercase_ : int=7 , lowercase_ : Any=True , lowercase_ : str=True , lowercase_ : List[Any]=True , lowercase_ : List[Any]=True , lowercase_ : Dict=99 , lowercase_ : Union[str, Any]=24 , lowercase_ : int=2 , lowercase_ : List[str]=6 , lowercase_ : Any=37 , lowercase_ : Dict="gelu" , lowercase_ : List[str]=0.1 , lowercase_ : Dict=0.1 , lowercase_ : Union[str, Any]=512 , lowercase_ : List[str]=16 , lowercase_ : Any=2 , lowercase_ : Any=0.02 , lowercase_ : List[Any]=3 , lowercase_ : Optional[int]=None , lowercase_ : str=1000 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE_ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE_ : Tuple = scope SCREAMING_SNAKE_CASE_ : Optional[int] = range_bbox def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : str = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[str] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : List[str] = t SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : Any = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LiltConfig( 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 , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = LiltModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = model(lowercase_ , bbox=lowercase_) 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 _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = LiltForTokenClassification(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LiltForQuestionAnswering(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) 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 _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : str , lowercase_ : str): '''simple docstring''' return True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = LiltModelTester(self) SCREAMING_SNAKE_CASE_ : Optional[int] = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : Dict = type self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[int] = LiltModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''').to(lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.tensor([[1, 2]] , device=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Dict = model(input_ids=lowercase_ , bbox=lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.Size([1, 2, 768]) SCREAMING_SNAKE_CASE_ : Dict = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=lowercase_ , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase_) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase_ , atol=1e-3))
91
0
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): """simple docstring""" lowercase__ = (DDIMParallelScheduler,) lowercase__ = (("eta", 0.0), ("num_inference_steps", 50)) def __lowerCAmelCase ( self : Union[str, Any] ,**lowercase_ : Optional[int] ): lowerCAmelCase__ : Any = { '''num_train_timesteps''': 1_0_0_0, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**lowercase_ ) return config def __lowerCAmelCase ( self : str ,**lowercase_ : Optional[Any] ): lowerCAmelCase__ : Tuple = self.scheduler_classes[0] lowerCAmelCase__ : str = self.get_scheduler_config(**lowercase_ ) lowerCAmelCase__ : Union[str, Any] = scheduler_class(**lowercase_ ) lowerCAmelCase__ : int = 1_0, 0.0 lowerCAmelCase__ : List[Any] = self.dummy_model() lowerCAmelCase__ : Tuple = self.dummy_sample_deter scheduler.set_timesteps(lowercase_ ) for t in scheduler.timesteps: lowerCAmelCase__ : Union[str, Any] = model(lowercase_ ,lowercase_ ) lowerCAmelCase__ : Any = scheduler.step(lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ).prev_sample return sample def __lowerCAmelCase ( self : str ): for timesteps in [1_0_0, 5_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=lowercase_ ) def __lowerCAmelCase ( self : Optional[int] ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_ ) lowerCAmelCase__ : Tuple = self.scheduler_classes[0] lowerCAmelCase__ : List[Any] = self.get_scheduler_config(steps_offset=1 ) lowerCAmelCase__ : Optional[int] = scheduler_class(**lowercase_ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps ,torch.LongTensor([8_0_1, 6_0_1, 4_0_1, 2_0_1, 1] ) ) def __lowerCAmelCase ( self : List[Any] ): for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] ,[0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowercase_ ,beta_end=lowercase_ ) def __lowerCAmelCase ( self : Dict ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_ ) def __lowerCAmelCase ( self : str ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_ ) def __lowerCAmelCase ( self : int ): for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowercase_ ) def __lowerCAmelCase ( self : List[Any] ): for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=lowercase_ ) def __lowerCAmelCase ( self : Tuple ): for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=lowercase_ ) def __lowerCAmelCase ( self : Optional[int] ): self.check_over_configs(thresholding=lowercase_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=lowercase_ ,prediction_type=lowercase_ ,sample_max_value=lowercase_ ,) def __lowerCAmelCase ( self : Optional[int] ): for t in [1, 1_0, 4_9]: self.check_over_forward(time_step=lowercase_ ) def __lowerCAmelCase ( self : str ): for t, num_inference_steps in zip([1, 1_0, 5_0] ,[1_0, 5_0, 5_0_0] ): self.check_over_forward(time_step=lowercase_ ,num_inference_steps=lowercase_ ) def __lowerCAmelCase ( self : Tuple ): for t, eta in zip([1, 1_0, 4_9] ,[0.0, 0.5, 1.0] ): self.check_over_forward(time_step=lowercase_ ,eta=lowercase_ ) def __lowerCAmelCase ( self : List[Any] ): lowerCAmelCase__ : str = self.scheduler_classes[0] lowerCAmelCase__ : Union[str, Any] = self.get_scheduler_config() lowerCAmelCase__ : List[Any] = scheduler_class(**lowercase_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ,0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_2_0 ,4_0_0 ) - 0.1_4771 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_8_0 ,9_6_0 ) - 0.3_2460 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(0 ,0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ,4_8_6 ) - 0.0_0979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ,9_9_8 ) - 0.02 ) ) < 1E-5 def __lowerCAmelCase ( self : Optional[int] ): lowerCAmelCase__ : List[str] = self.scheduler_classes[0] lowerCAmelCase__ : Optional[Any] = self.get_scheduler_config() lowerCAmelCase__ : Optional[Any] = scheduler_class(**lowercase_ ) lowerCAmelCase__ : Dict = 1_0, 0.0 scheduler.set_timesteps(lowercase_ ) lowerCAmelCase__ : Any = self.dummy_model() lowerCAmelCase__ : Optional[int] = self.dummy_sample_deter lowerCAmelCase__ : Tuple = self.dummy_sample_deter + 0.1 lowerCAmelCase__ : List[Any] = self.dummy_sample_deter - 0.1 lowerCAmelCase__ : Dict = samplea.shape[0] lowerCAmelCase__ : Optional[int] = torch.stack([samplea, samplea, samplea] ,dim=0 ) lowerCAmelCase__ : List[Any] = torch.arange(lowercase_ )[0:3, None].repeat(1 ,lowercase_ ) lowerCAmelCase__ : str = model(samples.flatten(0 ,1 ) ,timesteps.flatten(0 ,1 ) ) lowerCAmelCase__ : Any = scheduler.batch_step_no_noise(lowercase_ ,timesteps.flatten(0 ,1 ) ,samples.flatten(0 ,1 ) ,lowercase_ ) lowerCAmelCase__ : Optional[int] = torch.sum(torch.abs(lowercase_ ) ) lowerCAmelCase__ : int = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_1_4_7.7_9_0_4 ) < 1E-2 assert abs(result_mean.item() - 0.4982 ) < 1E-3 def __lowerCAmelCase ( self : Optional[int] ): lowerCAmelCase__ : str = self.full_loop() lowerCAmelCase__ : Dict = torch.sum(torch.abs(lowercase_ ) ) lowerCAmelCase__ : int = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_7_2.0_0_6_7 ) < 1E-2 assert abs(result_mean.item() - 0.22_3967 ) < 1E-3 def __lowerCAmelCase ( self : Optional[int] ): lowerCAmelCase__ : str = self.full_loop(prediction_type='''v_prediction''' ) lowerCAmelCase__ : Dict = torch.sum(torch.abs(lowercase_ ) ) lowerCAmelCase__ : List[str] = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 52.5302 ) < 1E-2 assert abs(result_mean.item() - 0.0684 ) < 1E-3 def __lowerCAmelCase ( self : Optional[Any] ): lowerCAmelCase__ : int = self.full_loop(set_alpha_to_one=lowercase_ ,beta_start=0.01 ) lowerCAmelCase__ : List[str] = torch.sum(torch.abs(lowercase_ ) ) lowerCAmelCase__ : int = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_4_9.8_2_9_5 ) < 1E-2 assert abs(result_mean.item() - 0.1951 ) < 1E-3 def __lowerCAmelCase ( self : str ): lowerCAmelCase__ : Tuple = self.full_loop(set_alpha_to_one=lowercase_ ,beta_start=0.01 ) lowerCAmelCase__ : Optional[int] = torch.sum(torch.abs(lowercase_ ) ) lowerCAmelCase__ : Optional[Any] = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_4_9.0_7_8_4 ) < 1E-2 assert abs(result_mean.item() - 0.1941 ) < 1E-3
106
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCAmelCase_ : Dict = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) UpperCAmelCase_ : Optional[Any] = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: UpperCAmelCase_ : Union[str, Any] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") UpperCAmelCase_ : Any = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase_ : List[Any] = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase_ : Dict = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
91
0
"""simple docstring""" from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class A_ (UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = """openai/whisper-base""" SCREAMING_SNAKE_CASE__ : int = ( """This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """ """transcribed text.""" ) SCREAMING_SNAKE_CASE__ : Dict = """transcriber""" SCREAMING_SNAKE_CASE__ : Dict = WhisperProcessor SCREAMING_SNAKE_CASE__ : List[str] = WhisperForConditionalGeneration SCREAMING_SNAKE_CASE__ : Dict = ["""audio"""] SCREAMING_SNAKE_CASE__ : Optional[int] = ["""text"""] def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" return self.pre_processor(lowercase_ , return_tensors="pt" ).input_features def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" return self.model.generate(inputs=lowercase_ ) def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" return self.pre_processor.batch_decode(lowercase_ , skip_special_tokens=lowercase_ )[0]
61
"""simple docstring""" from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) def _A (__a , __a ) -> Tuple: """simple docstring""" try: with open(__a , '''rb''' ) as flax_state_f: SCREAMING_SNAKE_CASE_ : Optional[int] = from_bytes(__a , flax_state_f.read() ) except UnpicklingError as e: try: with open(__a ) as f: if f.read().startswith('''version''' ): raise OSError( '''You seem to have cloned a repository without having git-lfs installed. Please''' ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the''' ''' folder you cloned.''' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(__a , __a ) def _A (__a , __a ) -> Tuple: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE_ : Optional[int] = flatten_dict(jax.tree_util.tree_map(lambda __a : x.dtype == jnp.bfloataa , __a ) ).values() if any(__a ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.tree_util.tree_map( lambda __a : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , __a ) SCREAMING_SNAKE_CASE_ : int = '''''' SCREAMING_SNAKE_CASE_ : str = flatten_dict(__a , sep='''.''' ) SCREAMING_SNAKE_CASE_ : List[Any] = pt_model.state_dict() # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Any = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple.split('''.''' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.transpose(__a , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": SCREAMING_SNAKE_CASE_ : Tuple = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[int] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": SCREAMING_SNAKE_CASE_ : Optional[int] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(__a ): SCREAMING_SNAKE_CASE_ : List[str] = ( flax_key_tuple_string.replace('''_0''' , '''.0''' ) .replace('''_1''' , '''.1''' ) .replace('''_2''' , '''.2''' ) .replace('''_3''' , '''.3''' ) .replace('''_4''' , '''.4''' ) .replace('''_5''' , '''.5''' ) .replace('''_6''' , '''.6''' ) .replace('''_7''' , '''.7''' ) .replace('''_8''' , '''.8''' ) .replace('''_9''' , '''.9''' ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = '''.'''.join(__a ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE_ : Optional[int] = np.asarray(__a ) if not isinstance(__a , np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.from_numpy(__a ) # remove from missing keys missing_keys.remove(__a ) else: # weight is not expected by PyTorch model unexpected_keys.append(__a ) pt_model.load_state_dict(__a ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE_ : int = list(__a ) if len(__a ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) if len(__a ) > 0: logger.warning( f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) return pt_model
91
0
import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) _lowerCamelCase : List[str] = logging.getLogger(__name__) def a_ ( ) -> Optional[int]: _snake_case = argparse.ArgumentParser( description='Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).' ) parser.add_argument('--file_path' , type=__a , default='data/dump.txt' , help='The path to the data.' ) parser.add_argument('--tokenizer_type' , type=__a , default='bert' , choices=['bert', 'roberta', 'gpt2'] ) parser.add_argument('--tokenizer_name' , type=__a , default='bert-base-uncased' , help='The tokenizer to use.' ) parser.add_argument('--dump_file' , type=__a , default='data/dump' , help='The dump file prefix.' ) _snake_case = parser.parse_args() logger.info(f'''Loading Tokenizer ({args.tokenizer_name})''' ) if args.tokenizer_type == "bert": _snake_case = BertTokenizer.from_pretrained(args.tokenizer_name ) _snake_case = tokenizer.special_tokens_map['''cls_token'''] # `[CLS]` _snake_case = tokenizer.special_tokens_map['''sep_token'''] # `[SEP]` elif args.tokenizer_type == "roberta": _snake_case = RobertaTokenizer.from_pretrained(args.tokenizer_name ) _snake_case = tokenizer.special_tokens_map['''cls_token'''] # `<s>` _snake_case = tokenizer.special_tokens_map['''sep_token'''] # `</s>` elif args.tokenizer_type == "gpt2": _snake_case = GPTaTokenizer.from_pretrained(args.tokenizer_name ) _snake_case = tokenizer.special_tokens_map['''bos_token'''] # `<|endoftext|>` _snake_case = tokenizer.special_tokens_map['''eos_token'''] # `<|endoftext|>` logger.info(f'''Loading text from {args.file_path}''' ) with open(args.file_path , 'r' , encoding='utf8' ) as fp: _snake_case = fp.readlines() logger.info('Start encoding' ) logger.info(f'''{len(__a )} examples to process.''' ) _snake_case = [] _snake_case = 0 _snake_case = 10_000 _snake_case = time.time() for text in data: _snake_case = f'''{bos} {text.strip()} {sep}''' _snake_case = tokenizer.encode(__a , add_special_tokens=__a ) rslt.append(__a ) iter += 1 if iter % interval == 0: _snake_case = time.time() logger.info(f'''{iter} examples processed. - {(end-start):.2f}s/{interval}expl''' ) _snake_case = time.time() logger.info('Finished binarization' ) logger.info(f'''{len(__a )} examples processed.''' ) _snake_case = f'''{args.dump_file}.{args.tokenizer_name}.pickle''' _snake_case = tokenizer.vocab_size if vocab_size < (1 << 16): _snake_case = [np.uintaa(__a ) for d in rslt] else: _snake_case = [np.intaa(__a ) for d in rslt] random.shuffle(rslt_ ) logger.info(f'''Dump to {dp_file}''' ) with open(__a , 'wb' ) as handle: pickle.dump(rslt_ , __a , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
282
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "openai-gpt" __UpperCamelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , lowercase_ : List[str]=40478 , lowercase_ : List[str]=512 , lowercase_ : Optional[Any]=768 , lowercase_ : Tuple=12 , lowercase_ : Tuple=12 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : List[Any]=0.1 , lowercase_ : Tuple=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : List[Any]=1e-5 , lowercase_ : int=0.02 , lowercase_ : Optional[int]="cls_index" , lowercase_ : Any=True , lowercase_ : List[Any]=None , lowercase_ : List[str]=True , lowercase_ : Optional[Any]=0.1 , **lowercase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE_ : Tuple = n_positions SCREAMING_SNAKE_CASE_ : Optional[int] = n_embd SCREAMING_SNAKE_CASE_ : Dict = n_layer SCREAMING_SNAKE_CASE_ : Any = n_head SCREAMING_SNAKE_CASE_ : Union[str, Any] = afn SCREAMING_SNAKE_CASE_ : int = resid_pdrop SCREAMING_SNAKE_CASE_ : List[str] = embd_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = attn_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = summary_type SCREAMING_SNAKE_CASE_ : Tuple = summary_use_proj SCREAMING_SNAKE_CASE_ : Union[str, Any] = summary_activation SCREAMING_SNAKE_CASE_ : Any = summary_first_dropout SCREAMING_SNAKE_CASE_ : List[str] = summary_proj_to_labels super().__init__(**lowercase_)
91
0
"""simple docstring""" from __future__ import annotations import math def _lowerCamelCase( a , a , a , a , a ): if depth < 0: raise ValueError("Depth cannot be less than 0" ) if not scores: raise ValueError("Scores cannot be empty" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __a , __a , __a ) , minimax(depth + 1 , node_index * 2 + 1 , __a , __a , __a ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __a , __a , __a ) , minimax(depth + 1 , node_index * 2 + 1 , __a , __a , __a ) , ) ) def _lowerCamelCase( ): __a = [9_0, 2_3, 6, 3_3, 2_1, 6_5, 1_2_3, 3_4_4_2_3] __a = math.log(len(__a ) , 2 ) print(F"Optimal value : {minimax(0 , 0 , __a , __a , __a )}" ) if __name__ == "__main__": import doctest doctest.testmod() main()
261
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' warnings.warn( '''The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DeiTImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() SCREAMING_SNAKE_CASE_:Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_:Optional[int] = { """post_extract_proj""": """feature_projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.upsample.0""": """encoder.upsample.projection""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: """simple docstring""" for attribute in key.split(""".""" ): A : str = getattr(__a , __a ) if weight_type is not None: A : Dict = getattr(__a , __a ).shape else: A : List[str] = hf_pointer.shape assert hf_shape == value.shape, ( f'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": A : Dict = value elif weight_type == "weight_g": A : Union[str, Any] = value elif weight_type == "weight_v": A : Tuple = value elif weight_type == "bias": A : Dict = value else: A : Optional[Any] = value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Optional[int]: """simple docstring""" A : List[str] = [] A : List[Any] = fairseq_model.state_dict() A : Any = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): A : Dict = False if "conv_layers" in name: load_conv_layer( __a , __a , __a , __a , hf_model.config.feat_extract_norm == """group""" , ) A : Any = True else: for key, mapped_key in MAPPING.items(): A : Union[str, Any] = '''sew.''' + mapped_key if (is_finetuned and mapped_key != '''lm_head''') else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: A : Optional[int] = True if "*" in mapped_key: A : int = name.split(__a )[0].split(""".""" )[-2] A : Optional[int] = mapped_key.replace("""*""" , __a ) if "weight_g" in name: A : Dict = '''weight_g''' elif "weight_v" in name: A : Union[str, Any] = '''weight_v''' elif "weight" in name: A : Tuple = '''weight''' elif "bias" in name: A : Dict = '''bias''' else: A : List[str] = None set_recursively(__a , __a , __a , __a , __a ) continue if not is_used: unused_weights.append(__a ) logger.warning(f'''Unused weights: {unused_weights}''' ) def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> str: """simple docstring""" A : Optional[int] = full_name.split("""conv_layers.""" )[-1] A : str = name.split(""".""" ) A : Optional[int] = int(items[0] ) A : List[str] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) A : Optional[int] = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) A : Optional[int] = value logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) A : Tuple = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'''{full_name} has size {value.shape}, but''' f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) A : Optional[int] = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(__a ) def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> Any: """simple docstring""" A : Union[str, Any] = SEWConfig() if is_finetuned: A : Optional[int] = model.wav_encoder.wav_model.cfg else: A : Optional[int] = model.cfg A : Tuple = fs_config.conv_bias A : Tuple = eval(fs_config.conv_feature_layers ) A : Any = [x[0] for x in conv_layers] A : int = [x[1] for x in conv_layers] A : int = [x[2] for x in conv_layers] A : List[Any] = '''gelu''' A : List[Any] = '''layer''' if fs_config.extractor_mode == '''layer_norm''' else '''group''' A : List[str] = 0.0 A : Dict = fs_config.activation_fn.name A : Optional[Any] = fs_config.encoder_embed_dim A : List[str] = 0.02 A : Tuple = fs_config.encoder_ffn_embed_dim A : List[Any] = 1e-5 A : Tuple = fs_config.encoder_layerdrop A : Optional[int] = fs_config.encoder_attention_heads A : Any = fs_config.conv_pos_groups A : Tuple = fs_config.conv_pos A : Dict = len(__a ) A : Tuple = fs_config.encoder_layers A : Optional[Any] = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: A : Optional[int] = model.cfg A : Optional[Any] = fs_config.final_dropout A : Dict = fs_config.layerdrop A : Tuple = fs_config.activation_dropout A : str = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 A : int = fs_config.attention_dropout A : Dict = fs_config.dropout_input A : List[str] = fs_config.dropout A : Any = fs_config.mask_channel_length A : Optional[int] = fs_config.mask_channel_prob A : str = fs_config.mask_length A : Tuple = fs_config.mask_prob A : Union[str, Any] = '''Wav2Vec2FeatureExtractor''' A : Any = '''Wav2Vec2CTCTokenizer''' return config @torch.no_grad() def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=True ) -> str: """simple docstring""" if is_finetuned: A : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: A : Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: A : Tuple = SEWConfig.from_pretrained(__a ) else: A : Dict = convert_config(model[0] , __a ) A : Union[str, Any] = model[0].eval() A : List[str] = True if config.feat_extract_norm == '''layer''' else False A : Optional[int] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=__a , return_attention_mask=__a , ) if is_finetuned: if dict_path: A : str = Dictionary.load(__a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq A : List[str] = target_dict.pad_index A : Tuple = target_dict.bos_index A : Any = target_dict.pad_index A : Dict = target_dict.bos_index A : str = target_dict.eos_index A : str = len(target_dict.symbols ) A : Optional[Any] = os.path.join(__a , """vocab.json""" ) if not os.path.isdir(__a ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__a ) ) return os.makedirs(__a , exist_ok=__a ) with open(__a , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(target_dict.indices , __a ) A : Tuple = WavaVecaCTCTokenizer( __a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=__a , ) A : Tuple = WavaVecaProcessor(feature_extractor=__a , tokenizer=__a ) processor.save_pretrained(__a ) A : Union[str, Any] = SEWForCTC(__a ) else: A : List[Any] = SEWModel(__a ) feature_extractor.save_pretrained(__a ) recursively_load_weights(__a , __a , __a ) hf_model.save_pretrained(__a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_:int = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) SCREAMING_SNAKE_CASE_:int = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
116
"""simple docstring""" import random from typing import Any def _A (__a ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ : Tuple = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = data[b], data[a] return data if __name__ == "__main__": UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5, 6, 7] UpperCAmelCase_ : Dict = ["""python""", """says""", """hello""", """!"""] print("""Fisher-Yates Shuffle:""") print("""List""", integers, strings) print("""FY Shuffle""", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
91
0
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class snake_case__: """simple docstring""" def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE : Collection[float] | None = None ): if components is None: lowercase__ : Optional[Any] = [] lowercase__ : int = list(lowercase_ ) def __len__( self : Optional[int] ): return len(self.__components ) def __str__( self : List[Any] ): return "(" + ",".join(map(lowercase_ , self.__components ) ) + ")" def __add__( self : Dict , SCREAMING_SNAKE_CASE : Vector ): lowercase__ : Dict = len(self ) if size == len(lowercase_ ): lowercase__ : Dict = [self.__components[i] + other.component(lowercase_ ) for i in range(lowercase_ )] return Vector(lowercase_ ) else: raise Exception("must have the same size" ) def __sub__( self : Union[str, Any] , SCREAMING_SNAKE_CASE : Vector ): lowercase__ : Optional[Any] = len(self ) if size == len(lowercase_ ): lowercase__ : Optional[Any] = [self.__components[i] - other.component(lowercase_ ) for i in range(lowercase_ )] return Vector(lowercase_ ) else: # error case raise Exception("must have the same size" ) @overload def __mul__( self : Optional[Any] , SCREAMING_SNAKE_CASE : float ): ... @overload def __mul__( self : Union[str, Any] , SCREAMING_SNAKE_CASE : Vector ): ... def __mul__( self : int , SCREAMING_SNAKE_CASE : float | Vector ): if isinstance(lowercase_ , (float, int) ): lowercase__ : int = [c * other for c in self.__components] return Vector(lowercase_ ) elif isinstance(lowercase_ , lowercase_ ) and len(self ) == len(lowercase_ ): lowercase__ : Optional[int] = len(self ) lowercase__ : List[str] = [self.__components[i] * other.component(lowercase_ ) for i in range(lowercase_ )] return sum(lowercase_ ) else: # error case raise Exception("invalid operand!" ) def snake_case ( self : Dict ): return Vector(self.__components ) def snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE : int ): if isinstance(lowercase_ , lowercase_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception("index out of range" ) def snake_case ( self : Any , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : float ): assert -len(self.__components ) <= pos < len(self.__components ) lowercase__ : Any = value def snake_case ( self : Union[str, Any] ): if len(self.__components ) == 0: raise Exception("Vector is empty" ) lowercase__ : Dict = [c**2 for c in self.__components] return math.sqrt(sum(lowercase_ ) ) def snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE : Vector , SCREAMING_SNAKE_CASE : bool = False ): lowercase__ : Union[str, Any] = self * other lowercase__ : Any = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" assert isinstance(__a , __a ) return Vector([0] * dimension ) def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" assert isinstance(__a , __a ) and (isinstance(__a , __a )) lowercase__ : List[str] = [0] * dimension lowercase__ : Union[str, Any] = 1 return Vector(__a ) def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" assert ( isinstance(__a , __a ) and isinstance(__a , __a ) and (isinstance(__a , (int, float) )) ) return x * scalar + y def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" random.seed(__a ) lowercase__ : List[str] = [random.randint(__a , __a ) for _ in range(__a )] return Vector(__a ) class snake_case__: """simple docstring""" def __init__( self : Any , SCREAMING_SNAKE_CASE : list[list[float]] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): lowercase__ : Any = matrix lowercase__ : Any = w lowercase__ : Union[str, Any] = h def __str__( self : Dict ): lowercase__ : Optional[int] = '''''' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self : str , SCREAMING_SNAKE_CASE : Matrix ): if self.__width == other.width() and self.__height == other.height(): lowercase__ : Tuple = [] for i in range(self.__height ): lowercase__ : Tuple = [ self.__matrix[i][j] + other.component(lowercase_ , lowercase_ ) for j in range(self.__width ) ] matrix.append(lowercase_ ) return Matrix(lowercase_ , self.__width , self.__height ) else: raise Exception("matrix must have the same dimension!" ) def __sub__( self : Optional[Any] , SCREAMING_SNAKE_CASE : Matrix ): if self.__width == other.width() and self.__height == other.height(): lowercase__ : Optional[int] = [] for i in range(self.__height ): lowercase__ : int = [ self.__matrix[i][j] - other.component(lowercase_ , lowercase_ ) for j in range(self.__width ) ] matrix.append(lowercase_ ) return Matrix(lowercase_ , self.__width , self.__height ) else: raise Exception("matrices must have the same dimension!" ) @overload def __mul__( self : str , SCREAMING_SNAKE_CASE : float ): ... @overload def __mul__( self : Optional[int] , SCREAMING_SNAKE_CASE : Vector ): ... def __mul__( self : List[str] , SCREAMING_SNAKE_CASE : float | Vector ): if isinstance(lowercase_ , lowercase_ ): # matrix-vector if len(lowercase_ ) == self.__width: lowercase__ : Optional[Any] = zero_vector(self.__height ) for i in range(self.__height ): lowercase__ : int = [ self.__matrix[i][j] * other.component(lowercase_ ) for j in range(self.__width ) ] ans.change_component(lowercase_ , sum(lowercase_ ) ) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(lowercase_ , (int, float) ): # matrix-scalar lowercase__ : Optional[Any] = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(lowercase_ , self.__width , self.__height ) return None def snake_case ( self : Optional[Any] ): return self.__height def snake_case ( self : Tuple ): return self.__width def snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds" ) def snake_case ( self : Optional[Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : float ): if 0 <= x < self.__height and 0 <= y < self.__width: lowercase__ : Dict = value else: raise Exception("change_component: indices out of bounds" ) def snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): if self.__height != self.__width: raise Exception("Matrix is not square" ) lowercase__ : int = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(lowercase_ ) ): lowercase__ : int = minor[i][:y] + minor[i][y + 1 :] return Matrix(lowercase_ , self.__width - 1 , self.__height - 1 ).determinant() def snake_case ( self : Tuple , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int ): if self.__height != self.__width: raise Exception("Matrix is not square" ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(lowercase_ , lowercase_ ) else: raise Exception("Indices out of bounds" ) def snake_case ( self : List[str] ): if self.__height != self.__width: raise Exception("Matrix is not square" ) if self.__height < 1: raise Exception("Matrix has no element" ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: lowercase__ : int = [ self.__matrix[0][y] * self.cofactor(0 , lowercase_ ) for y in range(self.__width ) ] return sum(lowercase_ ) def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" lowercase__ : list[list[float]] = [[0] * n for _ in range(__a )] return Matrix(__a , __a , __a ) def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" random.seed(__a ) lowercase__ : list[list[float]] = [ [random.randint(__a , __a ) for _ in range(__a )] for _ in range(__a ) ] return Matrix(__a , __a , __a )
130
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _A (__a , __a , __a ) -> Dict: """simple docstring""" if gpta_config_file == "": SCREAMING_SNAKE_CASE_ : Optional[Any] = GPTaConfig() else: SCREAMING_SNAKE_CASE_ : Tuple = GPTaConfig.from_json_file(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = GPTaModel(__a ) # Load weights from numpy load_tf_weights_in_gpta(__a , __a , __a ) # Save pytorch-model SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : List[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , __a ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow 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( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
91
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE__ = { """configuration_mobilenet_v2""": [ """MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MobileNetV2Config""", """MobileNetV2OnnxConfig""", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ["""MobileNetV2FeatureExtractor"""] SCREAMING_SNAKE_CASE__ = ["""MobileNetV2ImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ """MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST""", """MobileNetV2ForImageClassification""", """MobileNetV2ForSemanticSegmentation""", """MobileNetV2Model""", """MobileNetV2PreTrainedModel""", """load_tf_weights_in_mobilenet_v2""", ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
325
"""simple docstring""" from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
91
0
'''simple docstring''' def __UpperCAmelCase ( a_: Optional[int], a_: Dict ): while a != 0: _UpperCAmelCase : Optional[int] = b % a, a return b def __UpperCAmelCase ( a_: Optional[Any], a_: int ): if gcd(__a, __a ) != 1: _UpperCAmelCase : Any = f"""mod inverse of {a!r} and {m!r} does not exist""" raise ValueError(__a ) _UpperCAmelCase : Any = 1, 0, a _UpperCAmelCase : Dict = 0, 1, m while va != 0: _UpperCAmelCase : Any = ua // va _UpperCAmelCase : List[Any] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
145
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType 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, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' 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_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.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __a (UpperCAmelCase__ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = KandinskyInpaintPipeline _SCREAMING_SNAKE_CASE :Union[str, Any] = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image""", """mask_image"""] _SCREAMING_SNAKE_CASE :Optional[int] = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", """mask_image""", ] _SCREAMING_SNAKE_CASE :Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] _SCREAMING_SNAKE_CASE :Optional[Any] = False @property def _a ( self ) -> Union[str, Any]: """simple docstring""" return 32 @property def _a ( self ) -> Optional[Any]: """simple docstring""" return 32 @property def _a ( self ) -> str: """simple docstring""" return self.time_input_dim @property def _a ( self ) -> Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def _a ( self ) -> Tuple: """simple docstring""" return 100 @property def _a ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def _a ( self ) -> Any: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_005 , ) SCREAMING_SNAKE_CASE__ : Any = MultilingualCLIP(lowercase_ ) SCREAMING_SNAKE_CASE__ : List[Any] = text_encoder.eval() return text_encoder @property def _a ( self ) -> str: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = { '''in_channels''': 9, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''text_image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''text_image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel(**lowercase_ ) return model @property def _a ( self ) -> List[str]: """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _a ( self ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = VQModel(**self.dummy_movq_kwargs ) return model def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_tokenizer SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_unet SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_movq SCREAMING_SNAKE_CASE__ : List[Any] = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=lowercase_ , set_alpha_to_one=lowercase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=lowercase_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = { '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def _a ( self , _a , _a=0 ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(lowercase_ ) ).to(lowercase_ ) SCREAMING_SNAKE_CASE__ : int = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(lowercase_ ) # create init_image SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(lowercase_ ) ).to(lowercase_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(np.uinta(lowercase_ ) ).convert("""RGB""" ).resize((256, 256) ) # create mask SCREAMING_SNAKE_CASE__ : List[Any] = np.ones((64, 64) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : Any = 0 if str(lowercase_ ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ : Optional[int] = torch.manual_seed(lowercase_ ) else: SCREAMING_SNAKE_CASE__ : int = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) SCREAMING_SNAKE_CASE__ : Dict = { '''prompt''': '''horse''', '''image''': init_image, '''mask_image''': mask, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 2, '''guidance_scale''': 4.0, '''output_type''': '''np''', } return inputs def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = '''cpu''' SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : int = self.pipeline_class(**lowercase_ ) SCREAMING_SNAKE_CASE__ : str = pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**self.get_dummy_inputs(lowercase_ ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = output.images SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe( **self.get_dummy_inputs(lowercase_ ) , return_dict=lowercase_ , )[0] SCREAMING_SNAKE_CASE__ : int = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : str = image_from_tuple[0, -3:, -3:, -1] print(f'''image.shape {image.shape}''' ) assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ : str = np.array( [0.8_326_919, 0.73_790_467, 0.20_918_581, 0.9_309_612, 0.5_511_791, 0.43_713_328, 0.5_513_321, 0.49_922_934, 0.59_497_786] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' def _a ( self ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __a (unittest.TestCase): '''simple docstring''' def _a ( self ) -> Optional[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy""" ) SCREAMING_SNAKE_CASE__ : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) SCREAMING_SNAKE_CASE__ : Tuple = np.ones((768, 768) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Tuple = '''a hat''' SCREAMING_SNAKE_CASE__ : List[str] = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(lowercase_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = KandinskyInpaintPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-inpaint""" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : List[str] = pipeline.to(lowercase_ ) pipeline.set_progress_bar_config(disable=lowercase_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = pipe_prior( lowercase_ , generator=lowercase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() SCREAMING_SNAKE_CASE__ : str = pipeline( lowercase_ , image=lowercase_ , mask_image=lowercase_ , image_embeds=lowercase_ , negative_image_embeds=lowercase_ , generator=lowercase_ , num_inference_steps=100 , height=768 , width=768 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ : Tuple = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowercase_ , lowercase_ )
132
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase_ : Dict = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } UpperCAmelCase_ : List[str] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = GPTaTokenizer def __init__( self : Optional[int] , lowercase_ : int=None , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple="<|endoftext|>" , lowercase_ : str="<|endoftext|>" , lowercase_ : Dict="<|endoftext|>" , lowercase_ : Tuple=False , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , lowercase_ , tokenizer_file=lowercase_ , unk_token=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , add_prefix_space=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''add_bos_token''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('''add_prefix_space''' , lowercase_) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase_ , pre_tok_state.pop('''type''')) SCREAMING_SNAKE_CASE_ : str = add_prefix_space SCREAMING_SNAKE_CASE_ : Dict = pre_tok_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = add_prefix_space def _SCREAMING_SNAKE_CASE ( self : str , *lowercase_ : List[Any] , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''is_split_into_words''' , lowercase_) assert self.add_prefix_space or not is_split_into_words, ( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : List[str] , **lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.get('''is_split_into_words''' , lowercase_) assert self.add_prefix_space or not is_split_into_words, ( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._encode_plus(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self._tokenizer.model.save(lowercase_ , name=lowercase_) return tuple(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : "Conversation"): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase_ , add_special_tokens=lowercase_) + [self.eos_token_id]) if len(lowercase_) > self.model_max_length: SCREAMING_SNAKE_CASE_ : Any = input_ids[-self.model_max_length :] return input_ids
91
0
'''simple docstring''' from __future__ import annotations import math import numpy as np from numpy.linalg import norm def _lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : Union[str, Any] ) -> float: """simple docstring""" return math.sqrt(sum(pow(a - b , 2 ) for a, b in zip(__a , __a ) ) ) def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Union[str, Any] ) -> list[list[list[float] | float]]: """simple docstring""" if dataset.ndim != value_array.ndim: _SCREAMING_SNAKE_CASE =( '''Wrong input data\'s dimensions... ''' f"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(__a ) try: if dataset.shape[1] != value_array.shape[1]: _SCREAMING_SNAKE_CASE =( '''Wrong input data\'s shape... ''' f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(__a ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError('Wrong shape' ) if dataset.dtype != value_array.dtype: _SCREAMING_SNAKE_CASE =( '''Input data have different datatype... ''' f"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(__a ) _SCREAMING_SNAKE_CASE =[] for value in value_array: _SCREAMING_SNAKE_CASE =euclidean(__a , dataset[0] ) _SCREAMING_SNAKE_CASE =dataset[0].tolist() for dataset_value in dataset[1:]: _SCREAMING_SNAKE_CASE =euclidean(__a , __a ) if dist > temp_dist: _SCREAMING_SNAKE_CASE =temp_dist _SCREAMING_SNAKE_CASE =dataset_value.tolist() answer.append([vector, dist] ) return answer def _lowerCAmelCase ( _UpperCamelCase : int , _UpperCamelCase : List[Any] ) -> float: """simple docstring""" return np.dot(__a , __a ) / (norm(__a ) * norm(__a )) if __name__ == "__main__": import doctest doctest.testmod()
47
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(lowercase_ , '''hidden_sizes''')) self.parent.assertTrue(hasattr(lowercase_ , '''num_attention_heads''')) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Union[str, Any] , lowercase_ : List[Any]=13 , lowercase_ : Dict=64 , lowercase_ : Dict=3 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=2 , lowercase_ : Any=1 , lowercase_ : List[Any]=16 , lowercase_ : int=[128, 256, 384] , lowercase_ : str=[4, 6, 8] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Union[str, Any]=[16, 16, 16] , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[int]=[2, 2, 2] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=0.02 , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[int]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = kernel_size SCREAMING_SNAKE_CASE_ : Optional[Any] = stride SCREAMING_SNAKE_CASE_ : List[str] = padding SCREAMING_SNAKE_CASE_ : int = hidden_sizes SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : int = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = key_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_ratio SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = LevitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1) SCREAMING_SNAKE_CASE_ : Dict = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4) * ceil(width / 4), self.hidden_sizes[-1]) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitModelTester(self) SCREAMING_SNAKE_CASE_ : List[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return @unittest.skip(reason='''Levit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : str = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.model_tester.depths) + 1 self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) SCREAMING_SNAKE_CASE_ : Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) model.gradient_checkpointing_enable() model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowercase_), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'): SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''title'''] SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''num_labels'''] SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_ : str = inputs['''labels'''].unsqueeze(1).repeat(1 , problem_type['''num_labels''']) SCREAMING_SNAKE_CASE_ : Any = inputs['''labels'''].to(problem_type['''dtype''']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowercase_) as warning_list: SCREAMING_SNAKE_CASE_ : int = model(**lowercase_).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'Something is going wrong in the regression problem: intercepted {w.message}') loss.backward() @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = LevitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([1.04_48, -0.37_45, -1.83_17]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
91
0
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py _UpperCAmelCase : Optional[int] = """src/transformers""" _UpperCAmelCase : Tuple = """docs/source/en""" _UpperCAmelCase : Optional[Any] = """.""" def A ( lowercase , lowercase , lowercase ) -> Dict: '''simple docstring''' with open(__a , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase = f.readlines() # Find the start prompt. UpperCamelCase = 0 while not lines[start_index].startswith(__a ): start_index += 1 start_index += 1 UpperCamelCase = start_index while not lines[end_index].startswith(__a ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | _UpperCAmelCase : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. _UpperCAmelCase : int = re.compile(R"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") _UpperCAmelCase : Dict = re.compile(R"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _UpperCAmelCase : int = re.compile(R"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # This is to make sure the transformers module imported is the one in the repo. _UpperCAmelCase : Optional[int] = direct_transformers_import(TRANSFORMERS_PATH) def A ( lowercase ) -> int: '''simple docstring''' UpperCamelCase = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)' , __a ) return [m.group(0 ) for m in matches] def A ( lowercase , lowercase ) -> int: '''simple docstring''' UpperCamelCase = 2 if text == '''✅''' or text == '''❌''' else len(__a ) UpperCamelCase = (width - text_length) // 2 UpperCamelCase = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def A ( ) -> int: '''simple docstring''' UpperCamelCase = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES UpperCamelCase = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } UpperCamelCase = {name: config.replace('Config' , '' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. UpperCamelCase = collections.defaultdict(__a ) UpperCamelCase = collections.defaultdict(__a ) UpperCamelCase = collections.defaultdict(__a ) UpperCamelCase = collections.defaultdict(__a ) UpperCamelCase = collections.defaultdict(__a ) # Let's lookup through all transformers object (once). for attr_name in dir(__a ): UpperCamelCase = None if attr_name.endswith('Tokenizer' ): UpperCamelCase = slow_tokenizers UpperCamelCase = attr_name[:-9] elif attr_name.endswith('TokenizerFast' ): UpperCamelCase = fast_tokenizers UpperCamelCase = attr_name[:-13] elif _re_tf_models.match(__a ) is not None: UpperCamelCase = tf_models UpperCamelCase = _re_tf_models.match(__a ).groups()[0] elif _re_flax_models.match(__a ) is not None: UpperCamelCase = flax_models UpperCamelCase = _re_flax_models.match(__a ).groups()[0] elif _re_pt_models.match(__a ) is not None: UpperCamelCase = pt_models UpperCamelCase = _re_pt_models.match(__a ).groups()[0] if lookup_dict is not None: while len(__a ) > 0: if attr_name in model_name_to_prefix.values(): UpperCamelCase = True break # Try again after removing the last word in the name UpperCamelCase = ''''''.join(camel_case_split(__a )[:-1] ) # Let's build that table! UpperCamelCase = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) UpperCamelCase = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). UpperCamelCase = [len(__a ) + 2 for c in columns] UpperCamelCase = max([len(__a ) for name in model_names] ) + 2 # Build the table per se UpperCamelCase = '''|''' + '''|'''.join([_center_text(__a , __a ) for c, w in zip(__a , __a )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([':' + '-' * (w - 2) + ':' for w in widths] ) + "|\n" UpperCamelCase = {True: '''✅''', False: '''❌'''} for name in model_names: UpperCamelCase = model_name_to_prefix[name] UpperCamelCase = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__a , __a ) for l, w in zip(__a , __a )] ) + "|\n" return table def A ( lowercase=False ) -> List[str]: '''simple docstring''' UpperCamelCase = _find_text_in_file( filename=os.path.join(__a , 'index.md' ) , start_prompt='<!--This table is updated automatically from the auto modules' , end_prompt='<!-- End table-->' , ) UpperCamelCase = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__a , 'index.md' ) , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( 'The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.' ) if __name__ == "__main__": _UpperCAmelCase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") _UpperCAmelCase : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
222
"""simple docstring""" from math import factorial def _A (__a = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[str] = n // 2 return int(factorial(__a ) / (factorial(__a ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCAmelCase_ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
91
0
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): """simple docstring""" lowercase__ = ["image_processor", "tokenizer"] lowercase__ = "ViTImageProcessor" lowercase__ = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : str ,lowercase_ : Any=None ,lowercase_ : Optional[Any]=None ,**lowercase_ : int ): lowerCAmelCase__ : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' ,lowercase_ ,) lowerCAmelCase__ : Union[str, Any] = kwargs.pop('''feature_extractor''' ) lowerCAmelCase__ : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(lowercase_ ,lowercase_ ) def __call__( self : Optional[Any] ,lowercase_ : str=None ,lowercase_ : Optional[int]=None ,lowercase_ : Dict=None ,lowercase_ : List[Any]=None ,**lowercase_ : int ): if text is None and visual_prompt is None and images is None: raise ValueError('''You have to specify either text, visual prompt or images.''' ) if text is not None and visual_prompt is not None: raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.''' ) if text is not None: lowerCAmelCase__ : Optional[Any] = self.tokenizer(lowercase_ ,return_tensors=lowercase_ ,**lowercase_ ) if visual_prompt is not None: lowerCAmelCase__ : Union[str, Any] = self.image_processor(lowercase_ ,return_tensors=lowercase_ ,**lowercase_ ) if images is not None: lowerCAmelCase__ : Optional[int] = self.image_processor(lowercase_ ,return_tensors=lowercase_ ,**lowercase_ ) if visual_prompt is not None and images is not None: lowerCAmelCase__ : Optional[Any] = { '''pixel_values''': image_features.pixel_values, '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: lowerCAmelCase__ : int = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: lowerCAmelCase__ : int = { '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**lowercase_ ) ,tensor_type=lowercase_ ) def __lowerCAmelCase ( self : Tuple ,*lowercase_ : str ,**lowercase_ : List[Any] ): return self.tokenizer.batch_decode(*lowercase_ ,**lowercase_ ) def __lowerCAmelCase ( self : Optional[int] ,*lowercase_ : Union[str, Any] ,**lowercase_ : List[str] ): return self.tokenizer.decode(*lowercase_ ,**lowercase_ ) @property def __lowerCAmelCase ( self : Optional[int] ): warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' ,lowercase_ ,) return self.image_processor_class @property def __lowerCAmelCase ( self : Tuple ): warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' ,lowercase_ ,) return self.image_processor
106
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCAmelCase_ : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *lowercase_ : List[str] , **lowercase_ : List[str]): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
0
"""simple docstring""" import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): UpperCAmelCase_ : int = ('''dense.weight''', '''attention.self.query''', '''attention.self.key''', '''attention.self.value''') UpperCAmelCase_ : Union[str, Any] = ( ('''layer.''', '''layer_'''), ('''word_embeddings.weight''', '''word_embeddings'''), ('''position_embeddings.weight''', '''position_embeddings'''), ('''token_type_embeddings.weight''', '''token_type_embeddings'''), ('''.''', '''/'''), ('''LayerNorm/weight''', '''LayerNorm/gamma'''), ('''LayerNorm/bias''', '''LayerNorm/beta'''), ('''weight''', '''kernel'''), ) if not os.path.isdir(__a ): os.makedirs(__a ) UpperCAmelCase_ : Dict = model.state_dict() def to_tf_var_name(__lowerCamelCase ): for patt, repl in iter(__a ): UpperCAmelCase_ : Optional[int] = name.replace(__a, __a ) return f"""bert/{name}""" def create_tf_var(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): UpperCAmelCase_ : List[str] = tf.dtypes.as_dtype(tensor.dtype ) UpperCAmelCase_ : Optional[int] = tf.get_variable(dtype=__a, shape=tensor.shape, name=__a, initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(__a ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: UpperCAmelCase_ : Any = to_tf_var_name(__a ) UpperCAmelCase_ : Any = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): UpperCAmelCase_ : List[str] = torch_tensor.T UpperCAmelCase_ : List[Any] = create_tf_var(tensor=__a, name=__a, session=__a ) tf.keras.backend.set_value(__a, __a ) UpperCAmelCase_ : Optional[int] = session.run(__a ) print(f"""Successfully created {tf_name}: {np.allclose(__a, __a )}""" ) UpperCAmelCase_ : str = tf.train.Saver(tf.trainable_variables() ) saver.save(__a, os.path.join(__a, model_name.replace("-", "_" ) + ".ckpt" ) ) def __a ( __lowerCamelCase=None ): UpperCAmelCase_ : List[str] = argparse.ArgumentParser() parser.add_argument("--model_name", type=__a, required=__a, help="model name e.g. bert-base-uncased" ) parser.add_argument( "--cache_dir", type=__a, default=__a, required=__a, help="Directory containing pytorch model" ) parser.add_argument("--pytorch_model_path", type=__a, required=__a, help="/path/to/<pytorch-model-name>.bin" ) parser.add_argument("--tf_cache_dir", type=__a, required=__a, help="Directory in which to save tensorflow model" ) UpperCAmelCase_ : Dict = parser.parse_args(__a ) UpperCAmelCase_ : Dict = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name, state_dict=torch.load(args.pytorch_model_path ), cache_dir=args.cache_dir, ) convert_pytorch_checkpoint_to_tf(model=__a, ckpt_dir=args.tf_cache_dir, model_name=args.model_name ) if __name__ == "__main__": main()
61
"""simple docstring""" from __future__ import annotations class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : int = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = key def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : int = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[str] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[Any] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''encrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(lowercase_ , lowercase_)) except OSError: return False return True def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''decrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(lowercase_ , lowercase_)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
91
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) _lowerCamelCase : Dict = { """uclanlp/visualbert-vqa""": """https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json""", """uclanlp/visualbert-vqa-pre""": """https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json""", """uclanlp/visualbert-vqa-coco-pre""": ( """https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json""" ), """uclanlp/visualbert-vcr""": """https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json""", """uclanlp/visualbert-vcr-pre""": """https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json""", """uclanlp/visualbert-vcr-coco-pre""": ( """https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json""" ), """uclanlp/visualbert-nlvr2""": """https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json""", """uclanlp/visualbert-nlvr2-pre""": """https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json""", """uclanlp/visualbert-nlvr2-coco-pre""": ( """https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json""" ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): '''simple docstring''' _UpperCAmelCase : Optional[Any] = "visual_bert" def __init__( self : List[Any] , lowercase : str=30_522 , lowercase : Optional[Any]=768 , lowercase : str=512 , lowercase : Tuple=12 , lowercase : str=12 , lowercase : int=3_072 , lowercase : Dict="gelu" , lowercase : int=0.1 , lowercase : Any=0.1 , lowercase : List[str]=512 , lowercase : Any=2 , lowercase : Optional[int]=0.02 , lowercase : List[str]=1E-12 , lowercase : Optional[Any]=False , lowercase : str=True , lowercase : Dict=1 , lowercase : str=0 , lowercase : Optional[Any]=2 , **lowercase : Union[str, Any] , ): '''simple docstring''' super().__init__(pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_ ) _snake_case = vocab_size _snake_case = max_position_embeddings _snake_case = hidden_size _snake_case = visual_embedding_dim _snake_case = num_hidden_layers _snake_case = num_attention_heads _snake_case = intermediate_size _snake_case = hidden_act _snake_case = hidden_dropout_prob _snake_case = attention_probs_dropout_prob _snake_case = initializer_range _snake_case = type_vocab_size _snake_case = layer_norm_eps _snake_case = bypass_transformer _snake_case = special_visual_initialize
282
"""simple docstring""" def _A (__a = 50 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'''{solution() = }''')
91
0
"""simple docstring""" from __future__ import annotations from random import choice def _lowerCamelCase( a ): return choice(__a ) def _lowerCamelCase( a , a ): __a = random_pivot(__a ) # partition based on pivot # linear time __a = [e for e in lst if e < pivot] __a = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(__a ) == k - 1: return pivot # pivot is in elements bigger than k elif len(__a ) < k - 1: return kth_number(__a , k - len(__a ) - 1 ) # pivot is in elements smaller than k else: return kth_number(__a , __a ) if __name__ == "__main__": import doctest doctest.testmod()
261
"""simple docstring""" import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = (PNDMScheduler,) __UpperCamelCase = (("num_inference_steps", 5_0),) def _SCREAMING_SNAKE_CASE ( self : Any , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**lowercase_) return config def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[str]=0 , **lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample SCREAMING_SNAKE_CASE_ : List[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : Dict = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class.from_pretrained(lowercase_) new_scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Optional[Any] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Dict = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str]=0 , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Dict = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler_class.from_pretrained(lowercase_) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Any = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Tuple = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : str , **lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Dict = 10 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE_ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_) for i, t in enumerate(scheduler.prk_timesteps): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample for i, t in enumerate(scheduler.plms_timesteps): SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_).prev_sample return sample def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''num_inference_steps''' , lowercase_) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowercase_ , '''set_timesteps'''): scheduler.set_timesteps(lowercase_) elif num_inference_steps is not None and not hasattr(lowercase_ , '''set_timesteps'''): SCREAMING_SNAKE_CASE_ : Optional[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE_ : str = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE_ : Optional[int] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Dict = scheduler.step_prk(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : List[Any] = scheduler.step_prk(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_plms(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Any = scheduler.step_plms(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config(steps_offset=1) SCREAMING_SNAKE_CASE_ : Tuple = scheduler_class(**lowercase_) scheduler.set_timesteps(10) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]) , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01] , [0.0_02, 0.02]): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100]): self.check_over_forward(num_inference_steps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = 27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_sample SCREAMING_SNAKE_CASE_ : str = 0.1 * sample SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2]): SCREAMING_SNAKE_CASE_ : int = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : int = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Dict = scheduler_class(**lowercase_) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample).prev_sample def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.full_loop() SCREAMING_SNAKE_CASE_ : List[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_98.13_18) < 1e-2 assert abs(result_mean.item() - 0.25_80) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.full_loop(prediction_type='''v_prediction''') SCREAMING_SNAKE_CASE_ : str = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 67.39_86) < 1e-2 assert abs(result_mean.item() - 0.08_78) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 2_30.03_99) < 1e-2 assert abs(result_mean.item() - 0.29_95) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : int = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_86.94_82) < 1e-2 assert abs(result_mean.item() - 0.24_34) < 1e-3
91
0
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ("""foo.json""",)] ) def _lowerCAmelCase ( self, lowerCamelCase__ ): A : List[str] = GenerationConfig( do_sample=lowercase_, temperature=0.7, length_penalty=1.0, bad_words_ids=[[1, 2, 3], [4, 5]], ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_, config_name=lowercase_ ) A : Tuple = GenerationConfig.from_pretrained(lowercase_, config_name=lowercase_ ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample, lowercase_ ) self.assertEqual(loaded_config.temperature, 0.7 ) self.assertEqual(loaded_config.length_penalty, 1.0 ) self.assertEqual(loaded_config.bad_words_ids, [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k, 50 ) self.assertEqual(loaded_config.max_length, 20 ) self.assertEqual(loaded_config.max_time, lowercase_ ) def _lowerCAmelCase ( self ): A : Optional[Any] = AutoConfig.from_pretrained("""gpt2""" ) A : int = GenerationConfig.from_model_config(lowercase_ ) A : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_, lowercase_ ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id, default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id, model_config.eos_token_id ) def _lowerCAmelCase ( self ): A : str = GenerationConfig() A : Any = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } A : str = copy.deepcopy(lowercase_ ) A : Tuple = generation_config.update(**lowercase_ ) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_, lowercase_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens, 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_, {"""foo""": """bar"""} ) def _lowerCAmelCase ( self ): A : Optional[Any] = GenerationConfig() A : List[str] = '''bar''' with tempfile.TemporaryDirectory("""test-generation-config""" ) as tmp_dir: generation_config.save_pretrained(lowercase_ ) A : List[Any] = GenerationConfig.from_pretrained(lowercase_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo, """bar""" ) A : Optional[Any] = GenerationConfig.from_model_config(lowercase_ ) assert not hasattr(lowercase_, """foo""" ) # no new kwargs should be initialized if from config def _lowerCAmelCase ( self ): A : Tuple = GenerationConfig() self.assertEqual(default_config.temperature, 1.0 ) self.assertEqual(default_config.do_sample, lowercase_ ) self.assertEqual(default_config.num_beams, 1 ) A : Dict = GenerationConfig( do_sample=lowercase_, temperature=0.7, length_penalty=1.0, bad_words_ids=[[1, 2, 3], [4, 5]], ) self.assertEqual(config.temperature, 0.7 ) self.assertEqual(config.do_sample, lowercase_ ) self.assertEqual(config.num_beams, 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ ) A : Tuple = GenerationConfig.from_pretrained(lowercase_, temperature=1.0 ) self.assertEqual(loaded_config.temperature, 1.0 ) self.assertEqual(loaded_config.do_sample, lowercase_ ) self.assertEqual(loaded_config.num_beams, 1 ) # default value @is_staging_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _lowerCAmelCase ( cls ): A : str = TOKEN HfFolder.save_token(lowercase_ ) @classmethod def _lowerCAmelCase ( cls ): try: delete_repo(token=cls._token, repo_id="""test-generation-config""" ) except HTTPError: pass try: delete_repo(token=cls._token, repo_id="""valid_org/test-generation-config-org""" ) except HTTPError: pass def _lowerCAmelCase ( self ): A : Tuple = GenerationConfig( do_sample=lowercase_, temperature=0.7, length_penalty=1.0, ) config.push_to_hub("""test-generation-config""", use_auth_token=self._token ) A : int = GenerationConfig.from_pretrained(f'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_, getattr(lowercase_, lowercase_ ) ) # Reset repo delete_repo(token=self._token, repo_id="""test-generation-config""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_, repo_id="""test-generation-config""", push_to_hub=lowercase_, use_auth_token=self._token ) A : Optional[int] = GenerationConfig.from_pretrained(f'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_, getattr(lowercase_, lowercase_ ) ) def _lowerCAmelCase ( self ): A : Dict = GenerationConfig( do_sample=lowercase_, temperature=0.7, length_penalty=1.0, ) config.push_to_hub("""valid_org/test-generation-config-org""", use_auth_token=self._token ) A : Any = GenerationConfig.from_pretrained("""valid_org/test-generation-config-org""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_, getattr(lowercase_, lowercase_ ) ) # Reset repo delete_repo(token=self._token, repo_id="""valid_org/test-generation-config-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_, repo_id="""valid_org/test-generation-config-org""", push_to_hub=lowercase_, use_auth_token=self._token ) A : Any = GenerationConfig.from_pretrained("""valid_org/test-generation-config-org""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_, getattr(lowercase_, lowercase_ ) )
116
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)]) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ , config_name=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , config_name=lowercase_) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50) self.assertEqual(loaded_config.max_length , 20) self.assertEqual(loaded_config.max_time , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained('''gpt2''') SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_model_config(lowercase_) SCREAMING_SNAKE_CASE_ : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_ , lowercase_) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = GenerationConfig() SCREAMING_SNAKE_CASE_ : Any = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = generation_config.update(**lowercase_) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_ , lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_ , {'''foo''': '''bar'''}) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig() SCREAMING_SNAKE_CASE_ : List[str] = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir: generation_config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = GenerationConfig.from_pretrained(lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''') SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig.from_model_config(lowercase_) assert not hasattr(lowercase_ , '''foo''') # no new kwargs should be initialized if from config def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , lowercase_) self.assertEqual(default_config.num_beams , 1) SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , lowercase_) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str]): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-generation-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''test-generation-config''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Optional[int] = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_))
91
0
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class snake_case__(UpperCAmelCase__ ): """simple docstring""" lowercase_ = ["""image_processor""", """tokenizer"""] lowercase_ = """Pix2StructImageProcessor""" lowercase_ = ("""T5Tokenizer""", """T5TokenizerFast""") def __init__( self : Any , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : str ): lowercase__ : Tuple = False super().__init__(lowercase_ , lowercase_ ) def __call__( self : Dict , SCREAMING_SNAKE_CASE : Optional[int]=None , SCREAMING_SNAKE_CASE : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , SCREAMING_SNAKE_CASE : bool = True , SCREAMING_SNAKE_CASE : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE : Union[bool, str, TruncationStrategy] = None , SCREAMING_SNAKE_CASE : Optional[int] = None , SCREAMING_SNAKE_CASE : Optional[int] = 2_048 , SCREAMING_SNAKE_CASE : int = 0 , SCREAMING_SNAKE_CASE : Optional[int] = None , SCREAMING_SNAKE_CASE : Optional[bool] = None , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = True , SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , **SCREAMING_SNAKE_CASE : List[str] , ): if images is None and text is None: raise ValueError("You have to specify either images or text." ) # Get only text if images is None and not self.image_processor.is_vqa: lowercase__ : Dict = self.tokenizer lowercase__ : List[Any] = self.tokenizer( text=lowercase_ , add_special_tokens=lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , stride=lowercase_ , pad_to_multiple_of=lowercase_ , return_attention_mask=lowercase_ , return_overflowing_tokens=lowercase_ , return_special_tokens_mask=lowercase_ , return_offsets_mapping=lowercase_ , return_token_type_ids=lowercase_ , return_length=lowercase_ , verbose=lowercase_ , return_tensors=lowercase_ , **lowercase_ , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values lowercase__ : Any = self.image_processor( lowercase_ , return_tensors=lowercase_ , max_patches=lowercase_ , **lowercase_ ) else: # add pixel_values and bbox lowercase__ : List[Any] = self.image_processor( lowercase_ , return_tensors=lowercase_ , max_patches=lowercase_ , header_text=lowercase_ , **lowercase_ ) if text is not None and not self.image_processor.is_vqa: lowercase__ : Dict = self.tokenizer( text=lowercase_ , add_special_tokens=lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , stride=lowercase_ , pad_to_multiple_of=lowercase_ , return_attention_mask=lowercase_ , return_overflowing_tokens=lowercase_ , return_special_tokens_mask=lowercase_ , return_offsets_mapping=lowercase_ , return_token_type_ids=lowercase_ , return_length=lowercase_ , verbose=lowercase_ , return_tensors=lowercase_ , **lowercase_ , ) if "attention_mask" in text_encoding: lowercase__ : List[Any] = text_encoding.pop("attention_mask" ) if "input_ids" in text_encoding: lowercase__ : Dict = text_encoding.pop("input_ids" ) else: lowercase__ : str = None if text_encoding is not None: encoding_image_processor.update(lowercase_ ) return encoding_image_processor def snake_case ( self : Optional[Any] , *SCREAMING_SNAKE_CASE : str , **SCREAMING_SNAKE_CASE : List[str] ): return self.tokenizer.batch_decode(*lowercase_ , **lowercase_ ) def snake_case ( self : List[str] , *SCREAMING_SNAKE_CASE : List[Any] , **SCREAMING_SNAKE_CASE : Any ): return self.tokenizer.decode(*lowercase_ , **lowercase_ ) @property def snake_case ( self : str ): lowercase__ : int = self.tokenizer.model_input_names lowercase__ : List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
130
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : List[str] = """\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\", author = \"Moosavi, Nafise Sadat and Strube, Michael\", booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\", month = aug, year = \"2016\", address = \"Berlin, Germany\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/P16-1060\", doi = \"10.18653/v1/P16-1060\", pages = \"632--642\", } """ UpperCAmelCase_ : Tuple = """\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. """ UpperCAmelCase_ : Union[str, Any] = """ Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting 'keep_singletons=False', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs. min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: 'mentions': mentions 'muc': MUC metric [Vilain et al, 1995] 'bcub': B-cubed [Bagga and Baldwin, 1998] 'ceafe': CEAFe [Luo et al., 2005] 'lea': LEA [Moosavi and Strube, 2016] 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric('coval') >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -', ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)', ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)', ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -', ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -', ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {'mentions/recall': 1.0,[...] 'conll_score': 100.0} """ def _A (__a , __a , __a=False , __a=False , __a=True , __a=False , __a="dummy_doc" ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {doc: key_lines} SCREAMING_SNAKE_CASE_ : List[str] = {doc: sys_lines} SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = reader.get_doc_mentions(__a , key_doc_lines[doc] , __a ) key_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(__a , sys_doc_lines[doc] , __a ) sys_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) if remove_nested: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def _A (__a , __a , __a , __a , __a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_coref_infos(__a , __a , __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : str = {} SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = 0 for name, metric in metrics: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = evaluator.evaluate_documents(__a , __a , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 1_00:.2f}' , f' Precision: {precision * 1_00:.2f}' , f' F1: {fa * 1_00:.2f}' , ) if conll_subparts_num == 3: SCREAMING_SNAKE_CASE_ : Tuple = (conll / 3) * 1_00 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: SCREAMING_SNAKE_CASE_ : Any = line.split()[5] if not parse_col == "-": SCREAMING_SNAKE_CASE_ : Any = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''')), '''references''': datasets.Sequence(datasets.Value('''string''')), }) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Dict=True , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=False , lowercase_ : Dict=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = util.check_gold_parse_annotation(lowercase_) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''') # util.parse_key_file(key_file) # key_file = key_file + ".parsed" SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate( key_lines=lowercase_ , sys_lines=lowercase_ , metrics=lowercase_ , NP_only=lowercase_ , remove_nested=lowercase_ , keep_singletons=lowercase_ , min_span=lowercase_ , ) return score
91
0
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class A__ ( UpperCAmelCase__ ): lowerCAmelCase__ : int = (PNDMScheduler,) lowerCAmelCase__ : List[Any] = (("num_inference_steps", 50),) def a__ ( self : Any , **_UpperCAmelCase : Optional[Any] ) -> Union[str, Any]: """simple docstring""" __lowercase = { '''num_train_timesteps''': 10_00, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**lowercase_ ) return config def a__ ( self : Optional[Any] , _UpperCAmelCase : List[str]=0 , **_UpperCAmelCase : Union[str, Any] ) -> Dict: """simple docstring""" __lowercase = dict(self.forward_default_kwargs ) __lowercase = kwargs.pop('num_inference_steps' , lowercase_ ) __lowercase = self.dummy_sample __lowercase = 0.1 * sample __lowercase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __lowercase = self.get_scheduler_config(**lowercase_ ) __lowercase = scheduler_class(**lowercase_ ) scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals __lowercase = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_ ) __lowercase = scheduler_class.from_pretrained(lowercase_ ) new_scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals __lowercase = dummy_past_residuals[:] __lowercase = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample __lowercase = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" __lowercase = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample __lowercase = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def a__ ( self : Any ) -> Optional[int]: """simple docstring""" pass def a__ ( self : List[Any] , _UpperCAmelCase : List[str]=0 , **_UpperCAmelCase : List[str] ) -> Tuple: """simple docstring""" __lowercase = dict(self.forward_default_kwargs ) __lowercase = kwargs.pop('num_inference_steps' , lowercase_ ) __lowercase = self.dummy_sample __lowercase = 0.1 * sample __lowercase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __lowercase = self.get_scheduler_config() __lowercase = scheduler_class(**lowercase_ ) scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals (must be after setting timesteps) __lowercase = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_ ) __lowercase = scheduler_class.from_pretrained(lowercase_ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_ ) # copy over dummy past residual (must be after setting timesteps) __lowercase = dummy_past_residuals[:] __lowercase = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample __lowercase = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" __lowercase = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample __lowercase = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def a__ ( self : str , **_UpperCAmelCase : str ) -> Any: """simple docstring""" __lowercase = self.scheduler_classes[0] __lowercase = self.get_scheduler_config(**lowercase_ ) __lowercase = scheduler_class(**lowercase_ ) __lowercase = 10 __lowercase = self.dummy_model() __lowercase = self.dummy_sample_deter scheduler.set_timesteps(lowercase_ ) for i, t in enumerate(scheduler.prk_timesteps ): __lowercase = model(lowercase_ , lowercase_ ) __lowercase = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): __lowercase = model(lowercase_ , lowercase_ ) __lowercase = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ ).prev_sample return sample def a__ ( self : Dict ) -> str: """simple docstring""" __lowercase = dict(self.forward_default_kwargs ) __lowercase = kwargs.pop('num_inference_steps' , lowercase_ ) for scheduler_class in self.scheduler_classes: __lowercase = self.get_scheduler_config() __lowercase = scheduler_class(**lowercase_ ) __lowercase = self.dummy_sample __lowercase = 0.1 * sample if num_inference_steps is not None and hasattr(lowercase_ , 'set_timesteps' ): scheduler.set_timesteps(lowercase_ ) elif num_inference_steps is not None and not hasattr(lowercase_ , 'set_timesteps' ): __lowercase = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __lowercase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] __lowercase = dummy_past_residuals[:] __lowercase = scheduler.step_prk(lowercase_ , 0 , lowercase_ , **lowercase_ ).prev_sample __lowercase = scheduler.step_prk(lowercase_ , 1 , lowercase_ , **lowercase_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) __lowercase = scheduler.step_plms(lowercase_ , 0 , lowercase_ , **lowercase_ ).prev_sample __lowercase = scheduler.step_plms(lowercase_ , 1 , lowercase_ , **lowercase_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def a__ ( self : str ) -> List[Any]: """simple docstring""" for timesteps in [1_00, 10_00]: self.check_over_configs(num_train_timesteps=lowercase_ ) def a__ ( self : Dict ) -> Any: """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_ ) __lowercase = self.scheduler_classes[0] __lowercase = self.get_scheduler_config(steps_offset=1 ) __lowercase = scheduler_class(**lowercase_ ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps , torch.LongTensor( [9_01, 8_51, 8_51, 8_01, 8_01, 7_51, 7_51, 7_01, 7_01, 6_51, 6_51, 6_01, 6_01, 5_01, 4_01, 3_01, 2_01, 1_01, 1] ) , ) def a__ ( self : Any ) -> Optional[int]: """simple docstring""" for beta_start, beta_end in zip([0.0_001, 0.001] , [0.002, 0.02] ): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_ ) def a__ ( self : List[Any] ) -> int: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_ ) def a__ ( self : Any ) -> Union[str, Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_ ) def a__ ( self : int ) -> Optional[int]: """simple docstring""" for t in [1, 5, 10]: self.check_over_forward(time_step=lowercase_ ) def a__ ( self : Optional[Any] ) -> Any: """simple docstring""" for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 1_00] ): self.check_over_forward(num_inference_steps=lowercase_ ) def a__ ( self : Any ) -> List[str]: """simple docstring""" __lowercase = 27 for scheduler_class in self.scheduler_classes: __lowercase = self.dummy_sample __lowercase = 0.1 * sample __lowercase = self.get_scheduler_config() __lowercase = scheduler_class(**lowercase_ ) scheduler.set_timesteps(lowercase_ ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): __lowercase = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ ).prev_sample def a__ ( self : List[Any] ) -> str: """simple docstring""" with self.assertRaises(lowercase_ ): __lowercase = self.scheduler_classes[0] __lowercase = self.get_scheduler_config() __lowercase = scheduler_class(**lowercase_ ) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample def a__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __lowercase = self.full_loop() __lowercase = torch.sum(torch.abs(lowercase_ ) ) __lowercase = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_98.13_18 ) < 1e-2 assert abs(result_mean.item() - 0.2_580 ) < 1e-3 def a__ ( self : Optional[int] ) -> str: """simple docstring""" __lowercase = self.full_loop(prediction_type='v_prediction' ) __lowercase = torch.sum(torch.abs(lowercase_ ) ) __lowercase = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 67.3_986 ) < 1e-2 assert abs(result_mean.item() - 0.0_878 ) < 1e-3 def a__ ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __lowercase = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01 ) __lowercase = torch.sum(torch.abs(lowercase_ ) ) __lowercase = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 2_30.03_99 ) < 1e-2 assert abs(result_mean.item() - 0.2_995 ) < 1e-3 def a__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" __lowercase = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01 ) __lowercase = torch.sum(torch.abs(lowercase_ ) ) __lowercase = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_86.94_82 ) < 1e-2 assert abs(result_mean.item() - 0.2_434 ) < 1e-3
325
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = """▁""" UpperCAmelCase_ : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCAmelCase_ : str = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } UpperCAmelCase_ : str = { """facebook/xglm-564M""": 2048, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[Any] , lowercase_ : str , lowercase_ : Tuple="<s>" , lowercase_ : Any="</s>" , lowercase_ : Optional[int]="</s>" , lowercase_ : List[Any]="<s>" , lowercase_ : Union[str, Any]="<unk>" , lowercase_ : Union[str, Any]="<pad>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE_ : List[str] = 7 SCREAMING_SNAKE_CASE_ : Tuple = [F'<madeupword{i}>' for i in range(self.num_madeup_words)] SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''additional_special_tokens''' , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} SCREAMING_SNAKE_CASE_ : List[Any] = len(self.sp_model) SCREAMING_SNAKE_CASE_ : Optional[Any] = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE_ : Dict = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = 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_)) return [1] + ([0] * len(lowercase_)) + [1, 1] + ([0] * len(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : str): '''simple docstring''' return self.sp_model.encode(lowercase_ , out_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Union[str, Any]): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sp_model.PieceToId(lowercase_) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any]): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(lowercase_).replace(lowercase_ , ''' ''').strip() return out_string def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : int = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,)
91
0
'''simple docstring''' def __UpperCAmelCase ( a_: int, a_: List[Any] ): if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) _UpperCAmelCase : Union[str, Any] = str(bin(__a ) )[2:] # remove the leading "0b" _UpperCAmelCase : Dict = str(bin(__a ) )[2:] # remove the leading "0b" _UpperCAmelCase : List[str] = max(len(__a ), len(__a ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(__a ), b_binary.zfill(__a ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
145
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Dict = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : str = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_))
91
0
"""simple docstring""" def _lowercase ( __lowerCAmelCase = 100 ) -> int: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE__ : Optional[int] = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(f'{solution() = }')
132
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable UpperCAmelCase_ : str = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
0
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available from .timesteps import ( fastaa_timesteps, smartaa_timesteps, smartaa_timesteps, smartaaa_timesteps, smartaaa_timesteps, superaa_timesteps, superaa_timesteps, superaaa_timesteps, ) @dataclass class A__ ( UpperCAmelCase__ ): A__ = 42 A__ = 42 A__ = 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_if import IFPipeline from .pipeline_if_imgaimg import IFImgaImgPipeline from .pipeline_if_imgaimg_superresolution import IFImgaImgSuperResolutionPipeline from .pipeline_if_inpainting import IFInpaintingPipeline from .pipeline_if_inpainting_superresolution import IFInpaintingSuperResolutionPipeline from .pipeline_if_superresolution import IFSuperResolutionPipeline from .safety_checker import IFSafetyChecker from .watermark import IFWatermarker
47
"""simple docstring""" import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py UpperCAmelCase_ : Optional[int] = """src/transformers""" UpperCAmelCase_ : Tuple = """docs/source/en""" UpperCAmelCase_ : Optional[Any] = """.""" def _A (__a , __a , __a ) -> Dict: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE_ : List[Any] = 0 while not lines[start_index].startswith(__a ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Tuple = start_index while not lines[end_index].startswith(__a ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCAmelCase_ : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. UpperCAmelCase_ : int = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") UpperCAmelCase_ : Dict = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCAmelCase_ : int = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase_ : Optional[int] = direct_transformers_import(TRANSFORMERS_PATH) def _A (__a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __a ) return [m.group(0 ) for m in matches] def _A (__a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 2 if text == '''✅''' or text == '''❌''' else len(__a ) SCREAMING_SNAKE_CASE_ : Tuple = (width - text_length) // 2 SCREAMING_SNAKE_CASE_ : Tuple = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ : Tuple = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } SCREAMING_SNAKE_CASE_ : List[Any] = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) # Let's lookup through all transformers object (once). for attr_name in dir(__a ): SCREAMING_SNAKE_CASE_ : Any = None if attr_name.endswith('''Tokenizer''' ): SCREAMING_SNAKE_CASE_ : Dict = slow_tokenizers SCREAMING_SNAKE_CASE_ : Dict = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = fast_tokenizers SCREAMING_SNAKE_CASE_ : Optional[Any] = attr_name[:-13] elif _re_tf_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : int = tf_models SCREAMING_SNAKE_CASE_ : Dict = _re_tf_models.match(__a ).groups()[0] elif _re_flax_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : Any = flax_models SCREAMING_SNAKE_CASE_ : Tuple = _re_flax_models.match(__a ).groups()[0] elif _re_pt_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : str = pt_models SCREAMING_SNAKE_CASE_ : int = _re_pt_models.match(__a ).groups()[0] if lookup_dict is not None: while len(__a ) > 0: if attr_name in model_name_to_prefix.values(): SCREAMING_SNAKE_CASE_ : List[str] = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(camel_case_split(__a )[:-1] ) # Let's build that table! SCREAMING_SNAKE_CASE_ : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) SCREAMING_SNAKE_CASE_ : Any = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). SCREAMING_SNAKE_CASE_ : List[str] = [len(__a ) + 2 for c in columns] SCREAMING_SNAKE_CASE_ : str = max([len(__a ) for name in model_names] ) + 2 # Build the table per se SCREAMING_SNAKE_CASE_ : List[Any] = '''|''' + '''|'''.join([_center_text(__a , __a ) for c, w in zip(__a , __a )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" SCREAMING_SNAKE_CASE_ : Union[str, Any] = {True: '''✅''', False: '''❌'''} for name in model_names: SCREAMING_SNAKE_CASE_ : str = model_name_to_prefix[name] SCREAMING_SNAKE_CASE_ : int = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__a , __a ) for l, w in zip(__a , __a )] ) + "|\n" return table def _A (__a=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = _find_text_in_file( filename=os.path.join(__a , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) SCREAMING_SNAKE_CASE_ : Tuple = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__a , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
91
0
from __future__ import annotations from collections.abc import MutableSequence class lowercase : def __init__( self , A_ , A_ ) -> Union[str, Any]: """simple docstring""" if len(lowercase_ ) != degree + 1: raise ValueError( 'The number of coefficients should be equal to the degree + 1.' ) UpperCamelCase = list(lowercase_ ) UpperCamelCase = degree def __add__( self , A_ ) -> Any: """simple docstring""" if self.degree > polynomial_a.degree: UpperCamelCase = self.coefficients[:] for i in range(polynomial_a.degree + 1 ): coefficients[i] += polynomial_a.coefficients[i] return Polynomial(self.degree , lowercase_ ) else: UpperCamelCase = polynomial_a.coefficients[:] for i in range(self.degree + 1 ): coefficients[i] += self.coefficients[i] return Polynomial(polynomial_a.degree , lowercase_ ) def __sub__( self , A_ ) -> Optional[Any]: """simple docstring""" return self + polynomial_a * Polynomial(0 , [-1] ) def __neg__( self ) -> Any: """simple docstring""" return Polynomial(self.degree , [-c for c in self.coefficients] ) def __mul__( self , A_ ) -> Any: """simple docstring""" UpperCamelCase = [0] * (self.degree + polynomial_a.degree + 1) for i in range(self.degree + 1 ): for j in range(polynomial_a.degree + 1 ): coefficients[i + j] += ( self.coefficients[i] * polynomial_a.coefficients[j] ) return Polynomial(self.degree + polynomial_a.degree , lowercase_ ) def __UpperCamelCase ( self , A_ ) -> str: """simple docstring""" UpperCamelCase = 0 for i in range(self.degree + 1 ): result += self.coefficients[i] * (substitution**i) return result def __str__( self ) -> int: """simple docstring""" UpperCamelCase = '''''' for i in range(self.degree , -1 , -1 ): if self.coefficients[i] == 0: continue elif self.coefficients[i] > 0: if polynomial: polynomial += " + " else: polynomial += " - " if i == 0: polynomial += str(abs(self.coefficients[i] ) ) elif i == 1: polynomial += str(abs(self.coefficients[i] ) ) + "x" else: polynomial += str(abs(self.coefficients[i] ) ) + "x^" + str(lowercase_ ) return polynomial def __repr__( self ) -> List[str]: """simple docstring""" return self.__str__() def __UpperCamelCase ( self ) -> Dict: """simple docstring""" UpperCamelCase = [0] * self.degree for i in range(self.degree ): UpperCamelCase = self.coefficients[i + 1] * (i + 1) return Polynomial(self.degree - 1 , lowercase_ ) def __UpperCamelCase ( self , A_ = 0 ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = [0] * (self.degree + 2) UpperCamelCase = constant for i in range(self.degree + 1 ): UpperCamelCase = self.coefficients[i] / (i + 1) return Polynomial(self.degree + 1 , lowercase_ ) def __eq__( self , A_ ) -> Optional[Any]: """simple docstring""" if not isinstance(lowercase_ , lowercase_ ): return False if self.degree != polynomial_a.degree: return False for i in range(self.degree + 1 ): if self.coefficients[i] != polynomial_a.coefficients[i]: return False return True def __ne__( self , A_ ) -> List[str]: """simple docstring""" return not self.__eq__(lowercase_ )
222
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : List[str]=13 , lowercase_ : int=7 , lowercase_ : Any=True , lowercase_ : str=True , lowercase_ : List[Any]=True , lowercase_ : List[Any]=True , lowercase_ : Dict=99 , lowercase_ : Union[str, Any]=24 , lowercase_ : int=2 , lowercase_ : List[str]=6 , lowercase_ : Any=37 , lowercase_ : Dict="gelu" , lowercase_ : List[str]=0.1 , lowercase_ : Dict=0.1 , lowercase_ : Union[str, Any]=512 , lowercase_ : List[str]=16 , lowercase_ : Any=2 , lowercase_ : Any=0.02 , lowercase_ : List[Any]=3 , lowercase_ : Optional[int]=None , lowercase_ : str=1000 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE_ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE_ : Tuple = scope SCREAMING_SNAKE_CASE_ : Optional[int] = range_bbox def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : str = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[str] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : List[str] = t SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : Any = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LiltConfig( 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 , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = LiltModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = model(lowercase_ , bbox=lowercase_) 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 _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = LiltForTokenClassification(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LiltForQuestionAnswering(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) 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 _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : str , lowercase_ : str): '''simple docstring''' return True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = LiltModelTester(self) SCREAMING_SNAKE_CASE_ : Optional[int] = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : Dict = type self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[int] = LiltModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''').to(lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.tensor([[1, 2]] , device=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Dict = model(input_ids=lowercase_ , bbox=lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.Size([1, 2, 768]) SCREAMING_SNAKE_CASE_ : Dict = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=lowercase_ , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase_) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase_ , atol=1e-3))
91
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=UpperCAmelCase__ ) class SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): """simple docstring""" lowercase__ = field(default="text-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowercase__ = Features({"text": Value("string" )} ) lowercase__ = Features({"labels": ClassLabel} ) lowercase__ = "text" lowercase__ = "labels" def __lowerCAmelCase ( self : Union[str, Any] ,lowercase_ : Optional[Any] ): if self.label_column not in features: raise ValueError(F'Column {self.label_column} is not present in features.' ) if not isinstance(features[self.label_column] ,lowercase_ ): raise ValueError(F'Column {self.label_column} is not a ClassLabel.' ) lowerCAmelCase__ : str = copy.deepcopy(self ) lowerCAmelCase__ : Tuple = self.label_schema.copy() lowerCAmelCase__ : Any = features[self.label_column] lowerCAmelCase__ : Any = label_schema return task_template @property def __lowerCAmelCase ( self : str ): return { self.text_column: "text", self.label_column: "labels", }
106
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCAmelCase_ : Dict = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) UpperCAmelCase_ : Optional[Any] = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: UpperCAmelCase_ : Union[str, Any] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") UpperCAmelCase_ : Any = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase_ : List[Any] = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase_ : Dict = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
91
0
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class A_ : '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = 42 SCREAMING_SNAKE_CASE__ : Any = None # Automatically constructed SCREAMING_SNAKE_CASE__ : Optional[int] = """dict""" SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : List[str] = field(default="""Translation""" ,init=UpperCAmelCase__ ,repr=UpperCAmelCase__ ) def __call__( self ): """simple docstring""" return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def UpperCamelCase__ ( self ): """simple docstring""" from .features import Value return {k: Value("string" ) for k in sorted(self.languages )} @dataclass class A_ : '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : Tuple = None # Automatically constructed SCREAMING_SNAKE_CASE__ : List[str] = """dict""" SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Tuple = field(default="""TranslationVariableLanguages""" ,init=UpperCAmelCase__ ,repr=UpperCAmelCase__ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : str = sorted(set(self.languages ) ) if self.languages else None UpperCAmelCase_ : Any = len(self.languages ) if self.languages else None def __call__( self ): """simple docstring""" return pa.struct({"language": pa.list_(pa.string() ), "translation": pa.list_(pa.string() )} ) def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Optional[int] = set(self.languages ) if self.languages and set(lowercase_ ) - lang_set: raise ValueError( F"""Some languages in example ({", ".join(sorted(set(lowercase_ ) - lang_set ) )}) are not in valid set ({", ".join(lowercase_ )}).""" ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. UpperCAmelCase_ : int = [] for lang, text in translation_dict.items(): if isinstance(lowercase_ , lowercase_ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. UpperCAmelCase_ : str = zip(*sorted(lowercase_ ) ) return {"language": languages, "translation": translations} def UpperCamelCase__ ( self ): """simple docstring""" from .features import Sequence, Value return { "language": Sequence(Value("string" ) ), "translation": Sequence(Value("string" ) ), }
61
"""simple docstring""" from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) def _A (__a , __a ) -> Tuple: """simple docstring""" try: with open(__a , '''rb''' ) as flax_state_f: SCREAMING_SNAKE_CASE_ : Optional[int] = from_bytes(__a , flax_state_f.read() ) except UnpicklingError as e: try: with open(__a ) as f: if f.read().startswith('''version''' ): raise OSError( '''You seem to have cloned a repository without having git-lfs installed. Please''' ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the''' ''' folder you cloned.''' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(__a , __a ) def _A (__a , __a ) -> Tuple: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE_ : Optional[int] = flatten_dict(jax.tree_util.tree_map(lambda __a : x.dtype == jnp.bfloataa , __a ) ).values() if any(__a ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.tree_util.tree_map( lambda __a : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , __a ) SCREAMING_SNAKE_CASE_ : int = '''''' SCREAMING_SNAKE_CASE_ : str = flatten_dict(__a , sep='''.''' ) SCREAMING_SNAKE_CASE_ : List[Any] = pt_model.state_dict() # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Any = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple.split('''.''' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.transpose(__a , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": SCREAMING_SNAKE_CASE_ : Tuple = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[int] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": SCREAMING_SNAKE_CASE_ : Optional[int] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(__a ): SCREAMING_SNAKE_CASE_ : List[str] = ( flax_key_tuple_string.replace('''_0''' , '''.0''' ) .replace('''_1''' , '''.1''' ) .replace('''_2''' , '''.2''' ) .replace('''_3''' , '''.3''' ) .replace('''_4''' , '''.4''' ) .replace('''_5''' , '''.5''' ) .replace('''_6''' , '''.6''' ) .replace('''_7''' , '''.7''' ) .replace('''_8''' , '''.8''' ) .replace('''_9''' , '''.9''' ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = '''.'''.join(__a ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE_ : Optional[int] = np.asarray(__a ) if not isinstance(__a , np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.from_numpy(__a ) # remove from missing keys missing_keys.remove(__a ) else: # weight is not expected by PyTorch model unexpected_keys.append(__a ) pt_model.load_state_dict(__a ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE_ : int = list(__a ) if len(__a ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) if len(__a ) > 0: logger.warning( f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) return pt_model
91
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): '''simple docstring''' _UpperCAmelCase : List[str] = ["image_processor", "tokenizer"] _UpperCAmelCase : Tuple = "CLIPImageProcessor" _UpperCAmelCase : Tuple = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : List[Any] , lowercase : Dict=None , lowercase : List[str]=None , **lowercase : List[str] ): '''simple docstring''' _snake_case = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , lowercase_ , ) _snake_case = kwargs.pop('feature_extractor' ) _snake_case = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(lowercase_ , lowercase_ ) def __call__( self : str , lowercase : int=None , lowercase : int=None , lowercase : Dict=None , **lowercase : Any ): '''simple docstring''' if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: _snake_case = self.tokenizer(lowercase_ , return_tensors=lowercase_ , **lowercase_ ) if images is not None: _snake_case = self.image_processor(lowercase_ , return_tensors=lowercase_ , **lowercase_ ) if text is not None and images is not None: _snake_case = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowercase_ ) , tensor_type=lowercase_ ) def A ( self : str , *lowercase : int , **lowercase : Any ): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase_ , **lowercase_ ) def A ( self : List[str] , *lowercase : Union[str, Any] , **lowercase : Optional[int] ): '''simple docstring''' return self.tokenizer.decode(*lowercase_ , **lowercase_ ) @property def A ( self : List[str] ): '''simple docstring''' _snake_case = self.tokenizer.model_input_names _snake_case = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def A ( self : Optional[int] ): '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , lowercase_ , ) return self.image_processor_class @property def A ( self : List[str] ): '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , lowercase_ , ) return self.image_processor
282
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "openai-gpt" __UpperCamelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , lowercase_ : List[str]=40478 , lowercase_ : List[str]=512 , lowercase_ : Optional[Any]=768 , lowercase_ : Tuple=12 , lowercase_ : Tuple=12 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : List[Any]=0.1 , lowercase_ : Tuple=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : List[Any]=1e-5 , lowercase_ : int=0.02 , lowercase_ : Optional[int]="cls_index" , lowercase_ : Any=True , lowercase_ : List[Any]=None , lowercase_ : List[str]=True , lowercase_ : Optional[Any]=0.1 , **lowercase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE_ : Tuple = n_positions SCREAMING_SNAKE_CASE_ : Optional[int] = n_embd SCREAMING_SNAKE_CASE_ : Dict = n_layer SCREAMING_SNAKE_CASE_ : Any = n_head SCREAMING_SNAKE_CASE_ : Union[str, Any] = afn SCREAMING_SNAKE_CASE_ : int = resid_pdrop SCREAMING_SNAKE_CASE_ : List[str] = embd_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = attn_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = summary_type SCREAMING_SNAKE_CASE_ : Tuple = summary_use_proj SCREAMING_SNAKE_CASE_ : Union[str, Any] = summary_activation SCREAMING_SNAKE_CASE_ : Any = summary_first_dropout SCREAMING_SNAKE_CASE_ : List[str] = summary_proj_to_labels super().__init__(**lowercase_)
91
0
"""simple docstring""" import random from .binary_exp_mod import bin_exp_mod def _lowerCamelCase( a , a=1_0_0_0 ): if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd __a = n - 1 __a = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) __a = 0 while count < prec: __a = random.randint(2 , n - 1 ) __a = bin_exp_mod(__a , __a , __a ) if b != 1: __a = True for _ in range(__a ): if b == n - 1: __a = False break __a = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[Any] = abs(int(input("""Enter bound : """).strip())) print("""Here's the list of primes:""") print(""", """.join(str(i) for i in range(n + 1) if is_prime_big(i)))
261
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' warnings.warn( '''The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DeiTImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
0
import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class SCREAMING_SNAKE_CASE__ : '''simple docstring''' def __init__( self, lowerCamelCase__, lowerCamelCase__=None, lowerCamelCase__=None, lowerCamelCase__=None, lowerCamelCase__="resnet50", lowerCamelCase__=3, lowerCamelCase__=32, lowerCamelCase__=3, lowerCamelCase__=True, lowerCamelCase__=True, ): A : Dict = parent A : Tuple = out_indices if out_indices is not None else [4] A : Optional[int] = stage_names A : Any = out_features A : List[str] = backbone A : Union[str, Any] = batch_size A : Optional[Any] = image_size A : Dict = num_channels A : Any = use_pretrained_backbone A : Any = is_training def _lowerCAmelCase ( self ): A : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : List[Any] = self.get_config() return config, pixel_values def _lowerCAmelCase ( self ): return TimmBackboneConfig( image_size=self.image_size, num_channels=self.num_channels, out_features=self.out_features, out_indices=self.out_indices, stage_names=self.stage_names, use_pretrained_backbone=self.use_pretrained_backbone, backbone=self.backbone, ) def _lowerCAmelCase ( self, lowerCamelCase__, lowerCamelCase__ ): A : Any = TimmBackbone(config=lowercase_ ) model.to(lowercase_ ) model.eval() with torch.no_grad(): A : List[Any] = model(lowercase_ ) self.parent.assertEqual( result.feature_map[-1].shape, (self.batch_size, model.channels[-1], 14, 14), ) def _lowerCAmelCase ( self ): A : List[str] = self.prepare_config_and_inputs() A : Optional[Any] = config_and_inputs A : List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch @require_timm class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : Dict = (TimmBackbone,) if is_torch_available() else () __lowerCamelCase : Optional[Any] = {"feature-extraction": TimmBackbone} if is_torch_available() else {} __lowerCamelCase : Optional[int] = False __lowerCamelCase : int = False __lowerCamelCase : List[str] = False __lowerCamelCase : str = False def _lowerCAmelCase ( self ): A : Dict = TimmBackboneModelTester(self ) A : Optional[int] = ConfigTester(self, config_class=lowercase_, has_text_modality=lowercase_ ) def _lowerCAmelCase ( self ): self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _lowerCAmelCase ( self ): A : Union[str, Any] = '''resnet18''' A : List[Any] = '''microsoft/resnet-18''' A : str = AutoBackbone.from_pretrained(lowercase_, use_timm_backbone=lowercase_ ) A : str = AutoBackbone.from_pretrained(lowercase_ ) self.assertEqual(len(timm_model.out_features ), len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ), len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels, transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices, (-1,) ) self.assertEqual(transformers_model.out_indices, [len(timm_model.stage_names ) - 1] ) A : Optional[int] = AutoBackbone.from_pretrained(lowercase_, use_timm_backbone=lowercase_, out_indices=[1, 2, 3] ) A : Optional[Any] = AutoBackbone.from_pretrained(lowercase_, out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices, transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ), len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels, transformers_model.channels ) @unittest.skip("""TimmBackbone doesn\'t support feed forward chunking""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone doesn\'t have num_hidden_layers attribute""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone initialization is managed on the timm side""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone models doesn\'t have inputs_embeds""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone models doesn\'t have inputs_embeds""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""model weights aren\'t tied in TimmBackbone.""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""model weights aren\'t tied in TimmBackbone.""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone doesn\'t have hidden size info in its configuration.""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""TimmBackbone doesn\'t support output_attentions.""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""Safetensors is not supported by timm.""" ) def _lowerCAmelCase ( self ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _lowerCAmelCase ( self ): pass def _lowerCAmelCase ( self ): A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : Optional[int] = model_class(lowercase_ ) A : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : Optional[Any] = [*signature.parameters.keys()] A : Optional[int] = ['''pixel_values'''] self.assertListEqual(arg_names[:1], lowercase_ ) def _lowerCAmelCase ( self ): A : List[str] = self.model_tester.prepare_config_and_inputs_for_common() A : List[str] = True A : Optional[Any] = self.has_attentions # no need to test all models as different heads yield the same functionality A : Optional[int] = self.all_model_classes[0] A : List[Any] = model_class(lowercase_ ) model.to(lowercase_ ) A : Optional[Any] = self._prepare_for_class(lowercase_, lowercase_ ) A : List[str] = model(**lowercase_ ) A : int = outputs[0][-1] # Encoder-/Decoder-only models A : List[str] = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: A : Any = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=lowercase_ ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def _lowerCAmelCase ( self ): A : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : int = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() A : int = model(**lowercase_ ) self.assertEqual(len(result.feature_maps ), len(config.out_indices ) ) self.assertEqual(len(model.channels ), len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None A : List[str] = copy.deepcopy(lowercase_ ) A : int = None A : Any = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() A : Union[str, Any] = model(**lowercase_ ) self.assertEqual(len(result.feature_maps ), 1 ) self.assertEqual(len(model.channels ), 1 ) # Check backbone can be initialized with fresh weights A : int = copy.deepcopy(lowercase_ ) A : List[str] = False A : Any = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() A : Dict = model(**lowercase_ )
116
"""simple docstring""" import random from typing import Any def _A (__a ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ : Tuple = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = data[b], data[a] return data if __name__ == "__main__": UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5, 6, 7] UpperCAmelCase_ : Dict = ["""python""", """says""", """hello""", """!"""] print("""Fisher-Yates Shuffle:""") print("""List""", integers, strings) print("""FY Shuffle""", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
91
0
from ....configuration_utils import PretrainedConfig from ....utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """speechbrain/m-ctc-t-large""": """https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json""", # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class snake_case__(UpperCAmelCase__ ): """simple docstring""" lowercase_ = """mctct""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE : str=8_065 , SCREAMING_SNAKE_CASE : Optional[Any]=1_536 , SCREAMING_SNAKE_CASE : str=36 , SCREAMING_SNAKE_CASE : List[str]=6_144 , SCREAMING_SNAKE_CASE : Optional[Any]=4 , SCREAMING_SNAKE_CASE : Optional[Any]=384 , SCREAMING_SNAKE_CASE : Tuple=920 , SCREAMING_SNAKE_CASE : Any=1E-5 , SCREAMING_SNAKE_CASE : Optional[Any]=0.3 , SCREAMING_SNAKE_CASE : Any="relu" , SCREAMING_SNAKE_CASE : Any=0.02 , SCREAMING_SNAKE_CASE : Dict=0.3 , SCREAMING_SNAKE_CASE : int=0.3 , SCREAMING_SNAKE_CASE : Union[str, Any]=1 , SCREAMING_SNAKE_CASE : Union[str, Any]=0 , SCREAMING_SNAKE_CASE : Union[str, Any]=2 , SCREAMING_SNAKE_CASE : Union[str, Any]=1 , SCREAMING_SNAKE_CASE : List[str]=0.3 , SCREAMING_SNAKE_CASE : Optional[int]=1 , SCREAMING_SNAKE_CASE : Dict=(7,) , SCREAMING_SNAKE_CASE : Union[str, Any]=(3,) , SCREAMING_SNAKE_CASE : Tuple=80 , SCREAMING_SNAKE_CASE : Union[str, Any]=1 , SCREAMING_SNAKE_CASE : Any=None , SCREAMING_SNAKE_CASE : Any="sum" , SCREAMING_SNAKE_CASE : List[Any]=False , **SCREAMING_SNAKE_CASE : Any , ): super().__init__(**lowercase_ , pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ ) lowercase__ : str = vocab_size lowercase__ : Optional[int] = hidden_size lowercase__ : int = num_hidden_layers lowercase__ : List[Any] = intermediate_size lowercase__ : List[str] = num_attention_heads lowercase__ : Any = attention_head_dim lowercase__ : int = max_position_embeddings lowercase__ : List[str] = layer_norm_eps lowercase__ : Union[str, Any] = layerdrop lowercase__ : str = hidden_act lowercase__ : List[Any] = initializer_range lowercase__ : Optional[int] = hidden_dropout_prob lowercase__ : Tuple = attention_probs_dropout_prob lowercase__ : Tuple = pad_token_id lowercase__ : Tuple = bos_token_id lowercase__ : int = eos_token_id lowercase__ : Optional[Any] = conv_glu_dim lowercase__ : List[str] = conv_dropout lowercase__ : Optional[Any] = num_conv_layers lowercase__ : Tuple = input_feat_per_channel lowercase__ : Optional[int] = input_channels lowercase__ : List[str] = conv_channels lowercase__ : Union[str, Any] = ctc_loss_reduction lowercase__ : str = ctc_zero_infinity # prevents config testing fail with exporting to json lowercase__ : Optional[Any] = list(lowercase_ ) lowercase__ : Tuple = list(lowercase_ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.conv_kernel)` == `config.num_conv_layers` " f"""but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, """ f"""`config.num_conv_layers = {self.num_conv_layers}`.""" )
130
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _A (__a , __a , __a ) -> Dict: """simple docstring""" if gpta_config_file == "": SCREAMING_SNAKE_CASE_ : Optional[Any] = GPTaConfig() else: SCREAMING_SNAKE_CASE_ : Tuple = GPTaConfig.from_json_file(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = GPTaModel(__a ) # Load weights from numpy load_tf_weights_in_gpta(__a , __a , __a ) # Save pytorch-model SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : List[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , __a ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow 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( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
91
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 SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) if is_vision_available(): import PIL class A__ ( UpperCAmelCase__ ): lowerCAmelCase__ : Optional[int] = ["pixel_values"] def __init__( self : Dict , _UpperCAmelCase : bool = True , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _UpperCAmelCase : bool = True , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : bool = True , _UpperCAmelCase : Union[int, float] = 1 / 2_55 , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : bool = True , **_UpperCAmelCase : Any , ) -> List[str]: """simple docstring""" super().__init__(**lowercase_ ) __lowercase = size if size is not None else {'''shortest_edge''': 2_24} __lowercase = get_size_dict(lowercase_ , default_to_square=lowercase_ ) __lowercase = crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24} __lowercase = get_size_dict(lowercase_ , default_to_square=lowercase_ , 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 a__ ( self : List[Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Dict[str, int] , _UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Optional[Any] , ) -> Any: """simple docstring""" __lowercase = get_size_dict(lowercase_ , default_to_square=lowercase_ ) 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(lowercase_ , size=size['shortest_edge'] , default_to_square=lowercase_ ) return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_ ) def a__ ( self : str , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Dict[str, int] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Dict , ) -> Dict: """simple docstring""" __lowercase = get_size_dict(lowercase_ ) 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(lowercase_ , size=(size['height'], size['width']) , data_format=lowercase_ , **lowercase_ ) def a__ ( self : Optional[Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[int, float] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : List[Any] , ) -> Optional[int]: """simple docstring""" return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_ ) def a__ ( self : Any , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Dict , ) -> Union[str, Any]: """simple docstring""" return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_ ) def a__ ( self : Dict , _UpperCAmelCase : ImageInput , _UpperCAmelCase : bool = None , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : int = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : float = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Optional[Union[str, TensorType]] = None , _UpperCAmelCase : Optional[ChannelDimension] = ChannelDimension.FIRST , **_UpperCAmelCase : Union[str, Any] , ) -> Tuple: """simple docstring""" __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(lowercase_ , param_name='size' , default_to_square=lowercase_ ) __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(lowercase_ , param_name='crop_size' , default_to_square=lowercase_ ) __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(lowercase_ ) if not valid_images(lowercase_ ): 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(lowercase_ ) for image in images] # All transformations expect numpy arrays. __lowercase = [to_numpy_array(lowercase_ ) for image in images] if do_resize: __lowercase = [self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_ ) for image in images] if do_center_crop: __lowercase = [self.center_crop(image=lowercase_ , size=lowercase_ ) for image in images] if do_rescale: __lowercase = [self.rescale(image=lowercase_ , scale=lowercase_ ) for image in images] if do_normalize: __lowercase = [self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_ ) for image in images] __lowercase = [to_channel_dimension_format(lowercase_ , lowercase_ ) for image in images] __lowercase = {'''pixel_values''': images} return BatchFeature(data=lowercase_ , tensor_type=lowercase_ )
325
"""simple docstring""" from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
91
0
'''simple docstring''' def __UpperCAmelCase ( a_: List[str] = 1_000_000 ): _UpperCAmelCase : Any = 1 _UpperCAmelCase : Optional[int] = 1 _UpperCAmelCase : str = {1: 1} for inputa in range(2, __a ): _UpperCAmelCase : Optional[Any] = 0 _UpperCAmelCase : Dict = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: _UpperCAmelCase : Dict = (3 * number) + 1 counter += 1 if inputa not in counters: _UpperCAmelCase : Dict = counter if counter > pre_counter: _UpperCAmelCase : Tuple = inputa _UpperCAmelCase : Optional[int] = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
145
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType 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, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' 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_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.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
0
"""simple docstring""" from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) a :Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name a :Optional[Any] = """ Examples: ```py >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\") >>> pipe_prior.to(\"cuda\") >>> prompt = \"red cat, 4k photo\" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> zero_image_emb = out.negative_image_embeds >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\") >>> pipe.to(\"cuda\") >>> image = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=50, ... ).images >>> image[0].save(\"cat.png\") ``` """ def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=8 ) -> List[str]: SCREAMING_SNAKE_CASE__ : Any = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE__ : Any = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class __a (UpperCAmelCase__): '''simple docstring''' def __init__( self , _a , _a , _a , ) -> str: """simple docstring""" super().__init__() self.register_modules( unet=lowercase_ , scheduler=lowercase_ , movq=lowercase_ , ) SCREAMING_SNAKE_CASE__ : Tuple = 2 ** (len(self.movq.config.block_out_channels ) - 1) def _a ( self , _a , _a , _a , _a , _a , _a ) -> Optional[int]: """simple docstring""" if latents is None: SCREAMING_SNAKE_CASE__ : Optional[Any] = randn_tensor(lowercase_ , generator=lowercase_ , device=lowercase_ , dtype=lowercase_ ) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = latents.to(lowercase_ ) SCREAMING_SNAKE_CASE__ : Any = latents * scheduler.init_noise_sigma return latents def _a ( self , _a=0 ) -> List[str]: """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) SCREAMING_SNAKE_CASE__ : Dict = torch.device(f'''cuda:{gpu_id}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowercase_ , lowercase_ ) def _a ( self , _a=0 ) -> Union[str, Any]: """simple docstring""" if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) SCREAMING_SNAKE_CASE__ : Tuple = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=lowercase_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE__ : int = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE__ : Tuple = cpu_offload_with_hook(lowercase_ , lowercase_ , prev_module_hook=lowercase_ ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE__ : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _a ( self ) -> List[str]: """simple docstring""" if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(lowercase_ , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(lowercase_ ) def __call__( self , _a , _a , _a = 512 , _a = 512 , _a = 100 , _a = 4.0 , _a = 1 , _a = None , _a = None , _a = "pil" , _a = True , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self._execution_device SCREAMING_SNAKE_CASE__ : Optional[int] = guidance_scale > 1.0 if isinstance(lowercase_ , lowercase_ ): SCREAMING_SNAKE_CASE__ : List[str] = torch.cat(lowercase_ , dim=0 ) SCREAMING_SNAKE_CASE__ : int = image_embeds.shape[0] * num_images_per_prompt if isinstance(lowercase_ , lowercase_ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat(lowercase_ , dim=0 ) if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ : Optional[int] = image_embeds.repeat_interleave(lowercase_ , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = negative_image_embeds.repeat_interleave(lowercase_ , dim=0 ) SCREAMING_SNAKE_CASE__ : Any = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=lowercase_ ) self.scheduler.set_timesteps(lowercase_ , device=lowercase_ ) SCREAMING_SNAKE_CASE__ : str = self.scheduler.timesteps SCREAMING_SNAKE_CASE__ : Any = self.unet.config.in_channels SCREAMING_SNAKE_CASE__ : Optional[int] = downscale_height_and_width(lowercase_ , lowercase_ , self.movq_scale_factor ) # create initial latent SCREAMING_SNAKE_CASE__ : Dict = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , lowercase_ , lowercase_ , lowercase_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowercase_ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE__ : str = {'''image_embeds''': image_embeds} SCREAMING_SNAKE_CASE__ : Optional[Any] = self.unet( sample=lowercase_ , timestep=lowercase_ , encoder_hidden_states=lowercase_ , added_cond_kwargs=lowercase_ , return_dict=lowercase_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ : str = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE__ : Optional[int] = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE__ : List[str] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE__ : Tuple = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE__ : Optional[int] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler.step( lowercase_ , lowercase_ , lowercase_ , generator=lowercase_ , )[0] # post-processing SCREAMING_SNAKE_CASE__ : Any = self.movq.decode(lowercase_ , force_not_quantize=lowercase_ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE__ : Any = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE__ : Optional[Any] = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ : int = self.numpy_to_pil(lowercase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowercase_ )
132
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase_ : Dict = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } UpperCAmelCase_ : List[str] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = GPTaTokenizer def __init__( self : Optional[int] , lowercase_ : int=None , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple="<|endoftext|>" , lowercase_ : str="<|endoftext|>" , lowercase_ : Dict="<|endoftext|>" , lowercase_ : Tuple=False , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , lowercase_ , tokenizer_file=lowercase_ , unk_token=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , add_prefix_space=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''add_bos_token''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('''add_prefix_space''' , lowercase_) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase_ , pre_tok_state.pop('''type''')) SCREAMING_SNAKE_CASE_ : str = add_prefix_space SCREAMING_SNAKE_CASE_ : Dict = pre_tok_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = add_prefix_space def _SCREAMING_SNAKE_CASE ( self : str , *lowercase_ : List[Any] , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''is_split_into_words''' , lowercase_) assert self.add_prefix_space or not is_split_into_words, ( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : List[str] , **lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.get('''is_split_into_words''' , lowercase_) assert self.add_prefix_space or not is_split_into_words, ( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._encode_plus(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self._tokenizer.model.save(lowercase_ , name=lowercase_) return tuple(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : "Conversation"): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase_ , add_special_tokens=lowercase_) + [self.eos_token_id]) if len(lowercase_) > self.model_max_length: SCREAMING_SNAKE_CASE_ : Any = input_ids[-self.model_max_length :] return input_ids
91
0
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase : Tuple = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class A__ ( UpperCAmelCase__ , unittest.TestCase ): A__ = XLNetTokenizer A__ = XLNetTokenizerFast A__ = True A__ = True def A ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing _SCREAMING_SNAKE_CASE =XLNetTokenizer(lowercase_ , keep_accents=lowercase_ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def A ( self : Optional[int] ) -> Tuple: '''simple docstring''' _SCREAMING_SNAKE_CASE ='''<s>''' _SCREAMING_SNAKE_CASE =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_ ) , lowercase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_ ) , lowercase_ ) def A ( self : Optional[Any] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<eod>' ) self.assertEqual(len(lowercase_ ) , 1006 ) def A ( self : Tuple ) -> str: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def A ( self : Optional[int] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =XLNetTokenizer(lowercase_ , keep_accents=lowercase_ ) _SCREAMING_SNAKE_CASE =tokenizer.tokenize('This is a test' ) self.assertListEqual(lowercase_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_ ) , [285, 46, 10, 170, 382] ) _SCREAMING_SNAKE_CASE =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) _SCREAMING_SNAKE_CASE =tokenizer.convert_tokens_to_ids(lowercase_ ) self.assertListEqual(lowercase_ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) _SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(lowercase_ ) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def A ( self : Dict ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =XLNetTokenizer(lowercase_ , do_lower_case=lowercase_ ) _SCREAMING_SNAKE_CASE =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + '', 'i', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 'se', '.', ] , ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['▁he', 'll', 'o'] ) def A ( self : Optional[Any] ) -> Any: '''simple docstring''' _SCREAMING_SNAKE_CASE =XLNetTokenizer(lowercase_ , do_lower_case=lowercase_ ) _SCREAMING_SNAKE_CASE =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 'se', '.', ] , ) @slow def A ( self : Dict ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =XLNetTokenizer.from_pretrained('xlnet-base-cased' ) _SCREAMING_SNAKE_CASE =tokenizer.encode('sequence builders' , add_special_tokens=lowercase_ ) _SCREAMING_SNAKE_CASE =tokenizer.encode('multi-sequence build' , add_special_tokens=lowercase_ ) _SCREAMING_SNAKE_CASE =tokenizer.build_inputs_with_special_tokens(lowercase_ ) _SCREAMING_SNAKE_CASE =tokenizer.build_inputs_with_special_tokens(lowercase_ , lowercase_ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def A ( self : int ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE ={'''input_ids''': [[17, 2_1442, 270, 17, 10, 1_4645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 2_2018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 1_4431, 13, 5500, 11, 1176, 580, 13, 1_6819, 4797, 23, 17, 10, 1_7135, 658, 19, 457, 7932, 13, 184, 19, 3154, 1_7135, 6468, 19, 1404, 1_2269, 19, 4229, 5356, 1_6264, 46, 19, 17, 2_0545, 1_0395, 9, 9, 9, 11, 28, 6421, 9531, 2_0729, 17, 10, 353, 1_7022, 11, 21, 6421, 9531, 1_6949, 17, 10, 1_1509, 753, 11, 33, 95, 2421, 7385, 956, 1_4431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 2_4738, 19, 1_3203, 658, 218, 787, 21, 430, 1_8482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 2_2178, 27, 1064, 22, 956, 13, 1_1101, 1429, 5854, 2_4313, 1_8953, 40, 422, 2_4366, 68, 1758, 37, 1_0483, 1_4257, 31, 207, 263, 21, 203, 3773, 25, 71, 9735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2049, 3442, 17, 1_3894, 3380, 23, 95, 18, 1_7634, 2288, 9, 4, 3]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase_ , model_name='xlnet-base-cased' , revision='c841166438c31ec7ca9a106dee7bb312b73ae511' , )
47
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(lowercase_ , '''hidden_sizes''')) self.parent.assertTrue(hasattr(lowercase_ , '''num_attention_heads''')) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Union[str, Any] , lowercase_ : List[Any]=13 , lowercase_ : Dict=64 , lowercase_ : Dict=3 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=2 , lowercase_ : Any=1 , lowercase_ : List[Any]=16 , lowercase_ : int=[128, 256, 384] , lowercase_ : str=[4, 6, 8] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Union[str, Any]=[16, 16, 16] , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[int]=[2, 2, 2] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=0.02 , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[int]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = kernel_size SCREAMING_SNAKE_CASE_ : Optional[Any] = stride SCREAMING_SNAKE_CASE_ : List[str] = padding SCREAMING_SNAKE_CASE_ : int = hidden_sizes SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : int = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = key_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_ratio SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = LevitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1) SCREAMING_SNAKE_CASE_ : Dict = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4) * ceil(width / 4), self.hidden_sizes[-1]) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitModelTester(self) SCREAMING_SNAKE_CASE_ : List[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return @unittest.skip(reason='''Levit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : str = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.model_tester.depths) + 1 self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) SCREAMING_SNAKE_CASE_ : Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) model.gradient_checkpointing_enable() model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowercase_), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'): SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''title'''] SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''num_labels'''] SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_ : str = inputs['''labels'''].unsqueeze(1).repeat(1 , problem_type['''num_labels''']) SCREAMING_SNAKE_CASE_ : Any = inputs['''labels'''].to(problem_type['''dtype''']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowercase_) as warning_list: SCREAMING_SNAKE_CASE_ : int = model(**lowercase_).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'Something is going wrong in the regression problem: intercepted {w.message}') loss.backward() @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = LevitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([1.04_48, -0.37_45, -1.83_17]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
91
0
import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class lowercase ( unittest.TestCase ): def __UpperCamelCase ( self ) -> List[str]: """simple docstring""" UpperCamelCase = { '''task_specific_params''': { '''summarization''': {'''length_penalty''': 1.0, '''max_length''': 128, '''min_length''': 12, '''num_beams''': 4}, '''summarization_cnn''': {'''length_penalty''': 2.0, '''max_length''': 142, '''min_length''': 56, '''num_beams''': 4}, '''summarization_xsum''': {'''length_penalty''': 1.0, '''max_length''': 62, '''min_length''': 11, '''num_beams''': 6}, } } UpperCamelCase = { '''task_specific_params.summarization.length_penalty''': 1.0, '''task_specific_params.summarization.max_length''': 128, '''task_specific_params.summarization.min_length''': 12, '''task_specific_params.summarization.num_beams''': 4, '''task_specific_params.summarization_cnn.length_penalty''': 2.0, '''task_specific_params.summarization_cnn.max_length''': 142, '''task_specific_params.summarization_cnn.min_length''': 56, '''task_specific_params.summarization_cnn.num_beams''': 4, '''task_specific_params.summarization_xsum.length_penalty''': 1.0, '''task_specific_params.summarization_xsum.max_length''': 62, '''task_specific_params.summarization_xsum.min_length''': 11, '''task_specific_params.summarization_xsum.num_beams''': 6, } self.assertEqual(flatten_dict(lowercase_ ) , lowercase_ ) def __UpperCamelCase ( self ) -> int: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(lowercase_ ) , x.transpose() ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(lowercase_ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def __UpperCamelCase ( self ) -> int: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = torch.tensor(lowercase_ ) self.assertTrue(np.allclose(transpose(lowercase_ ) , transpose(lowercase_ ).numpy() ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = torch.tensor(lowercase_ ) self.assertTrue(np.allclose(transpose(lowercase_ , axes=(1, 2, 0) ) , transpose(lowercase_ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = tf.constant(lowercase_ ) self.assertTrue(np.allclose(transpose(lowercase_ ) , transpose(lowercase_ ).numpy() ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = tf.constant(lowercase_ ) self.assertTrue(np.allclose(transpose(lowercase_ , axes=(1, 2, 0) ) , transpose(lowercase_ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def __UpperCamelCase ( self ) -> str: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = jnp.array(lowercase_ ) self.assertTrue(np.allclose(transpose(lowercase_ ) , np.asarray(transpose(lowercase_ ) ) ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = jnp.array(lowercase_ ) self.assertTrue(np.allclose(transpose(lowercase_ , axes=(1, 2, 0) ) , np.asarray(transpose(lowercase_ , axes=(1, 2, 0) ) ) ) ) def __UpperCamelCase ( self ) -> str: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(lowercase_ , (4, 3) ) , np.reshape(lowercase_ , (4, 3) ) ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(lowercase_ , (12, 5) ) , np.reshape(lowercase_ , (12, 5) ) ) ) @require_torch def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = torch.tensor(lowercase_ ) self.assertTrue(np.allclose(reshape(lowercase_ , (4, 3) ) , reshape(lowercase_ , (4, 3) ).numpy() ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = torch.tensor(lowercase_ ) self.assertTrue(np.allclose(reshape(lowercase_ , (12, 5) ) , reshape(lowercase_ , (12, 5) ).numpy() ) ) @require_tf def __UpperCamelCase ( self ) -> int: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = tf.constant(lowercase_ ) self.assertTrue(np.allclose(reshape(lowercase_ , (4, 3) ) , reshape(lowercase_ , (4, 3) ).numpy() ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = tf.constant(lowercase_ ) self.assertTrue(np.allclose(reshape(lowercase_ , (12, 5) ) , reshape(lowercase_ , (12, 5) ).numpy() ) ) @require_flax def __UpperCamelCase ( self ) -> Any: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = jnp.array(lowercase_ ) self.assertTrue(np.allclose(reshape(lowercase_ , (4, 3) ) , np.asarray(reshape(lowercase_ , (4, 3) ) ) ) ) UpperCamelCase = np.random.randn(3 , 4 , 5 ) UpperCamelCase = jnp.array(lowercase_ ) self.assertTrue(np.allclose(reshape(lowercase_ , (12, 5) ) , np.asarray(reshape(lowercase_ , (12, 5) ) ) ) ) def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(lowercase_ ) , np.squeeze(lowercase_ ) ) ) UpperCamelCase = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(lowercase_ , axis=2 ) , np.squeeze(lowercase_ , axis=2 ) ) ) @require_torch def __UpperCamelCase ( self ) -> Any: """simple docstring""" UpperCamelCase = np.random.randn(1 , 3 , 4 ) UpperCamelCase = torch.tensor(lowercase_ ) self.assertTrue(np.allclose(squeeze(lowercase_ ) , squeeze(lowercase_ ).numpy() ) ) UpperCamelCase = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase = torch.tensor(lowercase_ ) self.assertTrue(np.allclose(squeeze(lowercase_ , axis=2 ) , squeeze(lowercase_ , axis=2 ).numpy() ) ) @require_tf def __UpperCamelCase ( self ) -> List[str]: """simple docstring""" UpperCamelCase = np.random.randn(1 , 3 , 4 ) UpperCamelCase = tf.constant(lowercase_ ) self.assertTrue(np.allclose(squeeze(lowercase_ ) , squeeze(lowercase_ ).numpy() ) ) UpperCamelCase = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase = tf.constant(lowercase_ ) self.assertTrue(np.allclose(squeeze(lowercase_ , axis=2 ) , squeeze(lowercase_ , axis=2 ).numpy() ) ) @require_flax def __UpperCamelCase ( self ) -> Tuple: """simple docstring""" UpperCamelCase = np.random.randn(1 , 3 , 4 ) UpperCamelCase = jnp.array(lowercase_ ) self.assertTrue(np.allclose(squeeze(lowercase_ ) , np.asarray(squeeze(lowercase_ ) ) ) ) UpperCamelCase = np.random.randn(1 , 4 , 1 , 5 ) UpperCamelCase = jnp.array(lowercase_ ) self.assertTrue(np.allclose(squeeze(lowercase_ , axis=2 ) , np.asarray(squeeze(lowercase_ , axis=2 ) ) ) ) def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(lowercase_ , axis=1 ) , np.expand_dims(lowercase_ , axis=1 ) ) ) @require_torch def __UpperCamelCase ( self ) -> str: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = torch.tensor(lowercase_ ) self.assertTrue(np.allclose(expand_dims(lowercase_ , axis=1 ) , expand_dims(lowercase_ , axis=1 ).numpy() ) ) @require_tf def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = tf.constant(lowercase_ ) self.assertTrue(np.allclose(expand_dims(lowercase_ , axis=1 ) , expand_dims(lowercase_ , axis=1 ).numpy() ) ) @require_flax def __UpperCamelCase ( self ) -> Tuple: """simple docstring""" UpperCamelCase = np.random.randn(3 , 4 ) UpperCamelCase = jnp.array(lowercase_ ) self.assertTrue(np.allclose(expand_dims(lowercase_ , axis=1 ) , np.asarray(expand_dims(lowercase_ , axis=1 ) ) ) )
222
"""simple docstring""" from math import factorial def _A (__a = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[str] = n // 2 return int(factorial(__a ) / (factorial(__a ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCAmelCase_ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
91
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def __SCREAMING_SNAKE_CASE ( A_ ): lowerCAmelCase__ : Union[str, Any] = SwinvaConfig() lowerCAmelCase__ : Optional[Any] = swinva_name.split('''_''' ) lowerCAmelCase__ : int = name_split[1] if "to" in name_split[3]: lowerCAmelCase__ : str = int(name_split[3][-3:] ) else: lowerCAmelCase__ : Any = int(name_split[3] ) if "to" in name_split[2]: lowerCAmelCase__ : Tuple = int(name_split[2][-2:] ) else: lowerCAmelCase__ : Dict = int(name_split[2][6:] ) if model_size == "tiny": lowerCAmelCase__ : int = 96 lowerCAmelCase__ : Dict = (2, 2, 6, 2) lowerCAmelCase__ : Union[str, Any] = (3, 6, 12, 24) elif model_size == "small": lowerCAmelCase__ : Union[str, Any] = 96 lowerCAmelCase__ : Optional[int] = (2, 2, 18, 2) lowerCAmelCase__ : int = (3, 6, 12, 24) elif model_size == "base": lowerCAmelCase__ : Optional[Any] = 1_28 lowerCAmelCase__ : Optional[Any] = (2, 2, 18, 2) lowerCAmelCase__ : Any = (4, 8, 16, 32) else: lowerCAmelCase__ : Optional[int] = 1_92 lowerCAmelCase__ : Union[str, Any] = (2, 2, 18, 2) lowerCAmelCase__ : Optional[Any] = (6, 12, 24, 48) if "to" in swinva_name: lowerCAmelCase__ : Dict = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): lowerCAmelCase__ : List[str] = 2_18_41 lowerCAmelCase__ : List[str] = '''huggingface/label-files''' lowerCAmelCase__ : Any = '''imagenet-22k-id2label.json''' lowerCAmelCase__ : Optional[int] = json.load(open(hf_hub_download(__a , __a , repo_type='''dataset''' ) , '''r''' ) ) lowerCAmelCase__ : int = {int(__a ): v for k, v in idalabel.items()} lowerCAmelCase__ : str = idalabel lowerCAmelCase__ : Tuple = {v: k for k, v in idalabel.items()} else: lowerCAmelCase__ : Any = 10_00 lowerCAmelCase__ : Tuple = '''huggingface/label-files''' lowerCAmelCase__ : Any = '''imagenet-1k-id2label.json''' lowerCAmelCase__ : List[Any] = json.load(open(hf_hub_download(__a , __a , repo_type='''dataset''' ) , '''r''' ) ) lowerCAmelCase__ : List[str] = {int(__a ): v for k, v in idalabel.items()} lowerCAmelCase__ : List[str] = idalabel lowerCAmelCase__ : Union[str, Any] = {v: k for k, v in idalabel.items()} lowerCAmelCase__ : Dict = img_size lowerCAmelCase__ : Union[str, Any] = num_classes lowerCAmelCase__ : Union[str, Any] = embed_dim lowerCAmelCase__ : str = depths lowerCAmelCase__ : Optional[Any] = num_heads lowerCAmelCase__ : str = window_size return config def __SCREAMING_SNAKE_CASE ( A_ ): if "patch_embed.proj" in name: lowerCAmelCase__ : Union[str, Any] = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: lowerCAmelCase__ : Dict = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: lowerCAmelCase__ : Tuple = '''encoder.''' + name if "attn.proj" in name: lowerCAmelCase__ : Optional[int] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: lowerCAmelCase__ : List[str] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: lowerCAmelCase__ : Optional[int] = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: lowerCAmelCase__ : str = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: lowerCAmelCase__ : Any = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: lowerCAmelCase__ : Tuple = name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: lowerCAmelCase__ : Dict = name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: lowerCAmelCase__ : Union[str, Any] = name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: lowerCAmelCase__ : Tuple = name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: lowerCAmelCase__ : Dict = name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": lowerCAmelCase__ : Optional[Any] = '''layernorm.weight''' if name == "norm.bias": lowerCAmelCase__ : Tuple = '''layernorm.bias''' if "head" in name: lowerCAmelCase__ : Any = name.replace('''head''' , '''classifier''' ) else: lowerCAmelCase__ : str = '''swinv2.''' + name return name def __SCREAMING_SNAKE_CASE ( A_ , A_ ): for key in orig_state_dict.copy().keys(): lowerCAmelCase__ : Optional[Any] = orig_state_dict.pop(__a ) if "mask" in key: continue elif "qkv" in key: lowerCAmelCase__ : Dict = key.split('''.''' ) lowerCAmelCase__ : Union[str, Any] = int(key_split[1] ) lowerCAmelCase__ : Union[str, Any] = int(key_split[3] ) lowerCAmelCase__ : Union[str, Any] = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: lowerCAmelCase__ : Optional[Any] = val[:dim, :] lowerCAmelCase__ : List[str] = val[dim : dim * 2, :] lowerCAmelCase__ : Dict = val[-dim:, :] else: lowerCAmelCase__ : Any = val[:dim] lowerCAmelCase__ : List[str] = val[ dim : dim * 2 ] lowerCAmelCase__ : List[str] = val[-dim:] else: lowerCAmelCase__ : Dict = val return orig_state_dict def __SCREAMING_SNAKE_CASE ( A_ , A_ ): lowerCAmelCase__ : Optional[int] = timm.create_model(__a , pretrained=__a ) timm_model.eval() lowerCAmelCase__ : int = get_swinva_config(__a ) lowerCAmelCase__ : Any = SwinvaForImageClassification(__a ) model.eval() lowerCAmelCase__ : Any = convert_state_dict(timm_model.state_dict() , __a ) model.load_state_dict(__a ) lowerCAmelCase__ : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowerCAmelCase__ : List[Any] = AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) lowerCAmelCase__ : Tuple = Image.open(requests.get(__a , stream=__a ).raw ) lowerCAmelCase__ : int = image_processor(images=__a , return_tensors='''pt''' ) lowerCAmelCase__ : Union[str, Any] = timm_model(inputs['''pixel_values'''] ) lowerCAmelCase__ : Tuple = model(**__a ).logits assert torch.allclose(__a , __a , atol=1e-3 ) print(f'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(__a ) model.push_to_hub( repo_path_or_name=Path(__a , __a ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": __UpperCamelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) __UpperCamelCase : int = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
106
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCAmelCase_ : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *lowercase_ : List[str] , **lowercase_ : List[str]): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
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 A_ (UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 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
61
"""simple docstring""" from __future__ import annotations class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : int = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = key def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : int = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[str] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[Any] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''encrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(lowercase_ , lowercase_)) except OSError: return False return True def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''decrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(lowercase_ , lowercase_)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
91
0
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def a_ ( __lowercase : Tuple = "isbn/0140328726" ) -> dict: _snake_case = olid.strip().strip('/' ) # Remove leading/trailing whitespace & slashes if new_olid.count('/' ) != 1: _snake_case = f'''{olid} is not a valid Open Library olid''' raise ValueError(__a ) return requests.get(f'''https://openlibrary.org/{new_olid}.json''' ).json() def a_ ( __lowercase : Any ) -> dict: _snake_case = { '''title''': '''Title''', '''publish_date''': '''Publish date''', '''authors''': '''Authors''', '''number_of_pages''': '''Number of pages:''', '''first_sentence''': '''First sentence''', '''isbn_10''': '''ISBN (10)''', '''isbn_13''': '''ISBN (13)''', } _snake_case = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} _snake_case = [ get_openlibrary_data(author['key'] )['''name'''] for author in data['''Authors'''] ] _snake_case = data['''First sentence''']['''value'''] for key, value in data.items(): if isinstance(__a , __a ): _snake_case = ''', '''.join(__a ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: _lowerCamelCase : Optional[Any] = input('''\nEnter the ISBN code to search (or \'quit\' to stop): ''').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(F'Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.') continue print(F'\nSearching Open Library for ISBN: {isbn}...\n') try: _lowerCamelCase : List[str] = summarize_book(get_openlibrary_data(F'isbn/{isbn}')) print('''\n'''.join(F'{key}: {value}' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(F'Sorry, there are no results for ISBN: {isbn}.')
282
"""simple docstring""" def _A (__a = 50 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'''{solution() = }''')
91
0
"""simple docstring""" from math import pi, sqrt, tan def _lowerCamelCase( a ): if side_length < 0: raise ValueError("surface_area_cube() only accepts non-negative values" ) return 6 * side_length**2 def _lowerCamelCase( a , a , a ): if length < 0 or breadth < 0 or height < 0: raise ValueError("surface_area_cuboid() only accepts non-negative values" ) return 2 * ((length * breadth) + (breadth * height) + (length * height)) def _lowerCamelCase( a ): if radius < 0: raise ValueError("surface_area_sphere() only accepts non-negative values" ) return 4 * pi * radius**2 def _lowerCamelCase( a ): if radius < 0: raise ValueError("surface_area_hemisphere() only accepts non-negative values" ) return 3 * pi * radius**2 def _lowerCamelCase( a , a ): if radius < 0 or height < 0: raise ValueError("surface_area_cone() only accepts non-negative values" ) return pi * radius * (radius + (height**2 + radius**2) ** 0.5) def _lowerCamelCase( a , a , a ): if radius_a < 0 or radius_a < 0 or height < 0: raise ValueError( "surface_area_conical_frustum() only accepts non-negative values" ) __a = (height**2 + (radius_a - radius_a) ** 2) ** 0.5 return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2) def _lowerCamelCase( a , a ): if radius < 0 or height < 0: raise ValueError("surface_area_cylinder() only accepts non-negative values" ) return 2 * pi * radius * (height + radius) def _lowerCamelCase( a , a ): if torus_radius < 0 or tube_radius < 0: raise ValueError("surface_area_torus() only accepts non-negative values" ) if torus_radius < tube_radius: raise ValueError( "surface_area_torus() does not support spindle or self intersecting tori" ) return 4 * pow(__a , 2 ) * torus_radius * tube_radius def _lowerCamelCase( a , a ): if length < 0 or width < 0: raise ValueError("area_rectangle() only accepts non-negative values" ) return length * width def _lowerCamelCase( a ): if side_length < 0: raise ValueError("area_square() only accepts non-negative values" ) return side_length**2 def _lowerCamelCase( a , a ): if base < 0 or height < 0: raise ValueError("area_triangle() only accepts non-negative values" ) return (base * height) / 2 def _lowerCamelCase( a , a , a ): if sidea < 0 or sidea < 0 or sidea < 0: raise ValueError("area_triangle_three_sides() only accepts non-negative values" ) elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea: raise ValueError("Given three sides do not form a triangle" ) __a = (sidea + sidea + sidea) / 2 __a = sqrt( semi_perimeter * (semi_perimeter - sidea) * (semi_perimeter - sidea) * (semi_perimeter - sidea) ) return area def _lowerCamelCase( a , a ): if base < 0 or height < 0: raise ValueError("area_parallelogram() only accepts non-negative values" ) return base * height def _lowerCamelCase( a , a , a ): if basea < 0 or basea < 0 or height < 0: raise ValueError("area_trapezium() only accepts non-negative values" ) return 1 / 2 * (basea + basea) * height def _lowerCamelCase( a ): if radius < 0: raise ValueError("area_circle() only accepts non-negative values" ) return pi * radius**2 def _lowerCamelCase( a , a ): if radius_x < 0 or radius_y < 0: raise ValueError("area_ellipse() only accepts non-negative values" ) return pi * radius_x * radius_y def _lowerCamelCase( a , a ): if diagonal_a < 0 or diagonal_a < 0: raise ValueError("area_rhombus() only accepts non-negative values" ) return 1 / 2 * diagonal_a * diagonal_a def _lowerCamelCase( a , a ): if not isinstance(__a , __a ) or sides < 3: raise ValueError( "area_reg_polygon() only accepts integers greater than or \\nequal to three as number of sides" ) elif length < 0: raise ValueError( "area_reg_polygon() only accepts non-negative values as \\nlength of a side" ) return (sides * length**2) / (4 * tan(pi / sides )) return (sides * length**2) / (4 * tan(pi / sides )) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) # verbose so we can see methods missing tests print("""[DEMO] Areas of various geometric shapes: \n""") print(F'''Rectangle: {area_rectangle(10, 20) = }''') print(F'''Square: {area_square(10) = }''') print(F'''Triangle: {area_triangle(10, 10) = }''') print(F'''Triangle: {area_triangle_three_sides(5, 12, 13) = }''') print(F'''Parallelogram: {area_parallelogram(10, 20) = }''') print(F'''Rhombus: {area_rhombus(10, 20) = }''') print(F'''Trapezium: {area_trapezium(10, 20, 30) = }''') print(F'''Circle: {area_circle(20) = }''') print(F'''Ellipse: {area_ellipse(10, 20) = }''') print("""\nSurface Areas of various geometric shapes: \n""") print(F'''Cube: {surface_area_cube(20) = }''') print(F'''Cuboid: {surface_area_cuboid(10, 20, 30) = }''') print(F'''Sphere: {surface_area_sphere(20) = }''') print(F'''Hemisphere: {surface_area_hemisphere(20) = }''') print(F'''Cone: {surface_area_cone(10, 20) = }''') print(F'''Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }''') print(F'''Cylinder: {surface_area_cylinder(10, 20) = }''') print(F'''Torus: {surface_area_torus(20, 10) = }''') print(F'''Equilateral Triangle: {area_reg_polygon(3, 10) = }''') print(F'''Square: {area_reg_polygon(4, 10) = }''') print(F'''Reqular Pentagon: {area_reg_polygon(5, 10) = }''')
261
"""simple docstring""" import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = (PNDMScheduler,) __UpperCamelCase = (("num_inference_steps", 5_0),) def _SCREAMING_SNAKE_CASE ( self : Any , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**lowercase_) return config def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[str]=0 , **lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample SCREAMING_SNAKE_CASE_ : List[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : Dict = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class.from_pretrained(lowercase_) new_scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Optional[Any] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Dict = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str]=0 , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Dict = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler_class.from_pretrained(lowercase_) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Any = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Tuple = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : str , **lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Dict = 10 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE_ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_) for i, t in enumerate(scheduler.prk_timesteps): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample for i, t in enumerate(scheduler.plms_timesteps): SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_).prev_sample return sample def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''num_inference_steps''' , lowercase_) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowercase_ , '''set_timesteps'''): scheduler.set_timesteps(lowercase_) elif num_inference_steps is not None and not hasattr(lowercase_ , '''set_timesteps'''): SCREAMING_SNAKE_CASE_ : Optional[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE_ : str = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE_ : Optional[int] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Dict = scheduler.step_prk(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : List[Any] = scheduler.step_prk(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_plms(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Any = scheduler.step_plms(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config(steps_offset=1) SCREAMING_SNAKE_CASE_ : Tuple = scheduler_class(**lowercase_) scheduler.set_timesteps(10) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]) , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01] , [0.0_02, 0.02]): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100]): self.check_over_forward(num_inference_steps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = 27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_sample SCREAMING_SNAKE_CASE_ : str = 0.1 * sample SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2]): SCREAMING_SNAKE_CASE_ : int = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : int = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Dict = scheduler_class(**lowercase_) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample).prev_sample def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.full_loop() SCREAMING_SNAKE_CASE_ : List[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_98.13_18) < 1e-2 assert abs(result_mean.item() - 0.25_80) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.full_loop(prediction_type='''v_prediction''') SCREAMING_SNAKE_CASE_ : str = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 67.39_86) < 1e-2 assert abs(result_mean.item() - 0.08_78) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 2_30.03_99) < 1e-2 assert abs(result_mean.item() - 0.29_95) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : int = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_86.94_82) < 1e-2 assert abs(result_mean.item() - 0.24_34) < 1e-3
91
0
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() SCREAMING_SNAKE_CASE_:int = logging.get_logger(__name__) def __UpperCamelCase ( _lowerCAmelCase ) -> List[str]: """simple docstring""" A : int = SwinConfig.from_pretrained( """microsoft/swin-tiny-patch4-window7-224""" , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) A : Optional[int] = MaskFormerConfig(backbone_config=__a ) A : List[Any] = '''huggingface/label-files''' if "ade20k-full" in model_name: # this should be ok A : Optional[Any] = 847 A : int = '''maskformer-ade20k-full-id2label.json''' elif "ade" in model_name: # this should be ok A : Optional[int] = 150 A : Union[str, Any] = '''ade20k-id2label.json''' elif "coco-stuff" in model_name: # this should be ok A : Any = 171 A : List[str] = '''maskformer-coco-stuff-id2label.json''' elif "coco" in model_name: # TODO A : List[Any] = 133 A : List[Any] = '''coco-panoptic-id2label.json''' elif "cityscapes" in model_name: # this should be ok A : Dict = 19 A : Union[str, Any] = '''cityscapes-id2label.json''' elif "vistas" in model_name: # this should be ok A : int = 65 A : List[Any] = '''mapillary-vistas-id2label.json''' A : Optional[int] = json.load(open(hf_hub_download(__a , __a , repo_type="""dataset""" ) , """r""" ) ) A : Any = {int(__a ): v for k, v in idalabel.items()} return config def __UpperCamelCase ( _lowerCAmelCase ) -> Tuple: """simple docstring""" A : Any = [] # 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 __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]: """simple docstring""" A : str = dct.pop(__a ) A : List[Any] = val def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: """simple docstring""" A : Dict = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): A : Optional[int] = 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 : Dict = state_dict.pop(f'''backbone.layers.{i}.blocks.{j}.attn.qkv.weight''' ) A : List[Any] = 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 : List[str] = in_proj_weight[:dim, :] A : int = in_proj_bias[: dim] A : int = in_proj_weight[ dim : dim * 2, : ] A : Any = in_proj_bias[ dim : dim * 2 ] A : Optional[int] = in_proj_weight[ -dim :, : ] A : str = in_proj_bias[-dim :] # fmt: on def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]: """simple docstring""" A : int = 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 : List[Any] = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight''' ) A : Dict = 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 : Union[str, Any] = in_proj_weight[: hidden_size, :] A : List[Any] = in_proj_bias[:config.hidden_size] A : Union[str, Any] = in_proj_weight[hidden_size : hidden_size * 2, :] A : Dict = in_proj_bias[hidden_size : hidden_size * 2] A : Dict = in_proj_weight[-hidden_size :, :] A : Union[str, Any] = 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 : str = state_dict.pop(f'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight''' ) A : Optional[int] = 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 : Any = in_proj_weight[: hidden_size, :] A : List[Any] = in_proj_bias[:config.hidden_size] A : Any = in_proj_weight[hidden_size : hidden_size * 2, :] A : List[Any] = in_proj_bias[hidden_size : hidden_size * 2] A : Optional[Any] = in_proj_weight[-hidden_size :, :] A : Any = in_proj_bias[-hidden_size :] # fmt: on def __UpperCamelCase ( ) -> torch.Tensor: """simple docstring""" A : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A : Optional[Any] = Image.open(requests.get(__a , stream=__a ).raw ) return im @torch.no_grad() def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = False ) -> Union[str, Any]: """simple docstring""" A : int = get_maskformer_config(__a ) # load original state_dict with open(__a , """rb""" ) as f: A : Any = pickle.load(__a ) A : Optional[int] = data['''model'''] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys A : Union[str, Any] = create_rename_keys(__a ) for src, dest in rename_keys: rename_key(__a , __a , __a ) read_in_swin_q_k_v(__a , config.backbone_config ) read_in_decoder_q_k_v(__a , __a ) # update to torch tensors for key, value in state_dict.items(): A : Optional[int] = torch.from_numpy(__a ) # load 🤗 model A : Dict = MaskFormerForInstanceSegmentation(__a ) model.eval() for name, param in model.named_parameters(): print(__a , param.shape ) A : List[str] = model.load_state_dict(__a , strict=__a ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(__a ) == 0, f'''Unexpected keys: {unexpected_keys}''' # verify results A : List[Any] = prepare_img() if "vistas" in model_name: A : Tuple = 65 elif "cityscapes" in model_name: A : Optional[int] = 6_5535 else: A : int = 255 A : Any = True if '''ade''' in model_name else False A : Optional[int] = MaskFormerImageProcessor(ignore_index=__a , reduce_labels=__a ) A : int = image_processor(__a , return_tensors="""pt""" ) A : Optional[Any] = model(**__a ) print("""Logits:""" , outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": A : int = torch.tensor( [[3.6_353, -4.4_770, -2.6_065], [0.5_081, -4.2_394, -3.5_343], [2.1_909, -5.0_353, -1.9_323]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , __a , 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(__a ).mkdir(exist_ok=__a ) model.save_pretrained(__a ) image_processor.save_pretrained(__a ) 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__": SCREAMING_SNAKE_CASE_:Optional[int] = 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.""" ) SCREAMING_SNAKE_CASE_:Dict = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
116
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)]) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ , config_name=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , config_name=lowercase_) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50) self.assertEqual(loaded_config.max_length , 20) self.assertEqual(loaded_config.max_time , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained('''gpt2''') SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_model_config(lowercase_) SCREAMING_SNAKE_CASE_ : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_ , lowercase_) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = GenerationConfig() SCREAMING_SNAKE_CASE_ : Any = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = generation_config.update(**lowercase_) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_ , lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_ , {'''foo''': '''bar'''}) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig() SCREAMING_SNAKE_CASE_ : List[str] = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir: generation_config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = GenerationConfig.from_pretrained(lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''') SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig.from_model_config(lowercase_) assert not hasattr(lowercase_ , '''foo''') # no new kwargs should be initialized if from config def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , lowercase_) self.assertEqual(default_config.num_beams , 1) SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , lowercase_) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str]): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-generation-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''test-generation-config''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Optional[int] = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_))
91
0
from math import isqrt, loga def __lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" lowercase__ : Optional[Any] = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , __a , __a ): lowercase__ : Union[str, Any] = False return [i for i in range(2 , __a ) if is_prime[i]] def __lowerCamelCase ( lowerCamelCase__ = 800_800 , lowerCamelCase__ = 800_800 ): """simple docstring""" lowercase__ : Optional[Any] = degree * loga(__a ) lowercase__ : str = int(__a ) lowercase__ : Optional[int] = calculate_prime_numbers(__a ) lowercase__ : int = 0 lowercase__ : List[Any] = 0 lowercase__ : List[Any] = len(__a ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(f'''{solution() = }''')
130
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : List[str] = """\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\", author = \"Moosavi, Nafise Sadat and Strube, Michael\", booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\", month = aug, year = \"2016\", address = \"Berlin, Germany\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/P16-1060\", doi = \"10.18653/v1/P16-1060\", pages = \"632--642\", } """ UpperCAmelCase_ : Tuple = """\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. """ UpperCAmelCase_ : Union[str, Any] = """ Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting 'keep_singletons=False', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs. min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: 'mentions': mentions 'muc': MUC metric [Vilain et al, 1995] 'bcub': B-cubed [Bagga and Baldwin, 1998] 'ceafe': CEAFe [Luo et al., 2005] 'lea': LEA [Moosavi and Strube, 2016] 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric('coval') >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -', ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)', ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)', ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -', ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -', ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {'mentions/recall': 1.0,[...] 'conll_score': 100.0} """ def _A (__a , __a , __a=False , __a=False , __a=True , __a=False , __a="dummy_doc" ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {doc: key_lines} SCREAMING_SNAKE_CASE_ : List[str] = {doc: sys_lines} SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = reader.get_doc_mentions(__a , key_doc_lines[doc] , __a ) key_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(__a , sys_doc_lines[doc] , __a ) sys_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) if remove_nested: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def _A (__a , __a , __a , __a , __a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_coref_infos(__a , __a , __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : str = {} SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = 0 for name, metric in metrics: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = evaluator.evaluate_documents(__a , __a , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 1_00:.2f}' , f' Precision: {precision * 1_00:.2f}' , f' F1: {fa * 1_00:.2f}' , ) if conll_subparts_num == 3: SCREAMING_SNAKE_CASE_ : Tuple = (conll / 3) * 1_00 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: SCREAMING_SNAKE_CASE_ : Any = line.split()[5] if not parse_col == "-": SCREAMING_SNAKE_CASE_ : Any = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''')), '''references''': datasets.Sequence(datasets.Value('''string''')), }) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Dict=True , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=False , lowercase_ : Dict=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = util.check_gold_parse_annotation(lowercase_) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''') # util.parse_key_file(key_file) # key_file = key_file + ".parsed" SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate( key_lines=lowercase_ , sys_lines=lowercase_ , metrics=lowercase_ , NP_only=lowercase_ , remove_nested=lowercase_ , keep_singletons=lowercase_ , min_span=lowercase_ , ) return score
91
0
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) class A__ ( UpperCAmelCase__ ): def __init__( self : List[str] , *_UpperCAmelCase : Dict , **_UpperCAmelCase : Union[str, Any] ) -> str: """simple docstring""" warnings.warn( 'The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DeiTImageProcessor instead.' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_ )
325
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = """▁""" UpperCAmelCase_ : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCAmelCase_ : str = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } UpperCAmelCase_ : str = { """facebook/xglm-564M""": 2048, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[Any] , lowercase_ : str , lowercase_ : Tuple="<s>" , lowercase_ : Any="</s>" , lowercase_ : Optional[int]="</s>" , lowercase_ : List[Any]="<s>" , lowercase_ : Union[str, Any]="<unk>" , lowercase_ : Union[str, Any]="<pad>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE_ : List[str] = 7 SCREAMING_SNAKE_CASE_ : Tuple = [F'<madeupword{i}>' for i in range(self.num_madeup_words)] SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''additional_special_tokens''' , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} SCREAMING_SNAKE_CASE_ : List[Any] = len(self.sp_model) SCREAMING_SNAKE_CASE_ : Optional[Any] = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE_ : Dict = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = 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_)) return [1] + ([0] * len(lowercase_)) + [1, 1] + ([0] * len(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : str): '''simple docstring''' return self.sp_model.encode(lowercase_ , out_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Union[str, Any]): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sp_model.PieceToId(lowercase_) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any]): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(lowercase_).replace(lowercase_ , ''' ''').strip() return out_string def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : int = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,)
91
0
'''simple docstring''' import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class A__ ( UpperCAmelCase__ ): """simple docstring""" UpperCamelCase_ : List[str] = '''facebook/bart-large-mnli''' UpperCamelCase_ : Optional[int] = ( '''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.''' ) UpperCamelCase_ : Any = '''text_classifier''' UpperCamelCase_ : Tuple = AutoTokenizer UpperCamelCase_ : List[Any] = AutoModelForSequenceClassification UpperCamelCase_ : List[str] = ['''text''', ['''text''']] UpperCamelCase_ : Optional[int] = ['''text'''] def _lowerCAmelCase ( self : Optional[int] ) -> List[Any]: """simple docstring""" super().setup() _UpperCAmelCase : Optional[int] = self.model.config _UpperCAmelCase : List[Any] = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("entail" ): _UpperCAmelCase : List[str] = 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 _lowerCAmelCase ( self : Any , lowerCAmelCase__ : str , lowerCAmelCase__ : int ) -> Dict: """simple docstring""" _UpperCAmelCase : Dict = labels return self.pre_processor( [text] * len(lowercase_ ) , [F"""This example is {label}""" for label in labels] , return_tensors="pt" , padding="max_length" , ) def _lowerCAmelCase ( self : Optional[int] , lowerCAmelCase__ : Optional[Any] ) -> int: """simple docstring""" _UpperCAmelCase : Optional[int] = outputs.logits _UpperCAmelCase : Optional[Any] = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
145
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Dict = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : str = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_))
91
0
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def _lowercase ( __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Tuple = checkpoints.load_tax_checkpoint(__a ) SCREAMING_SNAKE_CASE__ : Optional[Any] = flatten_dict(__a ) return flax_params def _lowercase ( __lowerCAmelCase ) -> Optional[int]: SCREAMING_SNAKE_CASE__ : Dict = {} SCREAMING_SNAKE_CASE__ : Optional[Any] = { '''token_embedder''': '''embeddings''', '''encoder_norm''': '''layernorm''', '''kernel''': '''weight''', '''.out''': '''.output''', '''scale''': '''weight''', '''embedders_0.pos_embedding''': '''row_embedder.weight''', '''embedders_1.pos_embedding''': '''column_embedder.weight''', } SCREAMING_SNAKE_CASE__ : Any = { '''query''': '''attention.query''', '''key''': '''attention.key''', '''value''': '''attention.value''', '''output.dense''': '''output''', '''encoder_decoder_attention.o''': '''encoder_decoder_attention.attention.o''', '''pre_self_attention_layer_norm''': '''self_attention.layer_norm''', '''pre_cross_attention_layer_norm''': '''encoder_decoder_attention.layer_norm''', '''mlp.''': '''mlp.DenseReluDense.''', '''pre_mlp_layer_norm''': '''mlp.layer_norm''', '''self_attention.o''': '''self_attention.attention.o''', '''decoder.embeddings.embedding''': '''decoder.embed_tokens.weight''', '''decoder.relpos_bias.rel_embedding''': '''decoder.layer.0.self_attention.attention.relative_attention_bias.weight''', '''decoder.decoder_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.logits_dense.weight''': '''decoder.lm_head.weight''', } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key SCREAMING_SNAKE_CASE__ : str = '''.'''.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): SCREAMING_SNAKE_CASE__ : str = new_key.replace(__a , __a ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): SCREAMING_SNAKE_CASE__ : Any = new_key.replace(__a , __a ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number SCREAMING_SNAKE_CASE__ : int = re.sub(r"""layers_(\d+)""" , r"""layer.\1""" , __a ) SCREAMING_SNAKE_CASE__ : Tuple = new_key.replace("""encoder""" , """encoder.encoder""" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number SCREAMING_SNAKE_CASE__ : Any = re.sub(r"""layers_(\d+)""" , r"""layer.\1""" , __a ) SCREAMING_SNAKE_CASE__ : str = flax_dict[key] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): SCREAMING_SNAKE_CASE__ : List[Any] = torch.from_numpy(converted_dict[key].T ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=False , __lowerCAmelCase=False ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_flax_param(__a ) if not use_large: SCREAMING_SNAKE_CASE__ : Optional[int] = PixaStructVisionConfig() SCREAMING_SNAKE_CASE__ : int = PixaStructTextConfig() else: SCREAMING_SNAKE_CASE__ : Dict = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) SCREAMING_SNAKE_CASE__ : Tuple = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=__a ) SCREAMING_SNAKE_CASE__ : Dict = PixaStructForConditionalGeneration(__a ) SCREAMING_SNAKE_CASE__ : Optional[int] = rename_and_convert_flax_params(__a ) model.load_state_dict(__a ) SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained("""ybelkada/test-pix2struct-tokenizer""" ) SCREAMING_SNAKE_CASE__ : List[str] = PixaStructImageProcessor() SCREAMING_SNAKE_CASE__ : str = PixaStructProcessor(image_processor=__a , tokenizer=__a ) if use_large: SCREAMING_SNAKE_CASE__ : int = 4096 SCREAMING_SNAKE_CASE__ : int = True # mkdir if needed os.makedirs(__a , exist_ok=__a ) model.save_pretrained(__a ) processor.save_pretrained(__a ) print("""Model saved in {}""".format(__a ) ) if __name__ == "__main__": a :Any = argparse.ArgumentParser() parser.add_argument("--t5x_checkpoint_path", default=None, type=str, help="Path to the original T5x checkpoint.") parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--use_large", action="store_true", help="Use large model.") parser.add_argument("--is_vqa", action="store_true", help="Use large model.") a :str = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
132
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable UpperCAmelCase_ : str = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
0
'''simple docstring''' import random from typing import Any def _lowerCAmelCase ( _UpperCamelCase : Dict ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): _SCREAMING_SNAKE_CASE =random.randint(0 , len(__a ) - 1 ) _SCREAMING_SNAKE_CASE =random.randint(0 , len(__a ) - 1 ) _SCREAMING_SNAKE_CASE =data[b], data[a] return data if __name__ == "__main__": lowerCamelCase : Dict = [0, 1, 2, 3, 4, 5, 6, 7] lowerCamelCase : Dict = ["""python""", """says""", """hello""", """!"""] print("Fisher-Yates Shuffle:") print("List", integers, strings) print("FY Shuffle", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
47
"""simple docstring""" import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py UpperCAmelCase_ : Optional[int] = """src/transformers""" UpperCAmelCase_ : Tuple = """docs/source/en""" UpperCAmelCase_ : Optional[Any] = """.""" def _A (__a , __a , __a ) -> Dict: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE_ : List[Any] = 0 while not lines[start_index].startswith(__a ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Tuple = start_index while not lines[end_index].startswith(__a ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCAmelCase_ : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. UpperCAmelCase_ : int = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") UpperCAmelCase_ : Dict = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCAmelCase_ : int = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase_ : Optional[int] = direct_transformers_import(TRANSFORMERS_PATH) def _A (__a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __a ) return [m.group(0 ) for m in matches] def _A (__a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 2 if text == '''✅''' or text == '''❌''' else len(__a ) SCREAMING_SNAKE_CASE_ : Tuple = (width - text_length) // 2 SCREAMING_SNAKE_CASE_ : Tuple = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ : Tuple = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } SCREAMING_SNAKE_CASE_ : List[Any] = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) # Let's lookup through all transformers object (once). for attr_name in dir(__a ): SCREAMING_SNAKE_CASE_ : Any = None if attr_name.endswith('''Tokenizer''' ): SCREAMING_SNAKE_CASE_ : Dict = slow_tokenizers SCREAMING_SNAKE_CASE_ : Dict = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = fast_tokenizers SCREAMING_SNAKE_CASE_ : Optional[Any] = attr_name[:-13] elif _re_tf_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : int = tf_models SCREAMING_SNAKE_CASE_ : Dict = _re_tf_models.match(__a ).groups()[0] elif _re_flax_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : Any = flax_models SCREAMING_SNAKE_CASE_ : Tuple = _re_flax_models.match(__a ).groups()[0] elif _re_pt_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : str = pt_models SCREAMING_SNAKE_CASE_ : int = _re_pt_models.match(__a ).groups()[0] if lookup_dict is not None: while len(__a ) > 0: if attr_name in model_name_to_prefix.values(): SCREAMING_SNAKE_CASE_ : List[str] = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(camel_case_split(__a )[:-1] ) # Let's build that table! SCREAMING_SNAKE_CASE_ : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) SCREAMING_SNAKE_CASE_ : Any = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). SCREAMING_SNAKE_CASE_ : List[str] = [len(__a ) + 2 for c in columns] SCREAMING_SNAKE_CASE_ : str = max([len(__a ) for name in model_names] ) + 2 # Build the table per se SCREAMING_SNAKE_CASE_ : List[Any] = '''|''' + '''|'''.join([_center_text(__a , __a ) for c, w in zip(__a , __a )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" SCREAMING_SNAKE_CASE_ : Union[str, Any] = {True: '''✅''', False: '''❌'''} for name in model_names: SCREAMING_SNAKE_CASE_ : str = model_name_to_prefix[name] SCREAMING_SNAKE_CASE_ : int = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__a , __a ) for l, w in zip(__a , __a )] ) + "|\n" return table def _A (__a=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = _find_text_in_file( filename=os.path.join(__a , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) SCREAMING_SNAKE_CASE_ : Tuple = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__a , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
91
0
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model _UpperCAmelCase : str = """0.12""" # assumed parallelism: 8 if is_torch_available(): import torch def A ( lowercase , lowercase , lowercase=None ) -> str: '''simple docstring''' if rng is None: UpperCamelCase = random.Random() UpperCamelCase = 1 for dim in shape: total_dims *= dim UpperCamelCase = [] for _ in range(__a ): values.append(rng.randint(0 , vocab_size - 1 ) ) UpperCamelCase = np.array(__a , dtype=jnp.intaa ).reshape(__a ) return output def A ( lowercase , lowercase=None ) -> Optional[Any]: '''simple docstring''' UpperCamelCase = ids_tensor(__a , vocab_size=2 , rng=__a ) # make sure that at least one token is attended to for each batch UpperCamelCase = 1 return attn_mask @require_flax class lowercase : __lowercase : Tuple = None __lowercase : Optional[Any] = () def __UpperCamelCase ( self ) -> List[str]: """simple docstring""" UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 UpperCamelCase = 2 UpperCamelCase = inputs['''input_ids'''].shape[-1] // 2 UpperCamelCase = inputs['''input_ids'''][:max_batch_size, :sequence_length] UpperCamelCase = jnp.ones_like(lowercase_ ) UpperCamelCase = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens UpperCamelCase = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` UpperCamelCase = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def __UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() UpperCamelCase = False UpperCamelCase = max_length UpperCamelCase = 0 for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model_class.__name__[4:] # Skip the "Flax" at the beginning UpperCamelCase = getattr(lowercase_ , lowercase_ ) UpperCamelCase = pt_model_class(lowercase_ ).eval() UpperCamelCase = load_flax_weights_in_pytorch_model(lowercase_ , flax_model.params ) UpperCamelCase = flax_model.generate(lowercase_ ).sequences UpperCamelCase = pt_model.generate(torch.tensor(lowercase_ , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: UpperCamelCase = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def __UpperCamelCase ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() UpperCamelCase = False UpperCamelCase = max_length for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model.generate(lowercase_ ).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_ ) UpperCamelCase = jit(model.generate ) UpperCamelCase = jit_generate(lowercase_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCamelCase ( self ) -> Any: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() UpperCamelCase = True UpperCamelCase = max_length for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model.generate(lowercase_ ).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_ ) UpperCamelCase = jit(model.generate ) UpperCamelCase = jit_generate(lowercase_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCamelCase ( self ) -> Any: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() UpperCamelCase = False UpperCamelCase = max_length UpperCamelCase = 2 for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model.generate(lowercase_ ).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_ ) UpperCamelCase = jit(model.generate ) UpperCamelCase = jit_generate(lowercase_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCamelCase ( self ) -> Any: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() UpperCamelCase = False UpperCamelCase = max_length UpperCamelCase = 2 UpperCamelCase = 2 for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model.generate(lowercase_ ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() UpperCamelCase = True UpperCamelCase = max_length UpperCamelCase = 0.8 UpperCamelCase = 10 UpperCamelCase = 0.3 UpperCamelCase = 1 UpperCamelCase = 8 UpperCamelCase = 9 for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model.generate(lowercase_ ).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_ ) UpperCamelCase = jit(model.generate ) UpperCamelCase = jit_generate(lowercase_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() UpperCamelCase = max_length UpperCamelCase = 1 UpperCamelCase = 8 UpperCamelCase = 9 for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model.generate(lowercase_ ).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_ ) UpperCamelCase = jit(model.generate ) UpperCamelCase = jit_generate(lowercase_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCamelCase ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() UpperCamelCase = max_length UpperCamelCase = 2 UpperCamelCase = 1 UpperCamelCase = 8 UpperCamelCase = 9 for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model.generate(lowercase_ ).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_ ) UpperCamelCase = jit(model.generate ) UpperCamelCase = jit_generate(lowercase_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCamelCase ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() # pad attention mask on the left UpperCamelCase = attention_mask.at[(0, 0)].set(0 ) UpperCamelCase = False UpperCamelCase = max_length for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model.generate(lowercase_ , attention_mask=lowercase_ ).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_ ) UpperCamelCase = jit(model.generate ) UpperCamelCase = jit_generate(lowercase_ , attention_mask=lowercase_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCamelCase ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() # pad attention mask on the left UpperCamelCase = attention_mask.at[(0, 0)].set(0 ) UpperCamelCase = True UpperCamelCase = max_length for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model.generate(lowercase_ , attention_mask=lowercase_ ).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_ ) UpperCamelCase = jit(model.generate ) UpperCamelCase = jit_generate(lowercase_ , attention_mask=lowercase_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __UpperCamelCase ( self ) -> str: """simple docstring""" UpperCamelCase = self._get_input_ids_and_config() # pad attention mask on the left UpperCamelCase = attention_mask.at[(0, 0)].set(0 ) UpperCamelCase = 2 UpperCamelCase = max_length for model_class in self.all_generative_model_classes: UpperCamelCase = model_class(lowercase_ ) UpperCamelCase = model.generate(lowercase_ , attention_mask=lowercase_ ).sequences self.assertEqual(generation_outputs.shape[-1] , lowercase_ ) UpperCamelCase = jit(model.generate ) UpperCamelCase = jit_generate(lowercase_ , attention_mask=lowercase_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class lowercase ( unittest.TestCase ): def __UpperCamelCase ( self ) -> int: """simple docstring""" UpperCamelCase = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-bert' ) UpperCamelCase = FlaxAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-bert-flax-only' ) UpperCamelCase = '''Hello world''' UpperCamelCase = tokenizer(lowercase_ , return_tensors='np' ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(lowercase_ , 'do_samples' ): model.generate(lowercase_ , do_samples=lowercase_ ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(lowercase_ , 'foo' ): UpperCamelCase = {'''foo''': '''bar'''} model.generate(lowercase_ , **lowercase_ )
222
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : List[str]=13 , lowercase_ : int=7 , lowercase_ : Any=True , lowercase_ : str=True , lowercase_ : List[Any]=True , lowercase_ : List[Any]=True , lowercase_ : Dict=99 , lowercase_ : Union[str, Any]=24 , lowercase_ : int=2 , lowercase_ : List[str]=6 , lowercase_ : Any=37 , lowercase_ : Dict="gelu" , lowercase_ : List[str]=0.1 , lowercase_ : Dict=0.1 , lowercase_ : Union[str, Any]=512 , lowercase_ : List[str]=16 , lowercase_ : Any=2 , lowercase_ : Any=0.02 , lowercase_ : List[Any]=3 , lowercase_ : Optional[int]=None , lowercase_ : str=1000 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE_ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE_ : Tuple = scope SCREAMING_SNAKE_CASE_ : Optional[int] = range_bbox def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : str = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[str] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : List[str] = t SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : Any = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LiltConfig( 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 , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = LiltModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = model(lowercase_ , bbox=lowercase_) 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 _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = LiltForTokenClassification(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LiltForQuestionAnswering(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) 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 _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : str , lowercase_ : str): '''simple docstring''' return True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = LiltModelTester(self) SCREAMING_SNAKE_CASE_ : Optional[int] = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : Dict = type self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[int] = LiltModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''').to(lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.tensor([[1, 2]] , device=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Dict = model(input_ids=lowercase_ , bbox=lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.Size([1, 2, 768]) SCREAMING_SNAKE_CASE_ : Dict = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=lowercase_ , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase_) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase_ , atol=1e-3))
91
0
"""simple docstring""" from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar __UpperCamelCase : int = TypeVar('''T''') class SCREAMING_SNAKE_CASE ( Generic[T] ): """simple docstring""" def __init__( self : Optional[int] ,lowercase_ : T ): lowerCAmelCase__ : Tuple = data lowerCAmelCase__ : Node[T] | None = None def __str__( self : Union[str, Any] ): return F'{self.data}' class SCREAMING_SNAKE_CASE ( Generic[T] ): """simple docstring""" def __init__( self : Optional[int] ): lowerCAmelCase__ : Node[T] | None = None def __iter__( self : int ): lowerCAmelCase__ : Tuple = self.top while node: yield node.data lowerCAmelCase__ : Union[str, Any] = node.next def __str__( self : Union[str, Any] ): return "->".join([str(lowercase_ ) for item in self] ) def __len__( self : Union[str, Any] ): return len(tuple(iter(self ) ) ) def __lowerCAmelCase ( self : Union[str, Any] ): return self.top is None def __lowerCAmelCase ( self : Tuple ,lowercase_ : T ): lowerCAmelCase__ : str = Node(lowercase_ ) if not self.is_empty(): lowerCAmelCase__ : Optional[int] = self.top lowerCAmelCase__ : Optional[Any] = node def __lowerCAmelCase ( self : Optional[Any] ): if self.is_empty(): raise IndexError('''pop from empty stack''' ) assert isinstance(self.top ,lowercase_ ) lowerCAmelCase__ : int = self.top lowerCAmelCase__ : int = self.top.next return pop_node.data def __lowerCAmelCase ( self : int ): if self.is_empty(): raise IndexError('''peek from empty stack''' ) assert self.top is not None return self.top.data def __lowerCAmelCase ( self : int ): lowerCAmelCase__ : str = None if __name__ == "__main__": from doctest import testmod testmod()
106
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCAmelCase_ : Dict = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) UpperCAmelCase_ : Optional[Any] = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: UpperCAmelCase_ : Union[str, Any] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") UpperCAmelCase_ : Any = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase_ : List[Any] = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase_ : Dict = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
91
0
"""simple docstring""" from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class A_ (UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = """philschmid/bart-large-cnn-samsum""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ( """This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, """ """and returns a summary of the text.""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = """summarizer""" SCREAMING_SNAKE_CASE__ : List[str] = AutoTokenizer SCREAMING_SNAKE_CASE__ : List[str] = AutoModelForSeqaSeqLM SCREAMING_SNAKE_CASE__ : str = ["""text"""] SCREAMING_SNAKE_CASE__ : Optional[int] = ["""text"""] def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" return self.pre_processor(lowercase_ , return_tensors="pt" , truncation=lowercase_ ) def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" return self.model.generate(**lowercase_ )[0] def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" return self.pre_processor.decode(lowercase_ , skip_special_tokens=lowercase_ , clean_up_tokenization_spaces=lowercase_ )
61
"""simple docstring""" from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) def _A (__a , __a ) -> Tuple: """simple docstring""" try: with open(__a , '''rb''' ) as flax_state_f: SCREAMING_SNAKE_CASE_ : Optional[int] = from_bytes(__a , flax_state_f.read() ) except UnpicklingError as e: try: with open(__a ) as f: if f.read().startswith('''version''' ): raise OSError( '''You seem to have cloned a repository without having git-lfs installed. Please''' ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the''' ''' folder you cloned.''' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(__a , __a ) def _A (__a , __a ) -> Tuple: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE_ : Optional[int] = flatten_dict(jax.tree_util.tree_map(lambda __a : x.dtype == jnp.bfloataa , __a ) ).values() if any(__a ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.tree_util.tree_map( lambda __a : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , __a ) SCREAMING_SNAKE_CASE_ : int = '''''' SCREAMING_SNAKE_CASE_ : str = flatten_dict(__a , sep='''.''' ) SCREAMING_SNAKE_CASE_ : List[Any] = pt_model.state_dict() # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Any = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple.split('''.''' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.transpose(__a , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": SCREAMING_SNAKE_CASE_ : Tuple = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[int] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": SCREAMING_SNAKE_CASE_ : Optional[int] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(__a ): SCREAMING_SNAKE_CASE_ : List[str] = ( flax_key_tuple_string.replace('''_0''' , '''.0''' ) .replace('''_1''' , '''.1''' ) .replace('''_2''' , '''.2''' ) .replace('''_3''' , '''.3''' ) .replace('''_4''' , '''.4''' ) .replace('''_5''' , '''.5''' ) .replace('''_6''' , '''.6''' ) .replace('''_7''' , '''.7''' ) .replace('''_8''' , '''.8''' ) .replace('''_9''' , '''.9''' ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = '''.'''.join(__a ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE_ : Optional[int] = np.asarray(__a ) if not isinstance(__a , np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.from_numpy(__a ) # remove from missing keys missing_keys.remove(__a ) else: # weight is not expected by PyTorch model unexpected_keys.append(__a ) pt_model.load_state_dict(__a ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE_ : int = list(__a ) if len(__a ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) if len(__a ) > 0: logger.warning( f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) return pt_model
91
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase : Dict = { """configuration_xlm_roberta_xl""": [ """XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMRobertaXLConfig""", """XLMRobertaXLOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = [ """XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMRobertaXLForCausalLM""", """XLMRobertaXLForMaskedLM""", """XLMRobertaXLForMultipleChoice""", """XLMRobertaXLForQuestionAnswering""", """XLMRobertaXLForSequenceClassification""", """XLMRobertaXLForTokenClassification""", """XLMRobertaXLModel""", """XLMRobertaXLPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys _lowerCamelCase : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
282
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "openai-gpt" __UpperCamelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , lowercase_ : List[str]=40478 , lowercase_ : List[str]=512 , lowercase_ : Optional[Any]=768 , lowercase_ : Tuple=12 , lowercase_ : Tuple=12 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : List[Any]=0.1 , lowercase_ : Tuple=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : List[Any]=1e-5 , lowercase_ : int=0.02 , lowercase_ : Optional[int]="cls_index" , lowercase_ : Any=True , lowercase_ : List[Any]=None , lowercase_ : List[str]=True , lowercase_ : Optional[Any]=0.1 , **lowercase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE_ : Tuple = n_positions SCREAMING_SNAKE_CASE_ : Optional[int] = n_embd SCREAMING_SNAKE_CASE_ : Dict = n_layer SCREAMING_SNAKE_CASE_ : Any = n_head SCREAMING_SNAKE_CASE_ : Union[str, Any] = afn SCREAMING_SNAKE_CASE_ : int = resid_pdrop SCREAMING_SNAKE_CASE_ : List[str] = embd_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = attn_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = summary_type SCREAMING_SNAKE_CASE_ : Tuple = summary_use_proj SCREAMING_SNAKE_CASE_ : Union[str, Any] = summary_activation SCREAMING_SNAKE_CASE_ : Any = summary_first_dropout SCREAMING_SNAKE_CASE_ : List[str] = summary_proj_to_labels super().__init__(**lowercase_)
91
0
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE__:Tuple = 16 SCREAMING_SNAKE_CASE__:List[str] = 32 def _lowerCamelCase( a , a = 1_6 ): __a = AutoTokenizer.from_pretrained("bert-base-cased" ) __a = load_dataset("glue" , "mrpc" ) def tokenize_function(a ): # max_length=None => use the model max length (it's actually the default) __a = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __a = datasets.map( __a , batched=__a , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __a = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(a ): # On TPU it's best to pad everything to the same length or training will be very slow. __a = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __a = 1_6 elif accelerator.mixed_precision != "no": __a = 8 else: __a = None return tokenizer.pad( __a , padding="longest" , max_length=__a , pad_to_multiple_of=__a , return_tensors="pt" , ) # Instantiate dataloaders. __a = DataLoader( tokenized_datasets["train"] , shuffle=__a , collate_fn=__a , batch_size=__a ) __a = DataLoader( tokenized_datasets["validation"] , shuffle=__a , collate_fn=__a , batch_size=__a ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders SCREAMING_SNAKE_CASE__:int = mocked_dataloaders # noqa: F811 def _lowerCamelCase( a , a ): if os.environ.get("TESTING_MOCKED_DATALOADERS" , __a ) == "1": __a = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: __a = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="all" , project_dir=args.project_dir ) else: __a = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a = config['''lr'''] __a = int(config["num_epochs"] ) __a = int(config["seed"] ) __a = int(config["batch_size"] ) set_seed(__a ) __a = get_dataloaders(__a , __a ) __a = evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation __a = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __a = batch_size // MAX_GPU_BATCH_SIZE __a = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=__a ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __a = model.to(accelerator.device ) # Instantiate optimizer __a = AdamW(params=model.parameters() , lr=__a ) # Instantiate scheduler __a = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=1_0_0 , num_training_steps=(len(__a ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __a = accelerator.prepare( __a , __a , __a , __a , __a ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: __a = os.path.split(__a )[-1].split("." )[0] accelerator.init_trackers(__a , __a ) # Now we train the model for epoch in range(__a ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: __a = 0 for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __a = model(**__a ) __a = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() __a = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): __a = model(**__a ) __a = outputs.logits.argmax(dim=-1 ) __a = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=__a , references=__a , ) __a = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , __a ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { "accuracy": eval_metric["accuracy"], "f1": eval_metric["f1"], "train_loss": total_loss.item() / len(__a ), "epoch": epoch, } , step=__a , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def _lowerCamelCase( ): __a = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=__a , default=__a , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) parser.add_argument( "--with_tracking" , action="store_true" , help="Whether to load in all available experiment trackers from the environment and use them for logging." , ) parser.add_argument( "--project_dir" , type=__a , default="logs" , help="Location on where to store experiment tracking logs` and relevent project information" , ) __a = parser.parse_args() __a = {'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 4_2, '''batch_size''': 1_6} training_function(__a , __a ) if __name__ == "__main__": main()
261
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' warnings.warn( '''The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DeiTImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
0
import csv import tweepy # Twitter API credentials SCREAMING_SNAKE_CASE_:Optional[Any] = """""" SCREAMING_SNAKE_CASE_:int = """""" SCREAMING_SNAKE_CASE_:List[str] = """""" SCREAMING_SNAKE_CASE_:Any = """""" def __UpperCamelCase ( _lowerCAmelCase ) -> None: """simple docstring""" A : List[Any] = tweepy.OAuthHandler(__a , __a ) auth.set_access_token(__a , __a ) A : Dict = tweepy.API(__a ) # initialize a list to hold all the tweepy Tweets A : List[Any] = [] # make initial request for most recent tweets (200 is the maximum allowed count) A : int = api.user_timeline(screen_name=__a , count=200 ) # save most recent tweets alltweets.extend(__a ) # save the id of the oldest tweet less one A : Optional[int] = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(__a ) > 0: print(f'''getting tweets before {oldest}''' ) # all subsequent requests use the max_id param to prevent duplicates A : Dict = api.user_timeline( screen_name=__a , count=200 , max_id=__a ) # save most recent tweets alltweets.extend(__a ) # update the id of the oldest tweet less one A : List[str] = alltweets[-1].id - 1 print(f'''...{len(__a )} tweets downloaded so far''' ) # transform the tweepy tweets into a 2D array that will populate the csv A : List[Any] = [[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: A : List[Any] = csv.writer(__a ) writer.writerow(["""id""", """created_at""", """text"""] ) writer.writerows(__a ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
116
"""simple docstring""" import random from typing import Any def _A (__a ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ : Tuple = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = data[b], data[a] return data if __name__ == "__main__": UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5, 6, 7] UpperCAmelCase_ : Dict = ["""python""", """says""", """hello""", """!"""] print("""Fisher-Yates Shuffle:""") print("""List""", integers, strings) print("""FY Shuffle""", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
91
0
import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor lowerCAmelCase__ = logging.get_logger(__name__) class snake_case__(UpperCAmelCase__ ): """simple docstring""" def __init__( self : List[str] , *SCREAMING_SNAKE_CASE : Tuple , **SCREAMING_SNAKE_CASE : Tuple ): warnings.warn( "The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DonutImageProcessor instead." , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_ )
130
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _A (__a , __a , __a ) -> Dict: """simple docstring""" if gpta_config_file == "": SCREAMING_SNAKE_CASE_ : Optional[Any] = GPTaConfig() else: SCREAMING_SNAKE_CASE_ : Tuple = GPTaConfig.from_json_file(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = GPTaModel(__a ) # Load weights from numpy load_tf_weights_in_gpta(__a , __a , __a ) # Save pytorch-model SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : List[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , __a ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow 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( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
91
0
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Optional[int] ) -> List[Any]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer __lowercase = flax_key_tuple[:-1] + ('''weight''',) __lowercase = torch.permute(__a , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__a ): # linear layer __lowercase = flax_key_tuple[:-1] + ('''weight''',) __lowercase = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: __lowercase = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : str ) -> Union[str, Any]: if "metadata" in layer: __lowercase = layer.split('metadata' ) __lowercase = ''''''.join(split_layer[0] )[:-1] __lowercase = [tuple(('metadata' + split_layer[1]).split('/' ) )] elif "kvstore" in layer: __lowercase = layer.split('kvstore' ) __lowercase = ''''''.join(split_layer[0] )[:-1] __lowercase = [tuple(('kvstore' + split_layer[1]).split('/' ) )] else: __lowercase = layer.split('/' ) __lowercase = '''/'''.join(split_layer[:-1] ) __lowercase = (split_layer[-1],) if "kvstore/path" in layer: __lowercase = F"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: __lowercase = '''file''' else: __lowercase = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[Any] ) -> int: __lowercase = rename_keys(__a ) __lowercase = {} for k, v in current_block.items(): __lowercase = v __lowercase = new_current_block torch.save(__a , __a ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : List[Any] = WEIGHTS_NAME ) -> Dict: __lowercase = convert_file_size_to_int(__a ) __lowercase = [] __lowercase = {} __lowercase = 0 __lowercase = 0 os.makedirs(__a , exist_ok=__a ) with gfile.GFile(switch_checkpoint_path + '/checkpoint' , 'rb' ) as fp: __lowercase = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] __lowercase = flatten_dict(__a , sep='/' ) __lowercase = {} for layer in checkpoint_info.keys(): __lowercase = get_key_and_tensorstore_dict( __a , __a , __a ) if curr_real_layer_name in all_layers: __lowercase = content else: __lowercase = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file __lowercase = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() __lowercase = torch.tensor(__a ) __lowercase = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts __lowercase = rename_base_flax_keys(tuple(key.split('/' ) ) , __a ) __lowercase = '''/'''.join(__a ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: __lowercase = os.path.join( __a , weights_name.replace('.bin' , F"""-{len(__a )+1:05d}-of-???.bin""" ) ) rename_and_save_block(__a , __a ) sharded_state_dicts.append(current_block.keys() ) del current_block __lowercase = {} __lowercase = 0 __lowercase = raw_weights.to(getattr(__a , __a ) ) current_block_size += weight_size total_size += weight_size # Add the last block __lowercase = os.path.join(__a , weights_name.replace('.bin' , F"""-{len(__a )+1:05d}-of-???.bin""" ) ) rename_and_save_block(__a , __a ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__a ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index __lowercase = {} __lowercase = {} for idx, shard in enumerate(__a ): __lowercase = weights_name.replace( '.bin' , F"""-{idx+1:05d}-of-{len(__a ):05d}.bin""" ) # len(sharded_state_dicts):05d} __lowercase = os.path.join(__a , weights_name.replace('.bin' , F"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(__a , os.path.join(__a , __a ) ) __lowercase = shard for key in shard: __lowercase = shard_file # Add the metadata __lowercase = {'''total_size''': total_size} __lowercase = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(__a , __a ) , 'w' , encoding='utf-8' ) as f: __lowercase = json.dumps(__a , indent=2 , sort_keys=__a ) + '''\n''' f.write(__a ) return metadata, index if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--switch_t5x_checkpoint_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600""", type=str, required=False, help="""Path to a directory containing a folder per layer. Follows the original Google format.""", ) parser.add_argument("""--max_shard_size""", default="""10GB""", required=False, help="""Max shard size""") parser.add_argument("""--dtype""", default="""bfloat16""", type=str, required=False, help="""dtype of the saved model""") parser.add_argument( """--pytorch_dump_folder_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted""", type=str, required=False, help="""Path to the output pytorch model.""", ) SCREAMING_SNAKE_CASE__ = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __SCREAMING_SNAKE_CASE ( ) -> Tuple: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer __lowercase = SwitchTransformersConfig.from_pretrained('google/switch-base-8' ) config.save_pretrained('/home/arthur_huggingface_co/transformers/switch_converted' ) __lowercase = SwitchTransformersForConditionalGeneration.from_pretrained( '/home/arthur_huggingface_co/transformers/switch_converted' , device_map='auto' ) __lowercase = TaTokenizer.from_pretrained('t5-small' ) __lowercase = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' __lowercase = tokenizer(__a , return_tensors='pt' ).input_ids __lowercase = model.generate(__a , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
325
"""simple docstring""" from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
91
0
'''simple docstring''' class A__ : # Public class to implement a graph """simple docstring""" def __init__( self : Tuple , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : list[list[bool]] ) -> int: """simple docstring""" _UpperCAmelCase : Union[str, Any] = row _UpperCAmelCase : Tuple = col _UpperCAmelCase : Union[str, Any] = graph def _lowerCAmelCase ( self : Tuple , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : list[list[bool]] ) -> Any: """simple docstring""" return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def _lowerCAmelCase ( self : Tuple , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : list[list[bool]] ) -> Optional[int]: """simple docstring""" _UpperCAmelCase : Optional[Any] = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order _UpperCAmelCase : Tuple = [-1, 0, 1, -1, 1, -1, 0, 1] _UpperCAmelCase : Tuple = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , lowercase_ ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , lowercase_ ) def _lowerCAmelCase ( self : int ) -> Dict: # And finally, count all islands. """simple docstring""" _UpperCAmelCase : str = [[False for j in range(self.COL )] for i in range(self.ROW )] _UpperCAmelCase : Dict = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(lowercase_ , lowercase_ , lowercase_ ) count += 1 return count
145
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType 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, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' 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_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.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
0
"""simple docstring""" import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class __a (UpperCAmelCase__): '''simple docstring''' _SCREAMING_SNAKE_CASE :int = (IPNDMScheduler,) _SCREAMING_SNAKE_CASE :Optional[int] = (("""num_inference_steps""", 50),) def _a ( self , **_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = {'''num_train_timesteps''': 1_000} config.update(**lowercase_ ) return config def _a ( self , _a=0 , **_a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop("""num_inference_steps""" , lowercase_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_sample SCREAMING_SNAKE_CASE__ : List[str] = 0.1 * sample SCREAMING_SNAKE_CASE__ : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config(**lowercase_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_class(**lowercase_ ) scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE__ : Dict = dummy_past_residuals[:] if time_step is None: SCREAMING_SNAKE_CASE__ : str = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_ ) SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class.from_pretrained(lowercase_ ) new_scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals SCREAMING_SNAKE_CASE__ : List[str] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample SCREAMING_SNAKE_CASE__ : str = new_scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample SCREAMING_SNAKE_CASE__ : Tuple = new_scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _a ( self ) -> List[str]: """simple docstring""" pass def _a ( self , _a=0 , **_a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : str = kwargs.pop("""num_inference_steps""" , lowercase_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_sample SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0.1 * sample SCREAMING_SNAKE_CASE__ : Any = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler_class(**lowercase_ ) scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE__ : Optional[int] = dummy_past_residuals[:] if time_step is None: SCREAMING_SNAKE_CASE__ : str = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler_class.from_pretrained(lowercase_ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_ ) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE__ : Optional[Any] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE__ : str = scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample SCREAMING_SNAKE_CASE__ : Any = new_scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE__ : List[Any] = scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample SCREAMING_SNAKE_CASE__ : List[Any] = new_scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _a ( self , **_a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : List[str] = self.get_scheduler_config(**lowercase_ ) SCREAMING_SNAKE_CASE__ : List[str] = scheduler_class(**lowercase_ ) SCREAMING_SNAKE_CASE__ : Tuple = 10 SCREAMING_SNAKE_CASE__ : Optional[Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : List[str] = model(lowercase_ , lowercase_ ) SCREAMING_SNAKE_CASE__ : Any = scheduler.step(lowercase_ , lowercase_ , lowercase_ ).prev_sample for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : List[Any] = model(lowercase_ , lowercase_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler.step(lowercase_ , lowercase_ , lowercase_ ).prev_sample return sample def _a ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE__ : int = kwargs.pop("""num_inference_steps""" , lowercase_ ) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE__ : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Tuple = scheduler_class(**lowercase_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_sample SCREAMING_SNAKE_CASE__ : List[Any] = 0.1 * sample if num_inference_steps is not None and hasattr(lowercase_ , """set_timesteps""" ): scheduler.set_timesteps(lowercase_ ) elif num_inference_steps is not None and not hasattr(lowercase_ , """set_timesteps""" ): SCREAMING_SNAKE_CASE__ : List[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE__ : List[str] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE__ : List[str] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE__ : List[str] = scheduler.timesteps[5] SCREAMING_SNAKE_CASE__ : Tuple = scheduler.timesteps[6] SCREAMING_SNAKE_CASE__ : int = scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample SCREAMING_SNAKE_CASE__ : Dict = scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample SCREAMING_SNAKE_CASE__ : Tuple = scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _a ( self ) -> Tuple: """simple docstring""" for timesteps in [100, 1_000]: self.check_over_configs(num_train_timesteps=lowercase_ , time_step=lowercase_ ) def _a ( self ) -> Optional[int]: """simple docstring""" for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=lowercase_ , time_step=lowercase_ ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.full_loop() SCREAMING_SNAKE_CASE__ : Tuple = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 2_540_529 ) < 10
132
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase_ : Dict = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } UpperCAmelCase_ : List[str] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = GPTaTokenizer def __init__( self : Optional[int] , lowercase_ : int=None , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple="<|endoftext|>" , lowercase_ : str="<|endoftext|>" , lowercase_ : Dict="<|endoftext|>" , lowercase_ : Tuple=False , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , lowercase_ , tokenizer_file=lowercase_ , unk_token=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , add_prefix_space=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''add_bos_token''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('''add_prefix_space''' , lowercase_) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase_ , pre_tok_state.pop('''type''')) SCREAMING_SNAKE_CASE_ : str = add_prefix_space SCREAMING_SNAKE_CASE_ : Dict = pre_tok_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = add_prefix_space def _SCREAMING_SNAKE_CASE ( self : str , *lowercase_ : List[Any] , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''is_split_into_words''' , lowercase_) assert self.add_prefix_space or not is_split_into_words, ( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : List[str] , **lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.get('''is_split_into_words''' , lowercase_) assert self.add_prefix_space or not is_split_into_words, ( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._encode_plus(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self._tokenizer.model.save(lowercase_ , name=lowercase_) return tuple(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : "Conversation"): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase_ , add_special_tokens=lowercase_) + [self.eos_token_id]) if len(lowercase_) > self.model_max_length: SCREAMING_SNAKE_CASE_ : Any = input_ids[-self.model_max_length :] return input_ids
91
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase : int = { """configuration_poolformer""": [ """POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PoolFormerConfig""", """PoolFormerOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = ["""PoolFormerFeatureExtractor"""] lowerCamelCase : int = ["""PoolFormerImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ """POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """PoolFormerForImageClassification""", """PoolFormerModel""", """PoolFormerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys lowerCamelCase : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
47
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(lowercase_ , '''hidden_sizes''')) self.parent.assertTrue(hasattr(lowercase_ , '''num_attention_heads''')) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Union[str, Any] , lowercase_ : List[Any]=13 , lowercase_ : Dict=64 , lowercase_ : Dict=3 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=2 , lowercase_ : Any=1 , lowercase_ : List[Any]=16 , lowercase_ : int=[128, 256, 384] , lowercase_ : str=[4, 6, 8] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Union[str, Any]=[16, 16, 16] , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[int]=[2, 2, 2] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=0.02 , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[int]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = kernel_size SCREAMING_SNAKE_CASE_ : Optional[Any] = stride SCREAMING_SNAKE_CASE_ : List[str] = padding SCREAMING_SNAKE_CASE_ : int = hidden_sizes SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : int = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = key_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_ratio SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = LevitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1) SCREAMING_SNAKE_CASE_ : Dict = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4) * ceil(width / 4), self.hidden_sizes[-1]) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitModelTester(self) SCREAMING_SNAKE_CASE_ : List[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return @unittest.skip(reason='''Levit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : str = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.model_tester.depths) + 1 self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) SCREAMING_SNAKE_CASE_ : Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) model.gradient_checkpointing_enable() model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowercase_), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'): SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''title'''] SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''num_labels'''] SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_ : str = inputs['''labels'''].unsqueeze(1).repeat(1 , problem_type['''num_labels''']) SCREAMING_SNAKE_CASE_ : Any = inputs['''labels'''].to(problem_type['''dtype''']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowercase_) as warning_list: SCREAMING_SNAKE_CASE_ : int = model(**lowercase_).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'Something is going wrong in the regression problem: intercepted {w.message}') loss.backward() @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = LevitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([1.04_48, -0.37_45, -1.83_17]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
91
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_squeezebert import SqueezeBertTokenizer _UpperCAmelCase : str = logging.get_logger(__name__) _UpperCAmelCase : str = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} _UpperCAmelCase : Union[str, Any] = { """vocab_file""": { """squeezebert/squeezebert-uncased""": ( """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt""" ), """squeezebert/squeezebert-mnli""": """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt""", """squeezebert/squeezebert-mnli-headless""": ( """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """squeezebert/squeezebert-uncased""": ( """https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json""" ), """squeezebert/squeezebert-mnli""": ( """https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json""" ), """squeezebert/squeezebert-mnli-headless""": ( """https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json""" ), }, } _UpperCAmelCase : Optional[Any] = { """squeezebert/squeezebert-uncased""": 512, """squeezebert/squeezebert-mnli""": 512, """squeezebert/squeezebert-mnli-headless""": 512, } _UpperCAmelCase : Any = { """squeezebert/squeezebert-uncased""": {"""do_lower_case""": True}, """squeezebert/squeezebert-mnli""": {"""do_lower_case""": True}, """squeezebert/squeezebert-mnli-headless""": {"""do_lower_case""": True}, } class lowercase ( UpperCAmelCase__ ): __lowercase : int = VOCAB_FILES_NAMES __lowercase : List[str] = PRETRAINED_VOCAB_FILES_MAP __lowercase : Tuple = PRETRAINED_INIT_CONFIGURATION __lowercase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase : List[Any] = SqueezeBertTokenizer def __init__( self , A_=None , A_=None , A_=True , A_="[UNK]" , A_="[SEP]" , A_="[PAD]" , A_="[CLS]" , A_="[MASK]" , A_=True , A_=None , **A_ , ) -> Dict: """simple docstring""" super().__init__( lowercase_ , tokenizer_file=lowercase_ , do_lower_case=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , pad_token=lowercase_ , cls_token=lowercase_ , mask_token=lowercase_ , tokenize_chinese_chars=lowercase_ , strip_accents=lowercase_ , **lowercase_ , ) UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , lowercase_ ) != do_lower_case or normalizer_state.get('strip_accents' , lowercase_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , lowercase_ ) != tokenize_chinese_chars ): UpperCamelCase = getattr(lowercase_ , normalizer_state.pop('type' ) ) UpperCamelCase = do_lower_case UpperCamelCase = strip_accents UpperCamelCase = tokenize_chinese_chars UpperCamelCase = normalizer_class(**lowercase_ ) UpperCamelCase = do_lower_case def __UpperCamelCase ( self , A_ , A_=None ) -> List[str]: """simple docstring""" UpperCamelCase = [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 __UpperCamelCase ( self , A_ , A_ = None ) -> List[str]: """simple docstring""" UpperCamelCase = [self.sep_token_id] UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCamelCase ( self , A_ , A_ = None ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = self._tokenizer.model.save(lowercase_ , name=lowercase_ ) return tuple(lowercase_ )
222
"""simple docstring""" from math import factorial def _A (__a = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[str] = n // 2 return int(factorial(__a ) / (factorial(__a ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCAmelCase_ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
91
0
"""simple docstring""" import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging __UpperCamelCase : int = logging.get_logger(__name__) def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ ): lowerCAmelCase__ : int = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(__a ) == len(__a ), f'{len(__a )} != {len(__a )}' dest_layers.load_state_dict(layers_to_copy.state_dict() ) __UpperCamelCase : Dict = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 1_2: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 1_1], 4: [0, 4, 8, 1_1], 6: [0, 2, 4, 7, 9, 1_1], 9: [0, 1, 2, 4, 5, 7, 9, 1_0, 1_1], 1_2: list(range(1_2)), }, 1_6: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 1_5], 3: [0, 8, 1_5], 4: [0, 5, 1_0, 1_5], 6: [0, 3, 6, 9, 1_2, 1_5], 8: [0, 2, 4, 6, 8, 1_0, 1_2, 1_5], 9: [0, 1, 3, 5, 7, 9, 1_1, 1_3, 1_5], 1_2: [0, 1, 2, 3, 4, 5, 6, 7, 9, 1_1, 1_3, 1_5], 1_6: list(range(1_6)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } __UpperCamelCase : List[str] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 1_2: {1: [1_1], 2: [5, 1_1], 3: [3, 7, 1_1], 6: [1, 3, 5, 8, 1_0, 1_1]}, 1_6: {1: [1_5], 4: [4, 9, 1_2, 1_5], 8: [1, 3, 5, 7, 9, 1_1, 1_3, 1_5]}, } def __SCREAMING_SNAKE_CASE ( A_ , A_ ): try: lowerCAmelCase__ : Tuple = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( f'no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first' f' {n_student}' ) return list(range(__a ) ) def __SCREAMING_SNAKE_CASE ( A_ , A_ ): if n_student > n_teacher: raise ValueError(f'Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}' ) elif n_teacher == n_student: return list(range(__a ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def __SCREAMING_SNAKE_CASE ( A_ , A_ = "student" , A_ = None , A_ = None , A_=False , A_=None , A_=None , **A_ , ): lowerCAmelCase__ : int = '''encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.''' assert (e is not None) or (d is not None), _msg if isinstance(__a , __a ): AutoTokenizer.from_pretrained(__a ).save_pretrained(__a ) # purely for convenience lowerCAmelCase__ : Tuple = AutoModelForSeqaSeqLM.from_pretrained(__a ).eval() else: assert isinstance(__a , __a ), f'teacher must be a model or string got type {type(__a )}' lowerCAmelCase__ : Tuple = teacher.config.to_diff_dict() try: lowerCAmelCase__ : List[Any] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: lowerCAmelCase__ : List[Any] = teacher_e if d is None: lowerCAmelCase__ : Tuple = teacher_d init_kwargs.update({'''encoder_layers''': e, '''decoder_layers''': d} ) except AttributeError: # T5 if hasattr(teacher.config , '''num_encoder_layers''' ): lowerCAmelCase__ : Optional[int] = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: lowerCAmelCase__ : int = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: lowerCAmelCase__ : Tuple = teacher_e if d is None: lowerCAmelCase__ : Union[str, Any] = teacher_d if hasattr(teacher.config , '''num_encoder_layers''' ): init_kwargs.update({'''num_encoder_layers''': e, '''num_decoder_layers''': d} ) else: init_kwargs.update({'''num_layers''': e, '''num_decoder_layers''': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(__a ) # Copy weights lowerCAmelCase__ : List[str] = teacher.config_class(**__a ) lowerCAmelCase__ : str = AutoModelForSeqaSeqLM.from_config(__a ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. lowerCAmelCase__ : Optional[Any] = student.load_state_dict(teacher.state_dict() , strict=__a ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save lowerCAmelCase__ : Tuple = list(range(__a ) ), list(range(__a ) ) logger.info( f'Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to' f' {save_path}' ) student.save_pretrained(__a ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: lowerCAmelCase__ : List[int] = pick_layers_to_copy(__a , __a ) if d_layers_to_copy is None: lowerCAmelCase__ : List[int] = pick_layers_to_copy(__a , __a ) try: if hasattr( __a , '''prophetnet''' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , __a ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , __a ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , __a ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , __a ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , __a ) copy_layers(teacher.decoder.block , student.decoder.block , __a ) logger.info( f'Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}' ) lowerCAmelCase__ : Optional[Any] = { '''teacher_type''': teacher.config.model_type, '''copied_encoder_layers''': e_layers_to_copy, '''copied_decoder_layers''': d_layers_to_copy, } student.save_pretrained(__a ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
106
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCAmelCase_ : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *lowercase_ : List[str] , **lowercase_ : List[str]): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
0
"""simple docstring""" import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class A_ (UpperCAmelCase__ ,unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = TextToVideoSDPipeline SCREAMING_SNAKE_CASE__ : List[str] = TEXT_TO_IMAGE_PARAMS SCREAMING_SNAKE_CASE__ : str = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. SCREAMING_SNAKE_CASE__ : List[Any] = frozenset( [ """num_inference_steps""", """generator""", """latents""", """return_dict""", """callback""", """callback_steps""", ] ) def UpperCamelCase__ ( self ): """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) UpperCAmelCase_ : Optional[Any] = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=lowercase_ , set_alpha_to_one=lowercase_ , ) torch.manual_seed(0 ) UpperCAmelCase_ : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="gelu" , projection_dim=512 , ) UpperCAmelCase_ : List[Any] = CLIPTextModel(lowercase_ ) UpperCAmelCase_ : Tuple = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) UpperCAmelCase_ : str = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, } return components def UpperCamelCase__ ( self , lowercase_ , lowercase_=0 ): """simple docstring""" if str(lowercase_ ).startswith("mps" ): UpperCAmelCase_ : Optional[Any] = torch.manual_seed(lowercase_ ) else: UpperCAmelCase_ : int = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) UpperCAmelCase_ : Union[str, Any] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''pt''', } return inputs def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Optional[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ : Any = self.get_dummy_components() UpperCAmelCase_ : List[Any] = TextToVideoSDPipeline(**lowercase_ ) UpperCAmelCase_ : Optional[Any] = sd_pipe.to(lowercase_ ) sd_pipe.set_progress_bar_config(disable=lowercase_ ) UpperCAmelCase_ : Optional[int] = self.get_dummy_inputs(lowercase_ ) UpperCAmelCase_ : Tuple = '''np''' UpperCAmelCase_ : List[Any] = sd_pipe(**lowercase_ ).frames UpperCAmelCase_ : Union[str, Any] = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) UpperCAmelCase_ : List[str] = np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase__ ( self ): """simple docstring""" self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowercase_ , expected_max_diff=3E-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def UpperCamelCase__ ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowercase_ , expected_max_diff=1E-2 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def UpperCamelCase__ ( self ): """simple docstring""" pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def UpperCamelCase__ ( self ): """simple docstring""" pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def UpperCamelCase__ ( self ): """simple docstring""" pass def UpperCamelCase__ ( self ): """simple docstring""" return super().test_progress_bar() @slow @skip_mps class A_ (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy" ) UpperCAmelCase_ : Optional[int] = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" ) UpperCAmelCase_ : str = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) UpperCAmelCase_ : Tuple = pipe.to("cuda" ) UpperCAmelCase_ : List[str] = '''Spiderman is surfing''' UpperCAmelCase_ : Any = torch.Generator(device="cpu" ).manual_seed(0 ) UpperCAmelCase_ : str = pipe(lowercase_ , generator=lowercase_ , num_inference_steps=25 , output_type="pt" ).frames UpperCAmelCase_ : Optional[Any] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2 def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Optional[int] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy" ) UpperCAmelCase_ : List[str] = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b" ) UpperCAmelCase_ : Tuple = pipe.to("cuda" ) UpperCAmelCase_ : Tuple = '''Spiderman is surfing''' UpperCAmelCase_ : int = torch.Generator(device="cpu" ).manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe(lowercase_ , generator=lowercase_ , num_inference_steps=2 , output_type="pt" ).frames UpperCAmelCase_ : List[Any] = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2
61
"""simple docstring""" from __future__ import annotations class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : int = 0): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = key def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(lowercase_) ^ key) for ch in content] def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : int = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[str] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE_ : List[Any] = '''''' for ch in content: ans += chr(ord(lowercase_) ^ key) return ans def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : int = 0): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''encrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(lowercase_ , lowercase_)) except OSError: return False return True def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : str , lowercase_ : int): '''simple docstring''' assert isinstance(lowercase_ , lowercase_) and isinstance(lowercase_ , lowercase_) try: with open(lowercase_) as fin, open('''decrypt.out''' , '''w+''') as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(lowercase_ , lowercase_)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
91
0
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING _lowerCamelCase : int = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[Any] , *lowercase : Optional[int] , **lowercase : List[str] ): '''simple docstring''' super().__init__(*lowercase_ , **lowercase_ ) requires_backends(self , 'vision' ) self.check_model_type(lowercase_ ) def __call__( self : List[Any] , lowercase : Union[str, List[str], "Image.Image", List["Image.Image"]] , **lowercase : Any ): '''simple docstring''' return super().__call__(lowercase_ , **lowercase_ ) def A ( self : Union[str, Any] , **lowercase : List[Any] ): '''simple docstring''' return {}, {}, {} def A ( self : List[str] , lowercase : Optional[int] ): '''simple docstring''' _snake_case = load_image(lowercase_ ) _snake_case = image.size _snake_case = self.image_processor(images=lowercase_ , return_tensors=self.framework ) return model_inputs def A ( self : int , lowercase : Optional[Any] ): '''simple docstring''' _snake_case = self.model(**lowercase_ ) return model_outputs def A ( self : Any , lowercase : Optional[Any] ): '''simple docstring''' _snake_case = model_outputs.predicted_depth _snake_case = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='bicubic' , align_corners=lowercase_ ) _snake_case = prediction.squeeze().cpu().numpy() _snake_case = (output * 255 / np.max(lowercase_ )).astype('uint8' ) _snake_case = Image.fromarray(lowercase_ ) _snake_case = {} _snake_case = predicted_depth _snake_case = depth return output_dict
282
"""simple docstring""" def _A (__a = 50 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f'''{solution() = }''')
91
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__:Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[int] = {} class snake_case__ ( UpperCAmelCase__ ): _snake_case : Union[str, Any] = """llama""" _snake_case : Optional[int] = ["""past_key_values"""] def __init__( self , lowerCamelCase=32000 , lowerCamelCase=4096 , lowerCamelCase=11008 , lowerCamelCase=32 , lowerCamelCase=32 , lowerCamelCase=None , lowerCamelCase="silu" , lowerCamelCase=2048 , lowerCamelCase=0.02 , lowerCamelCase=1E-6 , lowerCamelCase=True , lowerCamelCase=0 , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=1 , lowerCamelCase=False , lowerCamelCase=None , **lowerCamelCase , ): __a = vocab_size __a = max_position_embeddings __a = hidden_size __a = intermediate_size __a = num_hidden_layers __a = num_attention_heads # for backward compatibility if num_key_value_heads is None: __a = num_attention_heads __a = num_key_value_heads __a = hidden_act __a = initializer_range __a = rms_norm_eps __a = pretraining_tp __a = use_cache __a = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , tie_word_embeddings=lowercase_ , **lowercase_ , ) def a__ ( self ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , lowercase_ ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " F"got {self.rope_scaling}" ) __a = self.rope_scaling.get("type" , lowercase_ ) __a = self.rope_scaling.get("factor" , lowercase_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(lowercase_ , lowercase_ ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}" )
261
"""simple docstring""" import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = (PNDMScheduler,) __UpperCamelCase = (("num_inference_steps", 5_0),) def _SCREAMING_SNAKE_CASE ( self : Any , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**lowercase_) return config def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[str]=0 , **lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : List[str] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = self.dummy_sample SCREAMING_SNAKE_CASE_ : List[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : Dict = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class.from_pretrained(lowercase_) new_scheduler.set_timesteps(lowercase_) # copy over dummy past residuals SCREAMING_SNAKE_CASE_ : Optional[Any] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Dict = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : List[str]=0 , **lowercase_ : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Optional[Any] = kwargs.pop('''num_inference_steps''' , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.1 * sample SCREAMING_SNAKE_CASE_ : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Dict = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Union[str, Any] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Dict = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler_class.from_pretrained(lowercase_) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE_ : Any = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Optional[Any] = new_scheduler.step_prk(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Tuple = new_scheduler.step_plms(lowercase_ , lowercase_ , lowercase_ , **lowercase_).prev_sample assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical" def _SCREAMING_SNAKE_CASE ( self : str , **lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_scheduler_config(**lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Dict = 10 SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_model() SCREAMING_SNAKE_CASE_ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_) for i, t in enumerate(scheduler.prk_timesteps): SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample for i, t in enumerate(scheduler.plms_timesteps): SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : List[str] = scheduler.step_plms(lowercase_ , lowercase_ , lowercase_).prev_sample return sample def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = dict(self.forward_default_kwargs) SCREAMING_SNAKE_CASE_ : Dict = kwargs.pop('''num_inference_steps''' , lowercase_) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : Tuple = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[Any] = scheduler_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.dummy_sample SCREAMING_SNAKE_CASE_ : Any = 0.1 * sample if num_inference_steps is not None and hasattr(lowercase_ , '''set_timesteps'''): scheduler.set_timesteps(lowercase_) elif num_inference_steps is not None and not hasattr(lowercase_ , '''set_timesteps'''): SCREAMING_SNAKE_CASE_ : Optional[Any] = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE_ : str = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE_ : Optional[int] = dummy_past_residuals[:] SCREAMING_SNAKE_CASE_ : Dict = scheduler.step_prk(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : List[Any] = scheduler.step_prk(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler.step_plms(lowercase_ , 0 , lowercase_ , **lowercase_).prev_sample SCREAMING_SNAKE_CASE_ : Any = scheduler.step_plms(lowercase_ , 1 , lowercase_ , **lowercase_).prev_sample self.assertEqual(output_a.shape , sample.shape) self.assertEqual(output_a.shape , output_a.shape) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config(steps_offset=1) SCREAMING_SNAKE_CASE_ : Tuple = scheduler_class(**lowercase_) scheduler.set_timesteps(10) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]) , ) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for beta_start, beta_end in zip([0.00_01, 0.0_01] , [0.0_02, 0.02]): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100]): self.check_over_forward(num_inference_steps=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = 27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE_ : List[Any] = self.dummy_sample SCREAMING_SNAKE_CASE_ : str = 0.1 * sample SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Optional[int] = scheduler_class(**lowercase_) scheduler.set_timesteps(lowercase_) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2]): SCREAMING_SNAKE_CASE_ : int = scheduler.step_prk(lowercase_ , lowercase_ , lowercase_).prev_sample def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' with self.assertRaises(lowercase_): SCREAMING_SNAKE_CASE_ : int = self.scheduler_classes[0] SCREAMING_SNAKE_CASE_ : List[str] = self.get_scheduler_config() SCREAMING_SNAKE_CASE_ : Dict = scheduler_class(**lowercase_) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample).prev_sample def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.full_loop() SCREAMING_SNAKE_CASE_ : List[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_98.13_18) < 1e-2 assert abs(result_mean.item() - 0.25_80) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.full_loop(prediction_type='''v_prediction''') SCREAMING_SNAKE_CASE_ : str = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 67.39_86) < 1e-2 assert abs(result_mean.item() - 0.08_78) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : Optional[Any] = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : Any = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 2_30.03_99) < 1e-2 assert abs(result_mean.item() - 0.29_95) < 1e-3 def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01) SCREAMING_SNAKE_CASE_ : int = torch.sum(torch.abs(lowercase_)) SCREAMING_SNAKE_CASE_ : List[str] = torch.mean(torch.abs(lowercase_)) assert abs(result_sum.item() - 1_86.94_82) < 1e-2 assert abs(result_mean.item() - 0.24_34) < 1e-3
91
0
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging SCREAMING_SNAKE_CASE_:str = logging.get_logger(__name__) def __UpperCamelCase ( _lowerCAmelCase=None , _lowerCAmelCase=None ) -> int: """simple docstring""" return field(default_factory=lambda: default , metadata=__a ) @dataclass class SCREAMING_SNAKE_CASE__ : '''simple docstring''' __lowerCamelCase : Optional[Any] = list_field( default=[] , metadata={ "help": ( "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version" " of all available models" ) } , ) __lowerCamelCase : Optional[Any] = list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) __lowerCamelCase : List[Any] = list_field( default=[8, 32, 128, 512] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) __lowerCamelCase : List[str] = field( default=UpperCAmelCase__ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) __lowerCamelCase : List[str] = field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) __lowerCamelCase : Any = field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) __lowerCamelCase : Dict = field(default=UpperCAmelCase__ , metadata={"help": "Use FP16 to accelerate inference."} ) __lowerCamelCase : Optional[Any] = field(default=UpperCAmelCase__ , metadata={"help": "Benchmark training of model"} ) __lowerCamelCase : Tuple = field(default=UpperCAmelCase__ , metadata={"help": "Verbose memory tracing"} ) __lowerCamelCase : Optional[int] = field( default=UpperCAmelCase__ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) __lowerCamelCase : Optional[Any] = field( default=UpperCAmelCase__ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) __lowerCamelCase : str = field(default=UpperCAmelCase__ , metadata={"help": "Trace memory line by line"} ) __lowerCamelCase : Dict = field(default=UpperCAmelCase__ , metadata={"help": "Save result to a CSV file"} ) __lowerCamelCase : Optional[Any] = field(default=UpperCAmelCase__ , metadata={"help": "Save all print statements in a log file"} ) __lowerCamelCase : List[str] = field(default=UpperCAmelCase__ , metadata={"help": "Whether to print environment information"} ) __lowerCamelCase : List[Any] = field( default=UpperCAmelCase__ , metadata={ "help": ( "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use" " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled" " for debugging / testing and on TPU." ) } , ) __lowerCamelCase : Optional[int] = field( default=F'''inference_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv."} , ) __lowerCamelCase : Optional[Any] = field( default=F'''inference_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv."} , ) __lowerCamelCase : str = field( default=F'''train_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) __lowerCamelCase : Dict = field( default=F'''train_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) __lowerCamelCase : List[str] = field( default=F'''env_info_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving environment information."} , ) __lowerCamelCase : List[Any] = field( default=F'''log_{round(time() )}.csv''' , metadata={"help": "Log filename used if print statements are saved in log."} , ) __lowerCamelCase : Tuple = field(default=3 , metadata={"help": "Times an experiment will be run."} ) __lowerCamelCase : Optional[Any] = field( default=UpperCAmelCase__ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def _lowerCAmelCase ( self ): warnings.warn( f'''The class {self.__class__} is deprecated. Hugging Face Benchmarking utils''' """ are deprecated in general and it is advised to use external Benchmarking libraries """ """ to benchmark Transformer models.""", lowercase_, ) def _lowerCAmelCase ( self ): return json.dumps(dataclasses.asdict(self ), indent=2 ) @property def _lowerCAmelCase ( self ): if len(self.models ) <= 0: raise ValueError( """Please make sure you provide at least one model name / model identifier, *e.g.* `--models""" """ bert-base-cased` or `args.models = [\'bert-base-cased\'].""" ) return self.models @property def _lowerCAmelCase ( self ): if not self.multi_process: return False elif self.is_tpu: logger.info("""Multiprocessing is currently not possible on TPU.""" ) return False else: return True
116
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)]) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ , config_name=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , config_name=lowercase_) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50) self.assertEqual(loaded_config.max_length , 20) self.assertEqual(loaded_config.max_time , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained('''gpt2''') SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_model_config(lowercase_) SCREAMING_SNAKE_CASE_ : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_ , lowercase_) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = GenerationConfig() SCREAMING_SNAKE_CASE_ : Any = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = generation_config.update(**lowercase_) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_ , lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_ , {'''foo''': '''bar'''}) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig() SCREAMING_SNAKE_CASE_ : List[str] = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir: generation_config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = GenerationConfig.from_pretrained(lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''') SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig.from_model_config(lowercase_) assert not hasattr(lowercase_ , '''foo''') # no new kwargs should be initialized if from config def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , lowercase_) self.assertEqual(default_config.num_beams , 1) SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , lowercase_) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str]): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-generation-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''test-generation-config''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Optional[int] = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_))
91
0
def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" return int(input_a == input_a == 0 ) def __lowerCamelCase ( ): """simple docstring""" print("Truth Table of NOR Gate:" ) print("| Input 1 | Input 2 | Output |" ) print(F"""| 0 | 0 | {nor_gate(0 , 0 )} |""" ) print(F"""| 0 | 1 | {nor_gate(0 , 1 )} |""" ) print(F"""| 1 | 0 | {nor_gate(1 , 0 )} |""" ) print(F"""| 1 | 1 | {nor_gate(1 , 1 )} |""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
130
"""simple docstring""" import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401 from coval.conll import reader, util from coval.eval import evaluator import datasets UpperCAmelCase_ : Optional[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase_ : List[str] = """\ @InProceedings{moosavi2019minimum, author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube}, title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection}, year = {2019}, booktitle = {Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)}, publisher = {Association for Computational Linguistics}, address = {Florence, Italy}, } @inproceedings{10.3115/1072399.1072405, author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette}, title = {A Model-Theoretic Coreference Scoring Scheme}, year = {1995}, isbn = {1558604022}, publisher = {Association for Computational Linguistics}, address = {USA}, url = {https://doi.org/10.3115/1072399.1072405}, doi = {10.3115/1072399.1072405}, booktitle = {Proceedings of the 6th Conference on Message Understanding}, pages = {45–52}, numpages = {8}, location = {Columbia, Maryland}, series = {MUC6 ’95} } @INPROCEEDINGS{Bagga98algorithmsfor, author = {Amit Bagga and Breck Baldwin}, title = {Algorithms for Scoring Coreference Chains}, booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference}, year = {1998}, pages = {563--566} } @INPROCEEDINGS{Luo05oncoreference, author = {Xiaoqiang Luo}, title = {On coreference resolution performance metrics}, booktitle = {In Proc. of HLT/EMNLP}, year = {2005}, pages = {25--32}, publisher = {URL} } @inproceedings{moosavi-strube-2016-coreference, title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\", author = \"Moosavi, Nafise Sadat and Strube, Michael\", booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\", month = aug, year = \"2016\", address = \"Berlin, Germany\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/P16-1060\", doi = \"10.18653/v1/P16-1060\", pages = \"632--642\", } """ UpperCAmelCase_ : Tuple = """\ CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which implements of the common evaluation metrics including MUC [Vilain et al, 1995], B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005], LEA [Moosavi and Strube, 2016] and the averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) [Denis and Baldridge, 2009a; Pradhan et al., 2011]. This wrapper of CoVal currently only work with CoNLL line format: The CoNLL format has one word per line with all the annotation for this word in column separated by spaces: Column Type Description 1 Document ID This is a variation on the document filename 2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc. 3 Word number 4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release. 5 Part-of-Speech 6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column. 7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\" 8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7. 9 Word sense This is the word sense of the word in Column 3. 10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data. 11 Named Entities These columns identifies the spans representing various named entities. 12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7. N Coreference Coreference chain information encoded in a parenthesis structure. More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md CoVal code was written by @ns-moosavi. Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py The test suite is taken from https://github.com/conll/reference-coreference-scorers/ Mention evaluation and the test suite are added by @andreasvc. Parsing CoNLL files is developed by Leo Born. """ UpperCAmelCase_ : Union[str, Any] = """ Calculates coreference evaluation metrics. Args: predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format. Each prediction is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format. Each reference is a word with its annotations as a string made of columns joined with spaces. Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation) See the details on the format in the description of the metric. keep_singletons: After extracting all mentions of key or system files, mentions whose corresponding coreference chain is of size one, are considered as singletons. The default evaluation mode will include singletons in evaluations if they are included in the key or the system files. By setting 'keep_singletons=False', all singletons in the key and system files will be excluded from the evaluation. NP_only: Most of the recent coreference resolvers only resolve NP mentions and leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs. min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans. Minimum spans are determined using the MINA algorithm. Returns: 'mentions': mentions 'muc': MUC metric [Vilain et al, 1995] 'bcub': B-cubed [Bagga and Baldwin, 1998] 'ceafe': CEAFe [Luo et al., 2005] 'lea': LEA [Moosavi and Strube, 2016] 'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe) Examples: >>> coval = datasets.load_metric('coval') >>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -', ... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)', ... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)', ... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -', ... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -', ... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -'] >>> references = [words] >>> predictions = [words] >>> results = coval.compute(predictions=predictions, references=references) >>> print(results) # doctest:+ELLIPSIS {'mentions/recall': 1.0,[...] 'conll_score': 100.0} """ def _A (__a , __a , __a=False , __a=False , __a=True , __a=False , __a="dummy_doc" ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : int = {doc: key_lines} SCREAMING_SNAKE_CASE_ : List[str] = {doc: sys_lines} SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : Dict = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Tuple = 0 SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = reader.get_doc_mentions(__a , key_doc_lines[doc] , __a ) key_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = reader.get_doc_mentions(__a , sys_doc_lines[doc] , __a ) sys_singletons_num += singletons_num if NP_only or min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = reader.set_annotated_parse_trees(__a , key_doc_lines[doc] , __a , __a ) if remove_nested: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) key_nested_coref_num += nested_mentions key_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = reader.remove_nested_coref_mentions(__a , __a ) sys_nested_coref_num += nested_mentions sys_removed_nested_clusters += removed_clusters SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = reader.get_mention_assignments(__a , __a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster) if remove_nested: logger.info( '''Number of removed nested coreferring mentions in the key ''' f'annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}' ) logger.info( '''Number of resulting singleton clusters in the key ''' f'annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}' ) if not keep_singletons: logger.info( f'{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system ' '''files, respectively''' ) return doc_coref_infos def _A (__a , __a , __a , __a , __a , __a , __a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = get_coref_infos(__a , __a , __a , __a , __a , __a ) SCREAMING_SNAKE_CASE_ : str = {} SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE_ : str = 0 for name, metric in metrics: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = evaluator.evaluate_documents(__a , __a , beta=1 ) if name in ["muc", "bcub", "ceafe"]: conll += fa conll_subparts_num += 1 output_scores.update({f'{name}/recall': recall, f'{name}/precision': precision, f'{name}/f1': fa} ) logger.info( name.ljust(10 ) , f'Recall: {recall * 1_00:.2f}' , f' Precision: {precision * 1_00:.2f}' , f' F1: {fa * 1_00:.2f}' , ) if conll_subparts_num == 3: SCREAMING_SNAKE_CASE_ : Tuple = (conll / 3) * 1_00 logger.info(f'CoNLL score: {conll:.2f}' ) output_scores.update({'''conll_score''': conll} ) return output_scores def _A (__a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = False for line in key_lines: if not line.startswith('''#''' ): if len(line.split() ) > 6: SCREAMING_SNAKE_CASE_ : Any = line.split()[5] if not parse_col == "-": SCREAMING_SNAKE_CASE_ : Any = True break else: break return has_gold_parse @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''')), '''references''': datasets.Sequence(datasets.Value('''string''')), }) , codebase_urls=['''https://github.com/ns-moosavi/coval'''] , reference_urls=[ '''https://github.com/ns-moosavi/coval''', '''https://www.aclweb.org/anthology/P16-1060''', '''http://www.conll.cemantix.org/2012/data.html''', ] , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Dict=True , lowercase_ : Optional[Any]=False , lowercase_ : Optional[Any]=False , lowercase_ : Dict=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = [ ('''mentions''', evaluator.mentions), ('''muc''', evaluator.muc), ('''bcub''', evaluator.b_cubed), ('''ceafe''', evaluator.ceafe), ('''lea''', evaluator.lea), ] if min_span: SCREAMING_SNAKE_CASE_ : Union[str, Any] = util.check_gold_parse_annotation(lowercase_) if not has_gold_parse: raise NotImplementedError('''References should have gold parse annotation to use \'min_span\'.''') # util.parse_key_file(key_file) # key_file = key_file + ".parsed" SCREAMING_SNAKE_CASE_ : Optional[Any] = evaluate( key_lines=lowercase_ , sys_lines=lowercase_ , metrics=lowercase_ , NP_only=lowercase_ , remove_nested=lowercase_ , keep_singletons=lowercase_ , min_span=lowercase_ , ) return score
91
0
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class A__ ( UpperCAmelCase__ ): lowerCAmelCase__ : List[str] = "megatron-bert" def __init__( self : int , _UpperCAmelCase : int=2_90_56 , _UpperCAmelCase : Dict=10_24 , _UpperCAmelCase : Optional[Any]=24 , _UpperCAmelCase : Union[str, Any]=16 , _UpperCAmelCase : Optional[int]=40_96 , _UpperCAmelCase : Union[str, Any]="gelu" , _UpperCAmelCase : List[str]=0.1 , _UpperCAmelCase : Optional[Any]=0.1 , _UpperCAmelCase : int=5_12 , _UpperCAmelCase : Optional[Any]=2 , _UpperCAmelCase : Union[str, Any]=0.02 , _UpperCAmelCase : Optional[Any]=1e-1_2 , _UpperCAmelCase : Optional[Any]=0 , _UpperCAmelCase : Dict="absolute" , _UpperCAmelCase : Any=True , **_UpperCAmelCase : List[str] , ) -> Optional[int]: """simple docstring""" super().__init__(pad_token_id=lowercase_ , **lowercase_ ) __lowercase = vocab_size __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = hidden_act __lowercase = intermediate_size __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = max_position_embeddings __lowercase = type_vocab_size __lowercase = initializer_range __lowercase = layer_norm_eps __lowercase = position_embedding_type __lowercase = use_cache
325
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : Tuple = """▁""" UpperCAmelCase_ : Optional[Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCAmelCase_ : str = { """vocab_file""": { """facebook/xglm-564M""": """https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model""", } } UpperCAmelCase_ : str = { """facebook/xglm-564M""": 2048, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[Any] , lowercase_ : str , lowercase_ : Tuple="<s>" , lowercase_ : Any="</s>" , lowercase_ : Optional[int]="</s>" , lowercase_ : List[Any]="<s>" , lowercase_ : Union[str, Any]="<unk>" , lowercase_ : Union[str, Any]="<pad>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Tuple , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer SCREAMING_SNAKE_CASE_ : List[str] = 7 SCREAMING_SNAKE_CASE_ : Tuple = [F'<madeupword{i}>' for i in range(self.num_madeup_words)] SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''additional_special_tokens''' , []) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , sep_token=lowercase_ , cls_token=lowercase_ , pad_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowercase_)) SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE_ : Optional[Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} SCREAMING_SNAKE_CASE_ : List[Any] = len(self.sp_model) SCREAMING_SNAKE_CASE_ : Optional[Any] = {F'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)} self.fairseq_tokens_to_ids.update(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Optional[int] = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs'''): SCREAMING_SNAKE_CASE_ : Union[str, Any] = {} SCREAMING_SNAKE_CASE_ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a SCREAMING_SNAKE_CASE_ : Dict = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None , lowercase_ : bool = 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_)) return [1] + ([0] * len(lowercase_)) + [1, 1] + ([0] * len(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a) * [0] @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = {self.convert_ids_to_tokens(lowercase_): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : str): '''simple docstring''' return self.sp_model.encode(lowercase_ , out_type=lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : Union[str, Any]): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE_ : Optional[Any] = self.sp_model.PieceToId(lowercase_) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any]): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(lowercase_).replace(lowercase_ , ''' ''').strip() return out_string def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' if not os.path.isdir(lowercase_): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return SCREAMING_SNAKE_CASE_ : List[Any] = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase_) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , lowercase_) elif not os.path.isfile(self.vocab_file): with open(lowercase_ , '''wb''') as fi: SCREAMING_SNAKE_CASE_ : int = self.sp_model.serialized_model_proto() fi.write(lowercase_) return (out_vocab_file,)
91
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) __a = {"""configuration_vit""": ["""VIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTConfig""", """ViTOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = ["""ViTFeatureExtractor"""] __a = ["""ViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ """VIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ViTForImageClassification""", """ViTForMaskedImageModeling""", """ViTModel""", """ViTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ """TFViTForImageClassification""", """TFViTModel""", """TFViTPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ """FlaxViTForImageClassification""", """FlaxViTModel""", """FlaxViTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
145
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Dict = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] SCREAMING_SNAKE_CASE_ : List[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(lowercase_ , variant=lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] SCREAMING_SNAKE_CASE_ : str = '''fp16''' self.assertFalse(is_safetensors_compatible(lowercase_ , variant=lowercase_))
91
0
"""simple docstring""" import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a :str = """▁""" a :List[Any] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class __a (UpperCAmelCase__ , unittest.TestCase): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = BigBirdTokenizer _SCREAMING_SNAKE_CASE :List[str] = BigBirdTokenizerFast _SCREAMING_SNAKE_CASE :Dict = True _SCREAMING_SNAKE_CASE :List[str] = True def _a ( self ) -> Optional[int]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : Any = self.tokenizer_class(lowercase_ , keep_accents=lowercase_ ) tokenizer.save_pretrained(self.tmpdirname ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '''<s>''' SCREAMING_SNAKE_CASE__ : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_ ) , lowercase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_ ) , lowercase_ ) def _a ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<unk>""" ) self.assertEqual(vocab_keys[1] , """<s>""" ) self.assertEqual(vocab_keys[-1] , """[MASK]""" ) self.assertEqual(len(lowercase_ ) , 1_004 ) def _a ( self ) -> List[str]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def _a ( self ) -> List[Any]: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = '''I was born in 92000, and this is falsé.''' SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.tokenize(lowercase_ ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer.tokenize(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode(lowercase_ ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer.encode(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) def _a ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = BigBirdTokenizer(lowercase_ , keep_accents=lowercase_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(lowercase_ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase_ ) , [285, 46, 10, 170, 382] , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.convert_tokens_to_ids(lowercase_ ) self.assertListEqual( lowercase_ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) SCREAMING_SNAKE_CASE__ : Dict = tokenizer.convert_ids_to_tokens(lowercase_ ) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def _a ( self ) -> List[str]: """simple docstring""" return BigBirdTokenizer.from_pretrained("""google/bigbird-roberta-base""" ) @slow def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = '''Hello World!''' SCREAMING_SNAKE_CASE__ : List[Any] = [65, 18_536, 2_260, 101, 66] self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_ ) ) @slow def _a ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) # fmt: off SCREAMING_SNAKE_CASE__ : List[str] = [65, 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, 66] # noqa: E231 # fmt: on self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_ ) ) @require_torch @slow def _a ( self ) -> Optional[Any]: """simple docstring""" import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence SCREAMING_SNAKE_CASE__ : List[Any] = list(self.big_tokenizer.get_vocab().keys() )[:10] SCREAMING_SNAKE_CASE__ : str = ''' '''.join(lowercase_ ) SCREAMING_SNAKE_CASE__ : str = self.big_tokenizer.encode_plus(lowercase_ , return_tensors="""pt""" , return_token_type_ids=lowercase_ ) SCREAMING_SNAKE_CASE__ : int = self.big_tokenizer.batch_encode_plus( [sequence + """ """ + sequence] , return_tensors="""pt""" , return_token_type_ids=lowercase_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = BigBirdConfig(attention_type="""original_full""" ) SCREAMING_SNAKE_CASE__ : int = BigBirdModel(lowercase_ ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**lowercase_ ) model(**lowercase_ ) @slow def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = BigBirdTokenizer.from_pretrained("""google/bigbird-roberta-base""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(tokenizer("""Paris is the [MASK].""" ).input_ids ) self.assertTrue(decoded_text == """[CLS] Paris is the[MASK].[SEP]""" ) @slow def _a ( self ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = {'''input_ids''': [[65, 39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114, 66], [65, 448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase_ , model_name="""google/bigbird-roberta-base""" , revision="""215c99f1600e06f83acce68422f2035b2b5c3510""" , )
132
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable UpperCAmelCase_ : str = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Dict = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[str] = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys UpperCAmelCase_ : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
0
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : Optional[int] , _UpperCamelCase : Dict ) -> float: """simple docstring""" def get_matched_characters(_UpperCamelCase : Optional[Any] , _UpperCamelCase : Any ) -> str: _SCREAMING_SNAKE_CASE =[] _SCREAMING_SNAKE_CASE =min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): _SCREAMING_SNAKE_CASE =int(max(0 , i - limit ) ) _SCREAMING_SNAKE_CASE =int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(__a ) _SCREAMING_SNAKE_CASE =f"{_stra[0:_stra.index(__a )]} {_stra[_stra.index(__a ) + 1:]}" return "".join(__a ) # matching characters _SCREAMING_SNAKE_CASE =get_matched_characters(__a , __a ) _SCREAMING_SNAKE_CASE =get_matched_characters(__a , __a ) _SCREAMING_SNAKE_CASE =len(__a ) # transposition _SCREAMING_SNAKE_CASE =( len([(ca, ca) for ca, ca in zip(__a , __a ) if ca != ca] ) // 2 ) if not match_count: _SCREAMING_SNAKE_CASE =0.0 else: _SCREAMING_SNAKE_CASE =( 1 / 3 * ( match_count / len(__a ) + match_count / len(__a ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters _SCREAMING_SNAKE_CASE =0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
47
"""simple docstring""" import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py UpperCAmelCase_ : Optional[int] = """src/transformers""" UpperCAmelCase_ : Tuple = """docs/source/en""" UpperCAmelCase_ : Optional[Any] = """.""" def _A (__a , __a , __a ) -> Dict: """simple docstring""" with open(__a , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: SCREAMING_SNAKE_CASE_ : Dict = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE_ : List[Any] = 0 while not lines[start_index].startswith(__a ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ : Tuple = start_index while not lines[end_index].startswith(__a ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCAmelCase_ : Optional[Any] = """Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. UpperCAmelCase_ : int = re.compile(r"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") UpperCAmelCase_ : Dict = re.compile(r"""Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCAmelCase_ : int = re.compile(r"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase_ : Optional[int] = direct_transformers_import(TRANSFORMERS_PATH) def _A (__a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , __a ) return [m.group(0 ) for m in matches] def _A (__a , __a ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = 2 if text == '''✅''' or text == '''❌''' else len(__a ) SCREAMING_SNAKE_CASE_ : Tuple = (width - text_length) // 2 SCREAMING_SNAKE_CASE_ : Tuple = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _A () -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE_ : Tuple = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } SCREAMING_SNAKE_CASE_ : List[Any] = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : List[str] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = collections.defaultdict(__a ) SCREAMING_SNAKE_CASE_ : int = collections.defaultdict(__a ) # Let's lookup through all transformers object (once). for attr_name in dir(__a ): SCREAMING_SNAKE_CASE_ : Any = None if attr_name.endswith('''Tokenizer''' ): SCREAMING_SNAKE_CASE_ : Dict = slow_tokenizers SCREAMING_SNAKE_CASE_ : Dict = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = fast_tokenizers SCREAMING_SNAKE_CASE_ : Optional[Any] = attr_name[:-13] elif _re_tf_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : int = tf_models SCREAMING_SNAKE_CASE_ : Dict = _re_tf_models.match(__a ).groups()[0] elif _re_flax_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : Any = flax_models SCREAMING_SNAKE_CASE_ : Tuple = _re_flax_models.match(__a ).groups()[0] elif _re_pt_models.match(__a ) is not None: SCREAMING_SNAKE_CASE_ : str = pt_models SCREAMING_SNAKE_CASE_ : int = _re_pt_models.match(__a ).groups()[0] if lookup_dict is not None: while len(__a ) > 0: if attr_name in model_name_to_prefix.values(): SCREAMING_SNAKE_CASE_ : List[str] = True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE_ : Optional[int] = ''''''.join(camel_case_split(__a )[:-1] ) # Let's build that table! SCREAMING_SNAKE_CASE_ : Any = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) SCREAMING_SNAKE_CASE_ : Any = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support'''] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). SCREAMING_SNAKE_CASE_ : List[str] = [len(__a ) + 2 for c in columns] SCREAMING_SNAKE_CASE_ : str = max([len(__a ) for name in model_names] ) + 2 # Build the table per se SCREAMING_SNAKE_CASE_ : List[Any] = '''|''' + '''|'''.join([_center_text(__a , __a ) for c, w in zip(__a , __a )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" SCREAMING_SNAKE_CASE_ : Union[str, Any] = {True: '''✅''', False: '''❌'''} for name in model_names: SCREAMING_SNAKE_CASE_ : str = model_name_to_prefix[name] SCREAMING_SNAKE_CASE_ : int = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__a , __a ) for l, w in zip(__a , __a )] ) + "|\n" return table def _A (__a=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = _find_text_in_file( filename=os.path.join(__a , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) SCREAMING_SNAKE_CASE_ : Tuple = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__a , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCAmelCase_ : Any = parser.parse_args() check_model_table(args.fix_and_overwrite)
91
0
from pathlib import Path import numpy as np from PIL import Image def A ( lowercase ) -> np.ndarray: '''simple docstring''' UpperCamelCase = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2_9_8_9 * r + 0.5_8_7_0 * g + 0.1_1_4_0 * b def A ( lowercase ) -> np.ndarray: '''simple docstring''' return (gray > 127) & (gray <= 255) def A ( lowercase , lowercase ) -> np.ndarray: '''simple docstring''' UpperCamelCase = np.zeros_like(__a ) UpperCamelCase = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image UpperCamelCase = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): UpperCamelCase = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() UpperCamelCase = int(summation > 0 ) return output if __name__ == "__main__": # read original image _UpperCAmelCase : Dict = Path(__file__).resolve().parent / """image_data""" / """lena.jpg""" _UpperCAmelCase : int = np.array(Image.open(lena_path)) # kernel to be applied _UpperCAmelCase : Union[str, Any] = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) _UpperCAmelCase : Union[str, Any] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image _UpperCAmelCase : List[Any] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
222
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : List[Any] , lowercase_ : List[str]=13 , lowercase_ : int=7 , lowercase_ : Any=True , lowercase_ : str=True , lowercase_ : List[Any]=True , lowercase_ : List[Any]=True , lowercase_ : Dict=99 , lowercase_ : Union[str, Any]=24 , lowercase_ : int=2 , lowercase_ : List[str]=6 , lowercase_ : Any=37 , lowercase_ : Dict="gelu" , lowercase_ : List[str]=0.1 , lowercase_ : Dict=0.1 , lowercase_ : Union[str, Any]=512 , lowercase_ : List[str]=16 , lowercase_ : Any=2 , lowercase_ : Any=0.02 , lowercase_ : List[Any]=3 , lowercase_ : Optional[int]=None , lowercase_ : str=1000 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = seq_length SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE_ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = vocab_size SCREAMING_SNAKE_CASE_ : List[str] = hidden_size SCREAMING_SNAKE_CASE_ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE_ : Tuple = intermediate_size SCREAMING_SNAKE_CASE_ : Tuple = hidden_act SCREAMING_SNAKE_CASE_ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE_ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE_ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE_ : Any = initializer_range SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE_ : Tuple = scope SCREAMING_SNAKE_CASE_ : Optional[int] = range_bbox def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 3] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 1] SCREAMING_SNAKE_CASE_ : str = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE_ : List[str] = bbox[i, j, 2] SCREAMING_SNAKE_CASE_ : Optional[int] = bbox[i, j, 0] SCREAMING_SNAKE_CASE_ : List[str] = t SCREAMING_SNAKE_CASE_ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE_ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) SCREAMING_SNAKE_CASE_ : Union[str, Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) SCREAMING_SNAKE_CASE_ : List[str] = None SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE_ : Any = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LiltConfig( 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 , ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = LiltModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , bbox=lowercase_ , token_type_ids=lowercase_) SCREAMING_SNAKE_CASE_ : int = model(lowercase_ , bbox=lowercase_) 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 _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : int , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE_ : Optional[Any] = LiltForTokenClassification(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Tuple = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : str , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LiltForQuestionAnswering(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model( lowercase_ , bbox=lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) 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 _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : List[str] = config_and_inputs SCREAMING_SNAKE_CASE_ : str = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : List[str] , lowercase_ : Optional[int] , lowercase_ : Optional[int] , lowercase_ : str , lowercase_ : str): '''simple docstring''' return True def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = LiltModelTester(self) SCREAMING_SNAKE_CASE_ : Optional[int] = ConfigTester(self , config_class=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE_ : Dict = type self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[int] = LiltModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) @require_torch @slow class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''').to(lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.tensor([[1, 2]] , device=lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Dict = model(input_ids=lowercase_ , bbox=lowercase_) SCREAMING_SNAKE_CASE_ : str = torch.Size([1, 2, 768]) SCREAMING_SNAKE_CASE_ : Dict = torch.tensor( [[-0.06_53, 0.09_50, -0.00_61], [-0.05_45, 0.09_26, -0.03_24]] , device=lowercase_ , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase_) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase_ , atol=1e-3))
91
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig __UpperCamelCase : Optional[int] = { """google/tapas-base-finetuned-sqa""": ( """https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json""" ), """google/tapas-base-finetuned-wtq""": ( """https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json""" ), """google/tapas-base-finetuned-wikisql-supervised""": ( """https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json""" ), """google/tapas-base-finetuned-tabfact""": ( """https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( UpperCAmelCase__ ): """simple docstring""" lowercase__ = "tapas" def __init__( self : List[str] ,lowercase_ : Tuple=3_0_5_2_2 ,lowercase_ : str=7_6_8 ,lowercase_ : List[str]=1_2 ,lowercase_ : str=1_2 ,lowercase_ : str=3_0_7_2 ,lowercase_ : str="gelu" ,lowercase_ : Optional[int]=0.1 ,lowercase_ : Union[str, Any]=0.1 ,lowercase_ : Tuple=1_0_2_4 ,lowercase_ : Union[str, Any]=[3, 2_5_6, 2_5_6, 2, 2_5_6, 2_5_6, 1_0] ,lowercase_ : Union[str, Any]=0.02 ,lowercase_ : List[Any]=1E-12 ,lowercase_ : Dict=0 ,lowercase_ : Tuple=10.0 ,lowercase_ : Optional[int]=0 ,lowercase_ : Optional[int]=1.0 ,lowercase_ : List[str]=None ,lowercase_ : Optional[Any]=1.0 ,lowercase_ : int=False ,lowercase_ : Any=None ,lowercase_ : List[Any]=1.0 ,lowercase_ : List[Any]=1.0 ,lowercase_ : Any=False ,lowercase_ : Optional[int]=False ,lowercase_ : Dict="ratio" ,lowercase_ : Tuple=None ,lowercase_ : Optional[int]=None ,lowercase_ : List[str]=6_4 ,lowercase_ : Tuple=3_2 ,lowercase_ : Optional[int]=False ,lowercase_ : int=True ,lowercase_ : Any=False ,lowercase_ : Optional[int]=False ,lowercase_ : str=True ,lowercase_ : Optional[Any]=False ,lowercase_ : str=None ,lowercase_ : str=None ,**lowercase_ : List[str] ,): super().__init__(pad_token_id=lowercase_ ,**lowercase_ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) lowerCAmelCase__ : Dict = vocab_size lowerCAmelCase__ : Optional[Any] = hidden_size lowerCAmelCase__ : int = num_hidden_layers lowerCAmelCase__ : str = num_attention_heads lowerCAmelCase__ : List[Any] = hidden_act lowerCAmelCase__ : Optional[Any] = intermediate_size lowerCAmelCase__ : Optional[int] = hidden_dropout_prob lowerCAmelCase__ : List[Any] = attention_probs_dropout_prob lowerCAmelCase__ : str = max_position_embeddings lowerCAmelCase__ : Dict = type_vocab_sizes lowerCAmelCase__ : List[Any] = initializer_range lowerCAmelCase__ : List[Any] = layer_norm_eps # Fine-tuning task hyperparameters lowerCAmelCase__ : Dict = positive_label_weight lowerCAmelCase__ : Dict = num_aggregation_labels lowerCAmelCase__ : Optional[Any] = aggregation_loss_weight lowerCAmelCase__ : List[str] = use_answer_as_supervision lowerCAmelCase__ : Tuple = answer_loss_importance lowerCAmelCase__ : str = use_normalized_answer_loss lowerCAmelCase__ : str = huber_loss_delta lowerCAmelCase__ : List[str] = temperature lowerCAmelCase__ : Optional[Any] = aggregation_temperature lowerCAmelCase__ : Union[str, Any] = use_gumbel_for_cells lowerCAmelCase__ : List[str] = use_gumbel_for_aggregation lowerCAmelCase__ : Tuple = average_approximation_function lowerCAmelCase__ : Any = cell_selection_preference lowerCAmelCase__ : Tuple = answer_loss_cutoff lowerCAmelCase__ : str = max_num_rows lowerCAmelCase__ : Any = max_num_columns lowerCAmelCase__ : int = average_logits_per_cell lowerCAmelCase__ : Dict = select_one_column lowerCAmelCase__ : Union[str, Any] = allow_empty_column_selection lowerCAmelCase__ : int = init_cell_selection_weights_to_zero lowerCAmelCase__ : Union[str, Any] = reset_position_index_per_cell lowerCAmelCase__ : Union[str, Any] = disable_per_token_loss # Aggregation hyperparameters lowerCAmelCase__ : List[str] = aggregation_labels lowerCAmelCase__ : Any = no_aggregation_label_index if isinstance(self.aggregation_labels ,lowercase_ ): lowerCAmelCase__ : Dict = {int(lowercase_ ): v for k, v in aggregation_labels.items()}
106
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) UpperCAmelCase_ : Dict = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase_ : List[str] = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) UpperCAmelCase_ : Optional[Any] = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: UpperCAmelCase_ : Union[str, Any] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") UpperCAmelCase_ : Any = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase_ : List[Any] = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase_ : Dict = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
91
0
"""simple docstring""" from ....utils import logging _a = logging.get_logger(__name__) class A_ (UpperCAmelCase__ ): '''simple docstring''' def __init__( self , lowercase_ , lowercase_=None , lowercase_=2048 ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = config.__dict__ UpperCAmelCase_ : Any = modal_hidden_size if num_labels: UpperCAmelCase_ : Union[str, Any] = num_labels
61
"""simple docstring""" from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) def _A (__a , __a ) -> Tuple: """simple docstring""" try: with open(__a , '''rb''' ) as flax_state_f: SCREAMING_SNAKE_CASE_ : Optional[int] = from_bytes(__a , flax_state_f.read() ) except UnpicklingError as e: try: with open(__a ) as f: if f.read().startswith('''version''' ): raise OSError( '''You seem to have cloned a repository without having git-lfs installed. Please''' ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the''' ''' folder you cloned.''' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(__a , __a ) def _A (__a , __a ) -> Tuple: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE_ : Optional[int] = flatten_dict(jax.tree_util.tree_map(lambda __a : x.dtype == jnp.bfloataa , __a ) ).values() if any(__a ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) SCREAMING_SNAKE_CASE_ : Optional[Any] = jax.tree_util.tree_map( lambda __a : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , __a ) SCREAMING_SNAKE_CASE_ : int = '''''' SCREAMING_SNAKE_CASE_ : str = flatten_dict(__a , sep='''.''' ) SCREAMING_SNAKE_CASE_ : List[Any] = pt_model.state_dict() # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE_ : str = [] SCREAMING_SNAKE_CASE_ : Any = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple.split('''.''' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: SCREAMING_SNAKE_CASE_ : Any = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[Any] = jnp.transpose(__a , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": SCREAMING_SNAKE_CASE_ : Tuple = flax_key_tuple_array[:-1] + ['''weight'''] SCREAMING_SNAKE_CASE_ : Optional[int] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": SCREAMING_SNAKE_CASE_ : Optional[int] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(__a ): SCREAMING_SNAKE_CASE_ : List[str] = ( flax_key_tuple_string.replace('''_0''' , '''.0''' ) .replace('''_1''' , '''.1''' ) .replace('''_2''' , '''.2''' ) .replace('''_3''' , '''.3''' ) .replace('''_4''' , '''.4''' ) .replace('''_5''' , '''.5''' ) .replace('''_6''' , '''.6''' ) .replace('''_7''' , '''.7''' ) .replace('''_8''' , '''.8''' ) .replace('''_9''' , '''.9''' ) ) SCREAMING_SNAKE_CASE_ : Optional[Any] = '''.'''.join(__a ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE_ : Optional[int] = np.asarray(__a ) if not isinstance(__a , np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.from_numpy(__a ) # remove from missing keys missing_keys.remove(__a ) else: # weight is not expected by PyTorch model unexpected_keys.append(__a ) pt_model.load_state_dict(__a ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE_ : int = list(__a ) if len(__a ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) if len(__a ) > 0: logger.warning( f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) return pt_model
91
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Optional[int] = logging.get_logger(__name__) _lowerCamelCase : int = { """uw-madison/mra-base-512-4""": """https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): '''simple docstring''' _UpperCAmelCase : Union[str, Any] = "mra" def __init__( self : int , lowercase : Union[str, Any]=50_265 , lowercase : Tuple=768 , lowercase : Optional[Any]=12 , lowercase : Tuple=12 , lowercase : Optional[int]=3_072 , lowercase : Optional[Any]="gelu" , lowercase : Union[str, Any]=0.1 , lowercase : Optional[Any]=0.1 , lowercase : Optional[Any]=512 , lowercase : Union[str, Any]=1 , lowercase : Optional[int]=0.02 , lowercase : Optional[Any]=1E-5 , lowercase : int="absolute" , lowercase : Tuple=4 , lowercase : Any="full" , lowercase : int=0 , lowercase : List[Any]=0 , lowercase : List[Any]=1 , lowercase : Optional[int]=0 , lowercase : Optional[Any]=2 , **lowercase : Tuple , ): '''simple docstring''' super().__init__(pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_ ) _snake_case = vocab_size _snake_case = max_position_embeddings _snake_case = hidden_size _snake_case = num_hidden_layers _snake_case = num_attention_heads _snake_case = intermediate_size _snake_case = hidden_act _snake_case = hidden_dropout_prob _snake_case = attention_probs_dropout_prob _snake_case = initializer_range _snake_case = type_vocab_size _snake_case = layer_norm_eps _snake_case = position_embedding_type _snake_case = block_per_row _snake_case = approx_mode _snake_case = initial_prior_first_n_blocks _snake_case = initial_prior_diagonal_n_blocks
282
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Any = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "openai-gpt" __UpperCamelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , lowercase_ : List[str]=40478 , lowercase_ : List[str]=512 , lowercase_ : Optional[Any]=768 , lowercase_ : Tuple=12 , lowercase_ : Tuple=12 , lowercase_ : Union[str, Any]="gelu" , lowercase_ : List[Any]=0.1 , lowercase_ : Tuple=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : List[Any]=1e-5 , lowercase_ : int=0.02 , lowercase_ : Optional[int]="cls_index" , lowercase_ : Any=True , lowercase_ : List[Any]=None , lowercase_ : List[str]=True , lowercase_ : Optional[Any]=0.1 , **lowercase_ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE_ : Tuple = n_positions SCREAMING_SNAKE_CASE_ : Optional[int] = n_embd SCREAMING_SNAKE_CASE_ : Dict = n_layer SCREAMING_SNAKE_CASE_ : Any = n_head SCREAMING_SNAKE_CASE_ : Union[str, Any] = afn SCREAMING_SNAKE_CASE_ : int = resid_pdrop SCREAMING_SNAKE_CASE_ : List[str] = embd_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = attn_pdrop SCREAMING_SNAKE_CASE_ : Union[str, Any] = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[str] = summary_type SCREAMING_SNAKE_CASE_ : Tuple = summary_use_proj SCREAMING_SNAKE_CASE_ : Union[str, Any] = summary_activation SCREAMING_SNAKE_CASE_ : Any = summary_first_dropout SCREAMING_SNAKE_CASE_ : List[str] = summary_proj_to_labels super().__init__(**lowercase_)
91
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[Any] = {"""tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Any = { """tokenizer_file""": { """bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""", """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""", }, } class snake_case__ ( UpperCAmelCase__ ): _snake_case : Any = VOCAB_FILES_NAMES _snake_case : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _snake_case : List[str] = ["""input_ids""", """attention_mask"""] _snake_case : str = None def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<unk>" , lowerCamelCase="<s>" , lowerCamelCase="</s>" , lowerCamelCase="<pad>" , lowerCamelCase=False , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowercase_ , lowercase_ , tokenizer_file=lowercase_ , unk_token=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , pad_token=lowercase_ , add_prefix_space=lowercase_ , clean_up_tokenization_spaces=lowercase_ , **lowercase_ , ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowercase_ ) != add_prefix_space: __a = getattr(lowercase_ , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowercase_ ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowercase_ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._batch_encode_plus(*lowercase_ , **lowercase_ ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowercase_ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._encode_plus(*lowercase_ , **lowercase_ ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowercase_ , name=lowercase_ ) return tuple(lowercase_ ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase_ , add_special_tokens=lowercase_ ) + [self.eos_token_id] ) if len(lowercase_ ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
261
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : List[str] , *lowercase_ : Dict , **lowercase_ : Union[str, Any]): '''simple docstring''' warnings.warn( '''The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DeiTImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
0
import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.utils import logging logging.set_verbosity_info() # should not include what is already done by the `from_pt` argument SCREAMING_SNAKE_CASE_:str = { """/attention/""": """/0/SelfAttention/""", """/self_attention/""": """/0/SelfAttention/""", """/encoder_decoder_attention/""": """/1/EncDecAttention/""", """value""": """v""", """query""": """q""", """key""": """k""", """out""": """o""", """pre_self_attention_layer_norm""": """0/layer_norm""", """pre_cross_attention_layer_norm""": """1/layer_norm""", """pre_attention_layer_norm""": """0/layer_norm""", # previously 1, but seems wrong """token_embedder""": """shared""", """encoder_norm""": """final_layer_norm""", """decoder_norm""": """final_layer_norm""", """relpos_bias/rel_embedding""": """block/0/layer/0/SelfAttention/relative_attention_bias/weight""", """router/router_weights/w/""": """router/classifier/""", """roer/roer_weights/w/""": """router/classifier/""", """logits_dense""": """lm_head""", } def __UpperCamelCase ( _lowerCAmelCase ) -> Tuple: """simple docstring""" A : int = list(s_dict.keys() ) for key in keys: A : Tuple = R'''.*/layers_(\d+)''' A : Optional[Any] = key if re.match(__a , __a ): A : Tuple = re.sub(R"""layers_(\d+)""" , R"""block/\1/layer""" , __a ) A : Optional[int] = R'''(encoder|decoder)\/''' if re.match(__a , __a ): A : Optional[Any] = re.match(__a , __a ).groups() if groups[0] == "encoder": A : Optional[int] = re.sub(R"""/mlp/""" , R"""/1/mlp/""" , __a ) A : Optional[int] = re.sub(R"""/pre_mlp_layer_norm/""" , R"""/1/layer_norm/""" , __a ) elif groups[0] == "decoder": A : Optional[Any] = re.sub(R"""/mlp/""" , R"""/2/mlp/""" , __a ) A : List[Any] = re.sub(R"""/pre_mlp_layer_norm/""" , R"""/2/layer_norm/""" , __a ) # 2. Convert other classic mappings for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items(): if old_key in new_key: A : Optional[int] = new_key.replace(__a , __a ) print(f'''{key} -> {new_key}''' ) A : Union[str, Any] = s_dict.pop(__a ) if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: A : Optional[int] = s_dict[ '''encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight''' ].T if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: A : List[Any] = s_dict[ '''decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight''' ].T # 3. Take extra care of the EXPERTS layer for key in list(s_dict.keys() ): if "expert" in key: A : Any = s_dict[key].shape[0] A : Any = s_dict[key] for idx in range(__a ): A : str = expert_weihts[idx] print(f'''{key} -> {key.replace("expert/" , "nested fstring" )}''' ) s_dict.pop(__a ) return s_dict SCREAMING_SNAKE_CASE_:Tuple = { """NUM_ENCODER_LAYERS""": """num_layers""", """NUM_DECODER_LAYERS""": """num_decoder_layers""", """NUM_HEADS""": """num_heads""", """HEAD_DIM""": """d_kv""", """EMBED_DIM""": """d_model""", """MLP_DIM""": """d_ff""", """NUM_SELECTED_EXPERTS""": """num_selected_experts""", """NUM_ENCODER_SPARSE_LAYERS""": """num_sparse_encoder_layers""", """NUM_DECODER_SPARSE_LAYERS""": """num_sparse_decoder_layers""", """dense.MlpBlock.activations""": """feed_forward_proj""", } def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> List[Any]: """simple docstring""" import regex as re with open(__a , """r""" ) as f: A : List[Any] = f.read() A : Any = re.findall(R"""(.*) = ([0-9.]*)""" , __a ) A : Optional[int] = {} for param, value in regex_match: if param in GIN_TO_CONFIG_MAPPING and value != "": A : Union[str, Any] = float(__a ) if '''.''' in value else int(__a ) A : Dict = re.findall(R"""(.*activations) = \(\'(.*)\',\)""" , __a )[0] A : Optional[int] = str(activation[1] ) A : Optional[Any] = num_experts A : List[str] = SwitchTransformersConfig(**__a ) return config def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase="./" , _lowerCAmelCase=8 ) -> Union[str, Any]: """simple docstring""" print(f'''Loading flax weights from : {flax_checkpoint_path}''' ) A : Optional[int] = checkpoints.load_tax_checkpoint(__a ) if gin_file is not None: A : Optional[Any] = convert_gin_to_config(__a , __a ) else: A : int = SwitchTransformersConfig.from_pretrained(__a ) A : Dict = SwitchTransformersForConditionalGeneration(__a ) A : Dict = flax_params['''target'''] A : Any = flatten_dict(__a , sep="""/""" ) A : List[Any] = rename_keys(__a ) A : int = unflatten_dict(__a , sep="""/""" ) # Load the flax params in the PT model load_flax_weights_in_pytorch_model(__a , __a ) print(f'''Save PyTorch model to {pytorch_dump_path}''' ) pt_model.save_pretrained(__a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_:List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--switch_t5x_checkpoint_path""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the""" """ model architecture. If not provided, a `gin_file` has to be provided.""" ), ) parser.add_argument( """--gin_file""", default=None, type=str, required=False, help="""Path to the gin config file. If not provided, a `config_file` has to be passed """, ) parser.add_argument( """--config_name""", default=None, type=str, required=False, help="""Config name of SwitchTransformers model.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output pytorch model.""" ) parser.add_argument("""--num_experts""", default=8, type=int, required=False, help="""Number of experts""") SCREAMING_SNAKE_CASE_:Any = parser.parse_args() convert_flax_checkpoint_to_pytorch( args.switch_tax_checkpoint_path, args.config_name, args.gin_file, args.pytorch_dump_folder_path, args.num_experts, )
116
"""simple docstring""" import random from typing import Any def _A (__a ) -> list[Any]: """simple docstring""" for _ in range(len(__a ) ): SCREAMING_SNAKE_CASE_ : Optional[int] = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ : Tuple = random.randint(0 , len(__a ) - 1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = data[b], data[a] return data if __name__ == "__main__": UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5, 6, 7] UpperCAmelCase_ : Dict = ["""python""", """says""", """hello""", """!"""] print("""Fisher-Yates Shuffle:""") print("""List""", integers, strings) print("""FY Shuffle""", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
91
0
from manim import * class snake_case__(UpperCAmelCase__ ): """simple docstring""" def snake_case ( self : Union[str, Any] ): lowercase__ : Union[str, Any] = Rectangle(height=0.5 , width=0.5 ) lowercase__ : List[Any] = Rectangle(height=0.25 , width=0.25 ) lowercase__ : List[Any] = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) lowercase__ : Optional[Any] = [mem.copy() for i in range(6 )] lowercase__ : List[str] = [mem.copy() for i in range(6 )] lowercase__ : List[str] = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) lowercase__ : Dict = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) lowercase__ : Optional[Any] = VGroup(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0 ) lowercase__ : List[Any] = Text("CPU" , font_size=24 ) lowercase__ : Tuple = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowercase_ ) lowercase__ : Any = [mem.copy() for i in range(4 )] lowercase__ : Union[str, Any] = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) lowercase__ : List[str] = Text("GPU" , font_size=24 ) lowercase__ : Union[str, Any] = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) gpu.move_to([-1, -1, 0] ) self.add(lowercase_ ) lowercase__ : Optional[int] = [mem.copy() for i in range(6 )] lowercase__ : int = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) lowercase__ : List[Any] = Text("Model" , font_size=24 ) lowercase__ : Union[str, Any] = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) model.move_to([3, -1.0, 0] ) self.add(lowercase_ ) lowercase__ : Tuple = [] lowercase__ : int = [] lowercase__ : Any = [] for i, rect in enumerate(lowercase_ ): rect.set_stroke(lowercase_ ) lowercase__ : Optional[int] = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(lowercase_ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=lowercase_ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(model_cpu_arr[0] , direction=lowercase_ , buff=0.0 ) else: cpu_target.next_to(model_cpu_arr[i - 1] , direction=lowercase_ , buff=0.0 ) self.add(lowercase_ ) model_cpu_arr.append(lowercase_ ) self.add(*lowercase_ , *lowercase_ , *lowercase_ ) lowercase__ : Any = [mem.copy() for i in range(6 )] lowercase__ : Any = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) lowercase__ : Union[str, Any] = Text("Loaded Checkpoint" , font_size=24 ) lowercase__ : List[Any] = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) checkpoint.move_to([3, 0.5, 0] ) self.add(lowercase_ ) lowercase__ : Dict = [] lowercase__ : Dict = [] for i, rect in enumerate(lowercase_ ): lowercase__ : Any = fill.copy().set_fill(lowercase_ , opacity=0.7 ) target.move_to(lowercase_ ) ckpt_arr.append(lowercase_ ) lowercase__ : Any = target.copy() if i < 5: cpu_target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.move_to(cpu_right_col_base[i - 5] ) ckpt_cpu_arr.append(lowercase_ ) self.add(*lowercase_ , *lowercase_ ) lowercase__ : Union[str, Any] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowercase__ : int = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(lowercase_ , lowercase_ ) lowercase__ : List[Any] = MarkupText( f"""<span fgcolor=\'{BLUE}\'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(lowercase_ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(lowercase_ ) lowercase__ : List[Any] = MarkupText( f"""Based on the passed in configuration, weights are stored in\na variety of np.memmaps on disk or to a particular device.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) lowercase__ : List[str] = [meta_mem.copy() for i in range(6 )] lowercase__ : Any = [meta_mem.copy() for i in range(6 )] lowercase__ : Any = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) lowercase__ : Optional[Any] = VGroup(*lowercase_ ).arrange(lowercase_ , buff=0 ) lowercase__ : List[Any] = VGroup(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0 ) lowercase__ : Dict = Text("Disk" , font_size=24 ) lowercase__ : str = Group(lowercase_ , lowercase_ ).arrange(lowercase_ , buff=0.5 , aligned_edge=lowercase_ ) disk.move_to([-4.0, -1.25, 0] ) self.play(Write(lowercase_ , run_time=3 ) , Write(lowercase_ , run_time=1 ) , Create(lowercase_ , run_time=1 ) ) lowercase__ : int = [] for i, rect in enumerate(lowercase_ ): lowercase__ : List[Any] = rect.copy() target.generate_target() target.target.move_to(disk_left_col_base[i] ).scale(0.5 ) animations.append(MoveToTarget(lowercase_ , run_time=1.5 ) ) self.play(*lowercase_ ) self.play(FadeOut(lowercase_ ) ) lowercase__ : Any = MarkupText(f"""Then, the checkpoint is removed from memory\nthrough garbage collection.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(lowercase_ , run_time=3 ) ) self.play( FadeOut(lowercase_ , lowercase_ , *lowercase_ , *lowercase_ ) , ) self.wait()
130
"""simple docstring""" import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _A (__a , __a , __a ) -> Dict: """simple docstring""" if gpta_config_file == "": SCREAMING_SNAKE_CASE_ : Optional[Any] = GPTaConfig() else: SCREAMING_SNAKE_CASE_ : Tuple = GPTaConfig.from_json_file(__a ) SCREAMING_SNAKE_CASE_ : Optional[int] = GPTaModel(__a ) # Load weights from numpy load_tf_weights_in_gpta(__a , __a , __a ) # Save pytorch-model SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : List[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(f'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , __a ) print(f'Save configuration file to {pytorch_config_dump_path}' ) with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCAmelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--gpt2_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow 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( """--gpt2_config_file""", default="""""", type=str, help=( """An optional config json file corresponding to the pre-trained OpenAI model. \n""" """This specifies the model architecture.""" ), ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
91
0
from sklearn.metrics import fa_score import datasets SCREAMING_SNAKE_CASE__ = """ The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) """ SCREAMING_SNAKE_CASE__ = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives. - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {'f1': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results['f1'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results['f1'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\") >>> print(round(results['f1'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'f1': array([0.8, 0. , 0. ])} """ SCREAMING_SNAKE_CASE__ = """ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def a__ ( self : Tuple ) -> Tuple: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'] , ) def a__ ( self : List[str] , _UpperCAmelCase : str , _UpperCAmelCase : List[Any] , _UpperCAmelCase : int=None , _UpperCAmelCase : int=1 , _UpperCAmelCase : Any="binary" , _UpperCAmelCase : Dict=None ) -> List[str]: """simple docstring""" __lowercase = fa_score( lowercase_ , lowercase_ , labels=lowercase_ , pos_label=lowercase_ , average=lowercase_ , sample_weight=lowercase_ ) return {"f1": float(lowercase_ ) if score.size == 1 else score}
325
"""simple docstring""" from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
91
0
'''simple docstring''' 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 __UpperCAmelCase ( a_: Optional[int], a_: str ): _UpperCAmelCase : Optional[int] = { '''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 _UpperCAmelCase : Tuple = int(re.match(r".*layer_(\d*).*", __a )[1] ) layer_number -= 3 return f"""h.{layer_number}.""" + key def __UpperCAmelCase ( a_: Any ): if dtype == torch.bool: return 1 / 8 _UpperCAmelCase : Dict = re.search(r"[^\d](\d+)$", str(__a ) ) if bit_search is None: raise ValueError(f"""`dtype` is not a valid dtype: {dtype}.""" ) _UpperCAmelCase : int = int(bit_search.groups()[0] ) return bit_size // 8 def __UpperCAmelCase ( a_: int, a_: Dict, a_: Any, a_: List[Any], a_: List[Any] ): if bloom_config_file == "": _UpperCAmelCase : List[Any] = BloomConfig() else: _UpperCAmelCase : str = BloomConfig.from_json_file(__a ) if shard_model: _UpperCAmelCase : List[Any] = os.listdir(__a ) _UpperCAmelCase : List[str] = sorted(filter(lambda a_ : s.startswith("layer" ) and "model_00" in s, __a ) ) _UpperCAmelCase : List[str] = {'''weight_map''': {}, '''metadata''': {}} _UpperCAmelCase : Any = 0 _UpperCAmelCase : Dict = None _UpperCAmelCase : Optional[int] = BloomConfig() for j, file in enumerate(__a ): print("Processing file: {}".format(__a ) ) _UpperCAmelCase : Optional[Any] = None for i in range(__a ): # load all TP files _UpperCAmelCase : List[str] = file.replace("model_00", f"""model_0{i}""" ) _UpperCAmelCase : Tuple = torch.load(os.path.join(__a, __a ), map_location="cpu" ) # Rename keys in the transformers names _UpperCAmelCase : Optional[int] = list(temp.keys() ) for key in keys: _UpperCAmelCase : Dict = temp.pop(__a ) if tensors is None: _UpperCAmelCase : Any = temp else: for key in tensors.keys(): if any(key.endswith(__a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel _UpperCAmelCase : int = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks _UpperCAmelCase : Optional[int] = torch.cat([tensors[key], temp[key]], dim=__a ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(__a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): _UpperCAmelCase : Optional[Any] = tensors[key] / pretraining_tp torch.save( __a, os.path.join( __a, "pytorch_model_{}-of-{}.bin".format(str(j + 1 ).zfill(5 ), str(len(__a ) ).zfill(5 ) ), ), ) for key in tensors.keys(): _UpperCAmelCase : Union[str, Any] = tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: _UpperCAmelCase : str = '''pytorch_model_{}-of-{}.bin'''.format( str(j + 1 ).zfill(5 ), str(len(__a ) ).zfill(5 ) ) _UpperCAmelCase : List[str] = BloomConfig() _UpperCAmelCase : List[str] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME _UpperCAmelCase : Dict = total_size with open(__a, "w", encoding="utf-8" ) as f: f.write(config.to_json_string() ) with open(os.path.join(__a, WEIGHTS_NAME + ".index.json" ), "w", encoding="utf-8" ) as f: _UpperCAmelCase : Dict = json.dumps(__a, indent=2, sort_keys=__a ) + '''\n''' f.write(__a ) else: _UpperCAmelCase : str = BloomModel(__a ) _UpperCAmelCase : Optional[int] = os.listdir(__a ) _UpperCAmelCase : int = sorted(filter(lambda a_ : s.startswith("layer" ) and "model_00" in s, __a ) ) _UpperCAmelCase : Optional[Any] = None for i, file in enumerate(__a ): _UpperCAmelCase : Union[str, Any] = None for i in range(__a ): # load all TP files _UpperCAmelCase : List[Any] = file.replace("model_00", f"""model_0{i}""" ) _UpperCAmelCase : List[str] = torch.load(os.path.join(__a, __a ), map_location="cpu" ) # Rename keys in the transformers names _UpperCAmelCase : str = list(temp.keys() ) for key in keys: _UpperCAmelCase : Optional[int] = temp.pop(__a ) if tensors is None: _UpperCAmelCase : List[str] = temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(__a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel _UpperCAmelCase : List[Any] = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks _UpperCAmelCase : List[Any] = torch.cat([tensors[key], temp[key]], dim=__a ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(__a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): _UpperCAmelCase : str = tensors[key] / pretraining_tp _UpperCAmelCase : Tuple = model.load_state_dict(__a, strict=__a ) assert not other_keys.unexpected_keys, f"""The keys {other_keys.unexpected_keys} are unexpected""" if missing_keys is None: _UpperCAmelCase : List[Any] = set(other_keys.missing_keys ) else: _UpperCAmelCase : Tuple = missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, f"""The keys {missing_keys} are missing""" # Save pytorch-model os.makedirs(__a, exist_ok=__a ) _UpperCAmelCase : Optional[int] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME _UpperCAmelCase : Optional[Any] = 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: _UpperCAmelCase : List[str] = model.to(config.torch_dtype ) torch.save(model.state_dict(), __a ) print(f"""Save configuration file to {pytorch_config_dump_path}""" ) with open(__a, "w", encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __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, )
145
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType 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, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL UpperCAmelCase_ : int = logging.get_logger(__name__) def _A (__a ) -> List[List[ImageInput]]: """simple docstring""" if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self : Dict , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : bool = True , lowercase_ : Union[int, float] = 1 / 255 , lowercase_ : bool = True , lowercase_ : bool = True , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , **lowercase_ : Dict , ): '''simple docstring''' super().__init__(**lowercase_) SCREAMING_SNAKE_CASE_ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE_ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') SCREAMING_SNAKE_CASE_ : Optional[int] = do_resize SCREAMING_SNAKE_CASE_ : List[Any] = size SCREAMING_SNAKE_CASE_ : Tuple = do_center_crop SCREAMING_SNAKE_CASE_ : Dict = crop_size SCREAMING_SNAKE_CASE_ : List[Any] = resample SCREAMING_SNAKE_CASE_ : List[str] = do_rescale SCREAMING_SNAKE_CASE_ : List[str] = rescale_factor SCREAMING_SNAKE_CASE_ : List[Any] = offset SCREAMING_SNAKE_CASE_ : List[Any] = do_normalize SCREAMING_SNAKE_CASE_ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE_ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) if "shortest_edge" in size: SCREAMING_SNAKE_CASE_ : List[Any] = get_resize_output_image_size(lowercase_ , size['''shortest_edge'''] , default_to_square=lowercase_) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE_ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}') return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = get_size_dict(lowercase_) if "height" not in size or "width" not in size: raise ValueError(F'Size must have \'height\' and \'width\' as keys. Got {size.keys()}') return center_crop(lowercase_ , size=(size['''height'''], size['''width''']) , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : np.ndarray , lowercase_ : Union[int, float] , lowercase_ : bool = True , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Optional[int] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = image.astype(np.floataa) if offset: SCREAMING_SNAKE_CASE_ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : np.ndarray , lowercase_ : Union[float, List[float]] , lowercase_ : Union[float, List[float]] , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : List[str] , ): '''simple docstring''' return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str] , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , ): '''simple docstring''' 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_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.''') if offset and not do_rescale: raise ValueError('''For offset, do_rescale must also be set to True.''') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE_ : List[str] = to_numpy_array(lowercase_) if do_resize: SCREAMING_SNAKE_CASE_ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_) if do_center_crop: SCREAMING_SNAKE_CASE_ : Dict = self.center_crop(lowercase_ , size=lowercase_) if do_rescale: SCREAMING_SNAKE_CASE_ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_) if do_normalize: SCREAMING_SNAKE_CASE_ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_) return image def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : bool = None , lowercase_ : float = None , lowercase_ : bool = None , lowercase_ : bool = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[float, List[float]]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : ChannelDimension = ChannelDimension.FIRST , **lowercase_ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE_ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE_ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE_ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE_ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE_ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE_ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE_ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE_ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE_ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE_ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_) SCREAMING_SNAKE_CASE_ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE_ : Dict = get_size_dict(lowercase_ , param_name='''crop_size''') if not valid_images(lowercase_): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''') SCREAMING_SNAKE_CASE_ : Tuple = make_batched(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
91
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType 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, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a :int = logging.get_logger(__name__) def _lowercase ( __lowerCAmelCase ) -> List[List[ImageInput]]: if isinstance(__a , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(__a , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(__a ): return [[videos]] raise ValueError(F'''Could not make batched video from {videos}''' ) class __a (UpperCAmelCase__): '''simple docstring''' _SCREAMING_SNAKE_CASE :Tuple = ["""pixel_values"""] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BILINEAR , _a = True , _a = None , _a = True , _a = 1 / 255 , _a = True , _a = True , _a = None , _a = None , **_a , ) -> Optional[Any]: """simple docstring""" super().__init__(**lowercase_ ) SCREAMING_SNAKE_CASE__ : str = size if size is not None else {'''shortest_edge''': 256} SCREAMING_SNAKE_CASE__ : Optional[int] = get_size_dict(lowercase_ , default_to_square=lowercase_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} SCREAMING_SNAKE_CASE__ : Dict = get_size_dict(lowercase_ , param_name="""crop_size""" ) SCREAMING_SNAKE_CASE__ : Optional[int] = do_resize SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_center_crop SCREAMING_SNAKE_CASE__ : Dict = crop_size SCREAMING_SNAKE_CASE__ : List[Any] = resample SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : List[str] = rescale_factor SCREAMING_SNAKE_CASE__ : List[Any] = offset SCREAMING_SNAKE_CASE__ : List[Any] = do_normalize SCREAMING_SNAKE_CASE__ : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE__ : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _a ( self , _a , _a , _a = PILImageResampling.BILINEAR , _a = None , **_a , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_ ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE__ : List[Any] = get_resize_output_image_size(lowercase_ , size["""shortest_edge"""] , default_to_square=lowercase_ ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE__ : Union[str, Any] = (size['''height'''], size['''width''']) else: raise ValueError(f'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' ) return resize(lowercase_ , size=lowercase_ , resample=lowercase_ , data_format=lowercase_ , **lowercase_ ) def _a ( self , _a , _a , _a = None , **_a , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = get_size_dict(lowercase_ ) if "height" not in size or "width" not in size: raise ValueError(f'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}''' ) return center_crop(lowercase_ , size=(size["""height"""], size["""width"""]) , data_format=lowercase_ , **lowercase_ ) def _a ( self , _a , _a , _a = True , _a = None , **_a , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = image.astype(np.floataa ) if offset: SCREAMING_SNAKE_CASE__ : Tuple = image - (scale / 2) return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_ ) def _a ( self , _a , _a , _a , _a = None , **_a , ) -> List[Any]: """simple docstring""" return normalize(lowercase_ , mean=lowercase_ , std=lowercase_ , data_format=lowercase_ , **lowercase_ ) def _a ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , ) -> List[str]: """simple docstring""" 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_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.""" ) if offset and not do_rescale: raise ValueError("""For offset, do_rescale must also be set to True.""" ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : List[str] = to_numpy_array(lowercase_ ) if do_resize: SCREAMING_SNAKE_CASE__ : List[Any] = self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_ ) if do_center_crop: SCREAMING_SNAKE_CASE__ : Dict = self.center_crop(lowercase_ , size=lowercase_ ) if do_rescale: SCREAMING_SNAKE_CASE__ : int = self.rescale(image=lowercase_ , scale=lowercase_ , offset=lowercase_ ) if do_normalize: SCREAMING_SNAKE_CASE__ : Dict = self.normalize(image=lowercase_ , mean=lowercase_ , std=lowercase_ ) SCREAMING_SNAKE_CASE__ : List[Any] = to_channel_dimension_format(lowercase_ , lowercase_ ) return image def _a ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : int = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE__ : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : Dict = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE__ : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE__ : Dict = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE__ : List[str] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE__ : Union[str, Any] = size if size is not None else self.size SCREAMING_SNAKE_CASE__ : Tuple = get_size_dict(lowercase_ , default_to_square=lowercase_ ) SCREAMING_SNAKE_CASE__ : Any = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE__ : Dict = get_size_dict(lowercase_ , param_name="""crop_size""" ) if not valid_images(lowercase_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) SCREAMING_SNAKE_CASE__ : Tuple = make_batched(lowercase_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [ [ self._preprocess_image( image=lowercase_ , do_resize=lowercase_ , size=lowercase_ , resample=lowercase_ , do_center_crop=lowercase_ , crop_size=lowercase_ , do_rescale=lowercase_ , rescale_factor=lowercase_ , offset=lowercase_ , do_normalize=lowercase_ , image_mean=lowercase_ , image_std=lowercase_ , data_format=lowercase_ , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE__ : int = {'''pixel_values''': videos} return BatchFeature(data=lowercase_ , tensor_type=lowercase_ )
132
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase_ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase_ : Dict = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } UpperCAmelCase_ : List[str] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = GPTaTokenizer def __init__( self : Optional[int] , lowercase_ : int=None , lowercase_ : List[str]=None , lowercase_ : Union[str, Any]=None , lowercase_ : Tuple="<|endoftext|>" , lowercase_ : str="<|endoftext|>" , lowercase_ : Dict="<|endoftext|>" , lowercase_ : Tuple=False , **lowercase_ : Optional[int] , ): '''simple docstring''' super().__init__( lowercase_ , lowercase_ , tokenizer_file=lowercase_ , unk_token=lowercase_ , bos_token=lowercase_ , eos_token=lowercase_ , add_prefix_space=lowercase_ , **lowercase_ , ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = kwargs.pop('''add_bos_token''' , lowercase_) SCREAMING_SNAKE_CASE_ : Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('''add_prefix_space''' , lowercase_) != add_prefix_space: SCREAMING_SNAKE_CASE_ : int = getattr(lowercase_ , pre_tok_state.pop('''type''')) SCREAMING_SNAKE_CASE_ : str = add_prefix_space SCREAMING_SNAKE_CASE_ : Dict = pre_tok_class(**lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = add_prefix_space def _SCREAMING_SNAKE_CASE ( self : str , *lowercase_ : List[Any] , **lowercase_ : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = kwargs.get('''is_split_into_words''' , lowercase_) assert self.add_prefix_space or not is_split_into_words, ( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowercase_ : List[str] , **lowercase_ : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = kwargs.get('''is_split_into_words''' , lowercase_) assert self.add_prefix_space or not is_split_into_words, ( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._encode_plus(*lowercase_ , **lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : str , lowercase_ : Optional[str] = None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = self._tokenizer.model.save(lowercase_ , name=lowercase_) return tuple(lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : "Conversation"): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowercase_ , add_special_tokens=lowercase_) + [self.eos_token_id]) if len(lowercase_) > self.model_max_length: SCREAMING_SNAKE_CASE_ : Any = input_ids[-self.model_max_length :] return input_ids
91
0
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class A__ ( unittest.TestCase ): def A ( self : Any ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) _SCREAMING_SNAKE_CASE =get_activation('gelu' ) self.assertTrue(torch.allclose(gelu_python(lowercase_ ) , torch_builtin(lowercase_ ) ) ) self.assertFalse(torch.allclose(gelu_python(lowercase_ ) , gelu_new(lowercase_ ) ) ) def A ( self : List[Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) _SCREAMING_SNAKE_CASE =get_activation('gelu' ) _SCREAMING_SNAKE_CASE =get_activation('gelu_10' ) _SCREAMING_SNAKE_CASE =torch_builtin(lowercase_ ) _SCREAMING_SNAKE_CASE =geluaa(lowercase_ ) _SCREAMING_SNAKE_CASE =torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(lowercase_ ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def A ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' get_activation('gelu' ) get_activation('gelu_10' ) get_activation('gelu_fast' ) get_activation('gelu_new' ) get_activation('gelu_python' ) get_activation('gelu_pytorch_tanh' ) get_activation('linear' ) get_activation('mish' ) get_activation('quick_gelu' ) get_activation('relu' ) get_activation('sigmoid' ) get_activation('silu' ) get_activation('swish' ) get_activation('tanh' ) with self.assertRaises(lowercase_ ): get_activation('bogus' ) with self.assertRaises(lowercase_ ): get_activation(lowercase_ ) def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =get_activation('gelu' ) _SCREAMING_SNAKE_CASE =1 _SCREAMING_SNAKE_CASE =get_activation('gelu' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(lowercase_ ): _SCREAMING_SNAKE_CASE =acta.a
47
"""simple docstring""" import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(lowercase_ , '''hidden_sizes''')) self.parent.assertTrue(hasattr(lowercase_ , '''num_attention_heads''')) class lowerCAmelCase__ : '''simple docstring''' def __init__( self : str , lowercase_ : Union[str, Any] , lowercase_ : List[Any]=13 , lowercase_ : Dict=64 , lowercase_ : Dict=3 , lowercase_ : Optional[Any]=3 , lowercase_ : List[Any]=2 , lowercase_ : Any=1 , lowercase_ : List[Any]=16 , lowercase_ : int=[128, 256, 384] , lowercase_ : str=[4, 6, 8] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Union[str, Any]=[16, 16, 16] , lowercase_ : Optional[Any]=0 , lowercase_ : Optional[int]=[2, 2, 2] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=0.02 , lowercase_ : Any=True , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[int]=2 , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = image_size SCREAMING_SNAKE_CASE_ : int = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = kernel_size SCREAMING_SNAKE_CASE_ : Optional[Any] = stride SCREAMING_SNAKE_CASE_ : List[str] = padding SCREAMING_SNAKE_CASE_ : int = hidden_sizes SCREAMING_SNAKE_CASE_ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE_ : int = depths SCREAMING_SNAKE_CASE_ : Optional[Any] = key_dim SCREAMING_SNAKE_CASE_ : Optional[Any] = drop_path_rate SCREAMING_SNAKE_CASE_ : Tuple = patch_size SCREAMING_SNAKE_CASE_ : Optional[Any] = attention_ratio SCREAMING_SNAKE_CASE_ : str = mlp_ratio SCREAMING_SNAKE_CASE_ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE_ : List[Any] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] SCREAMING_SNAKE_CASE_ : Any = is_training SCREAMING_SNAKE_CASE_ : Tuple = use_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE_ : str = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[int] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowercase_ : Any , lowercase_ : int , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = LevitModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) SCREAMING_SNAKE_CASE_ : Any = (self.image_size, self.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Tuple = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : List[Any] = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1) SCREAMING_SNAKE_CASE_ : Dict = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4) * ceil(width / 4), self.hidden_sizes[-1]) , ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.num_labels SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE_ : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": LevitModel, "image-classification": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = LevitModelTester(self) SCREAMING_SNAKE_CASE_ : List[Any] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return @unittest.skip(reason='''Levit does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' pass @unittest.skip(reason='''Levit does not output attentions''') def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Any = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[str] , lowercase_ : Optional[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Tuple = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : str = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Optional[int] = len(self.model_tester.depths) + 1 self.assertEqual(len(lowercase_) , lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = (self.model_tester.image_size, self.model_tester.image_size) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_size[0], image_size[1] for _ in range(4): SCREAMING_SNAKE_CASE_ : Optional[Any] = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) SCREAMING_SNAKE_CASE_ : Optional[int] = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Optional[int] = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple=False): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : Union[str, Any] = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Optional[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : Dict = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE_ : List[str] = model_class(lowercase_) model.gradient_checkpointing_enable() model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Dict = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = model(**lowercase_).loss loss.backward() def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(lowercase_), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'): SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''title'''] SCREAMING_SNAKE_CASE_ : Optional[int] = problem_type['''num_labels'''] SCREAMING_SNAKE_CASE_ : str = model_class(lowercase_) model.to(lowercase_) model.train() SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE_ : str = inputs['''labels'''].unsqueeze(1).repeat(1 , problem_type['''num_labels''']) SCREAMING_SNAKE_CASE_ : Any = inputs['''labels'''].to(problem_type['''dtype''']) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=lowercase_) as warning_list: SCREAMING_SNAKE_CASE_ : int = model(**lowercase_).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message): raise ValueError( F'Something is going wrong in the regression problem: intercepted {w.message}') loss.backward() @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[Any] = LevitModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to( lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.default_image_processor SCREAMING_SNAKE_CASE_ : str = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : Any = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : Tuple = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = torch.tensor([1.04_48, -0.37_45, -1.83_17]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4))
91
0
from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class lowercase : __lowercase : List[Any] = 42 __lowercase : Any = None __lowercase : Union[str, Any] = None _UpperCAmelCase : Dict = namedtuple("CoinsDistribResult", "moves excess") def A ( lowercase ) -> int: '''simple docstring''' if root is None: return 0 # Validation def count_nodes(lowercase ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(lowercase ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(__a ) != count_coins(__a ): raise ValueError('The nodes number should be same as the number of coins' ) # Main calculation def get_distrib(lowercase ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) UpperCamelCase = get_distrib(node.left ) UpperCamelCase = get_distrib(node.right ) UpperCamelCase = 1 - left_distrib_excess UpperCamelCase = 1 - right_distrib_excess UpperCamelCase = ( left_distrib_moves + right_distrib_moves + abs(__a ) + abs(__a ) ) UpperCamelCase = node.data - coins_to_left - coins_to_right return CoinsDistribResult(__a , __a ) return get_distrib(__a )[0] if __name__ == "__main__": import doctest doctest.testmod()
222
"""simple docstring""" from math import factorial def _A (__a = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[str] = n // 2 return int(factorial(__a ) / (factorial(__a ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCAmelCase_ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
91
0
"""simple docstring""" def __SCREAMING_SNAKE_CASE ( A_ ): lowerCAmelCase__ : Dict = current_set.copy() for row_index, row in enumerate(__a ): lowerCAmelCase__ : int = row[0] for column_index, column in enumerate(__a ): if magnitude == 0: lowerCAmelCase__ : str = column continue lowerCAmelCase__ : Union[str, Any] = column / magnitude # Subtract to cancel term lowerCAmelCase__ : Optional[Any] = current_set[0] lowerCAmelCase__ : Optional[int] = [first_row] lowerCAmelCase__ : Union[str, Any] = current_set[1::] for row in current_set: lowerCAmelCase__ : Optional[Any] = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__a ) continue for column_index in range(len(__a ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__a ) # Create next recursion iteration set if len(final_set[0] ) != 3: lowerCAmelCase__ : str = final_set[0] lowerCAmelCase__ : Optional[int] = [] lowerCAmelCase__ : int = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) lowerCAmelCase__ : Union[str, Any] = simplify(__a ) for i in range(len(__a ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __a ) lowerCAmelCase__ : Tuple = resultant return final_set def __SCREAMING_SNAKE_CASE ( A_ ): if len(__a ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) lowerCAmelCase__ : int = len(__a ) + 1 if any(len(__a ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__a , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__a ) == 1: return [equations[0][-1] / equations[0][0]] lowerCAmelCase__ : List[Any] = equations.copy() if any(0 in row for row in data_set ): lowerCAmelCase__ : Optional[Any] = data_set.copy() lowerCAmelCase__ : Optional[Any] = [] for row_index, row in enumerate(__a ): if 0 not in row: lowerCAmelCase__ : Any = data_set.pop(__a ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __a ) lowerCAmelCase__ : Optional[int] = data_set.copy() lowerCAmelCase__ : int = simplify(__a ) lowerCAmelCase__ : Optional[int] = simplified[::-1] lowerCAmelCase__ : list = [] for row in simplified: lowerCAmelCase__ : Dict = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue lowerCAmelCase__ : List[str] = row.copy()[: len(__a ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__a ) == 0: solutions.append(0 ) continue lowerCAmelCase__ : Any = temp_row[1::] lowerCAmelCase__ : Dict = temp_row[::-1] for column_index, column in enumerate(__a ): current_solution -= column * solutions[column_index] solutions.append(__a ) lowerCAmelCase__ : Any = [] for item in solutions: final.append(float(round(__a , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() __UpperCamelCase : List[Any] = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
106
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCAmelCase_ : Any = logging.get_logger(__name__) class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' def __init__( self : Union[str, Any] , *lowercase_ : List[str] , **lowercase_ : List[str]): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_)
91
0
def _a ( SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : list[int] ): # Check if the input is valid if not len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ) == 3: raise ValueError("Please enter a valid equation." ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError("Both a & b of two equations can't be zero." ) # Extract the coefficients __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = equationa __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = equationa # Calculate the determinants of the matrices __lowerCAmelCase = aa * ba - aa * ba __lowerCAmelCase = ca * ba - ca * ba __lowerCAmelCase = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("Infinite solutions. (Consistent system)" ) else: raise ValueError("No solution. (Inconsistent system)" ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: __lowerCAmelCase = determinant_x / determinant __lowerCAmelCase = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
92
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): class a__ : def __init__( self , _A ): """simple docstring""" __lowerCAmelCase = metric_id class a__ : _a : Optional[int] = [MetricMock(snake_case__ ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ): if "tmp_path" in args: __lowerCAmelCase = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(SCREAMING_SNAKE_CASE_ , match="https://huggingface.co/docs/evaluate" ): func(*SCREAMING_SNAKE_CASE_ )
92
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = """▁""" UpperCamelCase__ = {"""vocab_file""": """sentencepiece.bpe.model"""} UpperCamelCase__ = { """vocab_file""": { """facebook/mbart-large-50-one-to-many-mmt""": ( """https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model""" ), } } UpperCamelCase__ = { """facebook/mbart-large-50-one-to-many-mmt""": 1024, } # fmt: off UpperCamelCase__ = ["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN""", """af_ZA""", """az_AZ""", """bn_IN""", """fa_IR""", """he_IL""", """hr_HR""", """id_ID""", """ka_GE""", """km_KH""", """mk_MK""", """ml_IN""", """mn_MN""", """mr_IN""", """pl_PL""", """ps_AF""", """pt_XX""", """sv_SE""", """sw_KE""", """ta_IN""", """te_IN""", """th_TH""", """tl_XX""", """uk_UA""", """ur_PK""", """xh_ZA""", """gl_ES""", """sl_SI"""] class a__ ( snake_case__ ): _a : Tuple = VOCAB_FILES_NAMES _a : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _a : Dict = ["""input_ids""", """attention_mask"""] _a : List[int] = [] _a : List[int] = [] def __init__( self , _A , _A=None , _A=None , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A = None , **_A , ): """simple docstring""" __lowerCAmelCase = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else mask_token __lowerCAmelCase = {} if sp_model_kwargs is None else sp_model_kwargs __lowerCAmelCase = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=_A , tgt_lang=_A , eos_token=_A , unk_token=_A , sep_token=_A , cls_token=_A , pad_token=_A , mask_token=_A , sp_model_kwargs=self.sp_model_kwargs , **_A , ) __lowerCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_A ) ) __lowerCAmelCase = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token __lowerCAmelCase = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab __lowerCAmelCase = 1 __lowerCAmelCase = len(self.sp_model ) __lowerCAmelCase = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(_A ) } __lowerCAmelCase = {v: k for k, v in self.lang_code_to_id.items()} __lowerCAmelCase = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) __lowerCAmelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} __lowerCAmelCase = src_lang if src_lang is not None else "en_XX" __lowerCAmelCase = self.lang_code_to_id[self._src_lang] __lowerCAmelCase = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self._src_lang @src_lang.setter def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self ): """simple docstring""" __lowerCAmelCase = self.__dict__.copy() __lowerCAmelCase = None return state def __setstate__( self , _A ): """simple docstring""" __lowerCAmelCase = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __lowerCAmelCase = {} __lowerCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {self.convert_ids_to_tokens(_A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" return self.sp_model.encode(_A , out_type=_A ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __lowerCAmelCase = self.sp_model.PieceToId(_A ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = [] __lowerCAmelCase = "" __lowerCAmelCase = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_A ) + token __lowerCAmelCase = True __lowerCAmelCase = [] else: current_sub_tokens.append(_A ) __lowerCAmelCase = False out_string += self.sp_model.decode(_A ) return out_string.strip() def __SCREAMING_SNAKE_CASE( self , _A , _A = None ): """simple docstring""" if not os.path.isdir(_A ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCAmelCase = os.path.join( _A , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _A ) elif not os.path.isfile(self.vocab_file ): with open(_A , "wb" ) as fi: __lowerCAmelCase = self.sp_model.serialized_model_proto() fi.write(_A ) return (out_vocab_file,) def __SCREAMING_SNAKE_CASE( self , _A , _A = None , _A = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A ) __lowerCAmelCase = [1] * len(self.prefix_tokens ) __lowerCAmelCase = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(_A )) + suffix_ones return prefix_ones + ([0] * len(_A )) + ([0] * len(_A )) + suffix_ones def __SCREAMING_SNAKE_CASE( self , _A , _A = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , **_A ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) __lowerCAmelCase = src_lang __lowerCAmelCase = self(_A , add_special_tokens=_A , return_tensors=_A , **_A ) __lowerCAmelCase = self.convert_tokens_to_ids(_A ) __lowerCAmelCase = tgt_lang_id return inputs def __SCREAMING_SNAKE_CASE( self , _A , _A = "en_XX" , _A = None , _A = "ro_RO" , **_A , ): """simple docstring""" __lowerCAmelCase = src_lang __lowerCAmelCase = tgt_lang return super().prepare_seqaseq_batch(_A , _A , **_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = self.lang_code_to_id[src_lang] __lowerCAmelCase = [self.cur_lang_code_id] __lowerCAmelCase = [self.eos_token_id] def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = self.lang_code_to_id[tgt_lang] __lowerCAmelCase = [self.cur_lang_code_id] __lowerCAmelCase = [self.eos_token_id]
92
from random import randint from tempfile import TemporaryFile import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = 0 if start < end: __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase , __lowerCAmelCase = _in_place_partition(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , p - 1 ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , p + 1 , SCREAMING_SNAKE_CASE_ ) return count def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = 0 __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase = start - 1 for index in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value __lowerCAmelCase = new_pivot_index + 1 __lowerCAmelCase = a[new_pivot_index] __lowerCAmelCase = a[index] __lowerCAmelCase = temp __lowerCAmelCase = a[new_pivot_index + 1] __lowerCAmelCase = a[end] __lowerCAmelCase = temp return new_pivot_index + 1, count UpperCamelCase__ = TemporaryFile() UpperCamelCase__ = 100 # 1000 elements are to be sorted UpperCamelCase__ , UpperCamelCase__ = 0, 1 # mean and standard deviation UpperCamelCase__ = np.random.normal(mu, sigma, p) np.save(outfile, X) print("""The array is""") print(X) outfile.seek(0) # using the same array UpperCamelCase__ = np.load(outfile) UpperCamelCase__ = len(M) - 1 UpperCamelCase__ = _in_place_quick_sort(M, 0, r) print( """No of Comparisons for 100 elements selected from a standard normal distribution""" """is :""" ) print(z)
92
1
def _a ( SCREAMING_SNAKE_CASE_ : int = 10_00 ): __lowerCAmelCase = 3 __lowerCAmelCase = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f'''{solution() = }''')
92
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available UpperCamelCase__ = { """configuration_audio_spectrogram_transformer""": [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ASTConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ASTForAudioClassification""", """ASTModel""", """ASTPreTrainedModel""", ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ["""ASTFeatureExtractor"""] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
1
from random import randint from tempfile import TemporaryFile import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = 0 if start < end: __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase , __lowerCAmelCase = _in_place_partition(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , p - 1 ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , p + 1 , SCREAMING_SNAKE_CASE_ ) return count def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = 0 __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase = start - 1 for index in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value __lowerCAmelCase = new_pivot_index + 1 __lowerCAmelCase = a[new_pivot_index] __lowerCAmelCase = a[index] __lowerCAmelCase = temp __lowerCAmelCase = a[new_pivot_index + 1] __lowerCAmelCase = a[end] __lowerCAmelCase = temp return new_pivot_index + 1, count UpperCamelCase__ = TemporaryFile() UpperCamelCase__ = 100 # 1000 elements are to be sorted UpperCamelCase__ , UpperCamelCase__ = 0, 1 # mean and standard deviation UpperCamelCase__ = np.random.normal(mu, sigma, p) np.save(outfile, X) print("""The array is""") print(X) outfile.seek(0) # using the same array UpperCamelCase__ = np.load(outfile) UpperCamelCase__ = len(M) - 1 UpperCamelCase__ = _in_place_quick_sort(M, 0, r) print( """No of Comparisons for 100 elements selected from a standard normal distribution""" """is :""" ) print(z)
92
import argparse import os import re import packaging.version UpperCamelCase__ = """examples/""" UpperCamelCase__ = { """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(R"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(R"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), R"""\1version=\"VERSION\","""), """doc""": (re.compile(R"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } UpperCamelCase__ = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } UpperCamelCase__ = """README.md""" def _a ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str] ): with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = re_pattern.sub(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): for folder, directories, fnames in os.walk(SCREAMING_SNAKE_CASE_ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , pattern="examples" ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int]=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not patch: update_version_in_examples(SCREAMING_SNAKE_CASE_ ) def _a ( ): __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(SCREAMING_SNAKE_CASE_ ) def _a ( ): with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(SCREAMING_SNAKE_CASE_ ).groups()[0] return packaging.version.parse(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any]=False ): __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: __lowerCAmelCase = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(F"""Which version are you releasing? [{default_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: __lowerCAmelCase = default_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ , patch=SCREAMING_SNAKE_CASE_ ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _a ( ): __lowerCAmelCase = get_version() __lowerCAmelCase = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: __lowerCAmelCase = dev_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") UpperCamelCase__ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
92
1
def _a ( SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase , __lowerCAmelCase = [], [] while len(SCREAMING_SNAKE_CASE_ ) > 1: __lowerCAmelCase , __lowerCAmelCase = min(SCREAMING_SNAKE_CASE_ ), max(SCREAMING_SNAKE_CASE_ ) start.append(SCREAMING_SNAKE_CASE_ ) end.append(SCREAMING_SNAKE_CASE_ ) collection.remove(SCREAMING_SNAKE_CASE_ ) collection.remove(SCREAMING_SNAKE_CASE_ ) end.reverse() return start + collection + end if __name__ == "__main__": UpperCamelCase__ = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase__ = [int(item) for item in user_input.split(""",""")] print(*merge_sort(unsorted), sep=""",""")
92
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class a__ ( snake_case__ , unittest.TestCase ): _a : Dict = KandinskyImgaImgPipeline _a : List[Any] = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] _a : str = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] _a : List[Any] = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] _a : int = False @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 3_2 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 3_2 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.time_input_dim @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.time_input_dim * 4 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 1_0_0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_0_0_5 , ) __lowerCAmelCase = MultilingualCLIP(_A ) __lowerCAmelCase = text_encoder.eval() return text_encoder @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "text_image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "text_image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } __lowerCAmelCase = UNetaDConditionModel(**_A ) return model @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return { "block_out_channels": [3_2, 6_4], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.dummy_text_encoder __lowerCAmelCase = self.dummy_tokenizer __lowerCAmelCase = self.dummy_unet __lowerCAmelCase = self.dummy_movq __lowerCAmelCase = { "num_train_timesteps": 1_0_0_0, "beta_schedule": "linear", "beta_start": 0.0_00_85, "beta_end": 0.0_12, "clip_sample": False, "set_alpha_to_one": False, "steps_offset": 0, "prediction_type": "epsilon", "thresholding": False, } __lowerCAmelCase = DDIMScheduler(**_A ) __lowerCAmelCase = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" __lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_A ) ).to(_A ) __lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_A ) # create init_image __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_A ) ).to(_A ) __lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowerCAmelCase = Image.fromarray(np.uinta(_A ) ).convert("RGB" ).resize((2_5_6, 2_5_6) ) if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "horse", "image": init_image, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 6_4, "width": 6_4, "num_inference_steps": 1_0, "guidance_scale": 7.0, "strength": 0.2, "output_type": "np", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "cpu" __lowerCAmelCase = self.get_dummy_components() __lowerCAmelCase = self.pipeline_class(**_A ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __lowerCAmelCase = pipe(**self.get_dummy_inputs(_A ) ) __lowerCAmelCase = output.images __lowerCAmelCase = pipe( **self.get_dummy_inputs(_A ) , return_dict=_A , )[0] __lowerCAmelCase = image[0, -3:, -3:, -1] __lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCAmelCase = np.array( [0.61_47_49_43, 0.6_07_35_39, 0.43_30_85_44, 0.5_92_82_69, 0.47_49_35_95, 0.46_75_59_73, 0.4_61_38_38, 0.45_36_87_97, 0.50_11_92_33] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_img2img_frog.npy" ) __lowerCAmelCase = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) __lowerCAmelCase = "A red cartoon frog, 4k" __lowerCAmelCase = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(_A ) __lowerCAmelCase = KandinskyImgaImgPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipeline.to(_A ) pipeline.set_progress_bar_config(disable=_A ) __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase , __lowerCAmelCase = pipe_prior( _A , generator=_A , num_inference_steps=5 , negative_prompt="" , ).to_tuple() __lowerCAmelCase = pipeline( _A , image=_A , image_embeds=_A , negative_image_embeds=_A , generator=_A , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , strength=0.2 , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A )
92
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase__ = { """configuration_lxmert""": ["""LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LxmertConfig"""], """tokenization_lxmert""": ["""LxmertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ["""LxmertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """LxmertEncoder""", """LxmertForPreTraining""", """LxmertForQuestionAnswering""", """LxmertModel""", """LxmertPreTrainedModel""", """LxmertVisualFeatureEncoder""", """LxmertXLayer""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFLxmertForPreTraining""", """TFLxmertMainLayer""", """TFLxmertModel""", """TFLxmertPreTrainedModel""", """TFLxmertVisualFeatureEncoder""", ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
class a__ ( snake_case__ ): pass class a__ ( snake_case__ ): pass class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [ [], [], [], ] def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: if len(self.queues[priority] ) >= 1_0_0: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(_A ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self ): """simple docstring""" return "\n".join(f"""Priority {i}: {q}""" for i, q in enumerate(self.queues ) ) class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [] def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" if len(self.queue ) == 1_0_0: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.queue: raise UnderFlowError("The queue is empty" ) else: __lowerCAmelCase = min(self.queue ) self.queue.remove(_A ) return data def __str__( self ): """simple docstring""" return str(self.queue ) def _a ( ): __lowerCAmelCase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): __lowerCAmelCase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
92
1
from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar UpperCamelCase__ = TypeVar("""T""") class a__ ( Generic[T] ): def __init__( self , _A ): """simple docstring""" __lowerCAmelCase = data __lowerCAmelCase = None def __str__( self ): """simple docstring""" return f"""{self.data}""" class a__ ( Generic[T] ): def __init__( self ): """simple docstring""" __lowerCAmelCase = None def __iter__( self ): """simple docstring""" __lowerCAmelCase = self.top while node: yield node.data __lowerCAmelCase = node.next def __str__( self ): """simple docstring""" return "->".join([str(_A ) for item in self] ) def __len__( self ): """simple docstring""" return len(tuple(iter(self ) ) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.top is None def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = Node(_A ) if not self.is_empty(): __lowerCAmelCase = self.top __lowerCAmelCase = node def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if self.is_empty(): raise IndexError("pop from empty stack" ) assert isinstance(self.top , _A ) __lowerCAmelCase = self.top __lowerCAmelCase = self.top.next return pop_node.data def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if self.is_empty(): raise IndexError("peek from empty stack" ) assert self.top is not None return self.top.data def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = None if __name__ == "__main__": from doctest import testmod testmod()
92
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class a__ : def __init__( self , _A , _A=1_3 , _A=3_0 , _A=2 , _A=3 , _A=True , _A=True , _A=3_2 , _A=5 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1_0 , _A=0.02 , _A=3 , _A=None , _A=2 , ): """simple docstring""" __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = image_size __lowerCAmelCase = patch_size __lowerCAmelCase = num_channels __lowerCAmelCase = is_training __lowerCAmelCase = use_labels __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 = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = scope __lowerCAmelCase = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCAmelCase = (image_size // patch_size) ** 2 __lowerCAmelCase = num_patches + 2 def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = self.get_config() return config, pixel_values, labels def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_A , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTModel(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTForMaskedImageModeling(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForMaskedImageModeling(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = self.type_sequence_label_size __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = config_and_inputs __lowerCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a__ ( snake_case__ , snake_case__ , unittest.TestCase ): _a : Optional[Any] = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) _a : int = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) _a : Optional[Any] = False _a : Tuple = False _a : Tuple = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=3_7 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_A , nn.Linear ) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) __lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase = [*signature.parameters.keys()] __lowerCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=False ): """simple docstring""" __lowerCAmelCase = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.model_tester.is_training: return __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(_A ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return __lowerCAmelCase = False __lowerCAmelCase = True for model_class in self.all_model_classes: if model_class in get_values(_A ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue __lowerCAmelCase = model_class(_A ) model.gradient_checkpointing_enable() model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(_A ), *get_values(_A ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"""Testing {model_class} with {problem_type['title']}""" ): __lowerCAmelCase = problem_type["title"] __lowerCAmelCase = problem_type["num_labels"] __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) if problem_type["num_labels"] > 1: __lowerCAmelCase = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) __lowerCAmelCase = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=_A ) as warning_list: __lowerCAmelCase = model(**_A ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"""Something is going wrong in the regression problem: intercepted {w.message}""" ) loss.backward() @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = DeiTModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def _a ( ): __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class a__ ( unittest.TestCase ): @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to( _A ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ).to(_A ) # forward pass with torch.no_grad(): __lowerCAmelCase = model(**_A ) # verify the logits __lowerCAmelCase = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _A ) __lowerCAmelCase = torch.tensor([-1.02_66, 0.19_12, -1.28_61] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModel.from_pretrained( "facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ) __lowerCAmelCase = inputs.pixel_values.to(_A ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __lowerCAmelCase = model(_A )
92
1
import requests from bsa import BeautifulSoup def _a ( SCREAMING_SNAKE_CASE_ : str = "https://www.worldometers.info/coronavirus" ): __lowerCAmelCase = BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE_ ).text , "html.parser" ) __lowerCAmelCase = soup.findAll("h1" ) __lowerCAmelCase = soup.findAll("div" , {"class": "maincounter-number"} ) keys += soup.findAll("span" , {"class": "panel-title"} ) values += soup.findAll("div" , {"class": "number-table-main"} ) return {key.text.strip(): value.text.strip() for key, value in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )} if __name__ == "__main__": print("""\033[1m""" + """COVID-19 Status of the World""" + """\033[0m\n""") for key, value in world_covidaa_stats().items(): print(f'''{key}\n{value}\n''')
92
def _a ( SCREAMING_SNAKE_CASE_ : int = 1_00_00_00 ): __lowerCAmelCase = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , SCREAMING_SNAKE_CASE_ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
92
1
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = {"""vocab_file""": """sentencepiece.model"""} UpperCamelCase__ = { """vocab_file""": { """google/rembert""": """https://huggingface.co/google/rembert/resolve/main/sentencepiece.model""", }, } UpperCamelCase__ = { """google/rembert""": 256, } class a__ ( snake_case__ ): _a : Optional[int] = VOCAB_FILES_NAMES _a : Dict = PRETRAINED_VOCAB_FILES_MAP _a : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _A , _A=False , _A=True , _A=True , _A="[CLS]" , _A="[SEP]" , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , **_A , ): """simple docstring""" super().__init__( do_lower_case=_A , remove_space=_A , keep_accents=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , **_A , ) __lowerCAmelCase = do_lower_case __lowerCAmelCase = remove_space __lowerCAmelCase = keep_accents __lowerCAmelCase = vocab_file __lowerCAmelCase = spm.SentencePieceProcessor() self.sp_model.Load(_A ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return len(self.sp_model ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {self.convert_ids_to_tokens(_A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" __lowerCAmelCase = self.__dict__.copy() __lowerCAmelCase = None return state def __setstate__( self , _A ): """simple docstring""" __lowerCAmelCase = d __lowerCAmelCase = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def __SCREAMING_SNAKE_CASE( self , _A , _A=False ): """simple docstring""" __lowerCAmelCase = self.sp_model.EncodeAsPieces(_A ) return pieces def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" return self.sp_model.PieceToId(_A ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" return self.sp_model.IdToPiece(_A ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = self.sp_model.decode_pieces(_A ) return out_string def __SCREAMING_SNAKE_CASE( self , _A , _A = None ): """simple docstring""" __lowerCAmelCase = [self.sep_token_id] __lowerCAmelCase = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __SCREAMING_SNAKE_CASE( self , _A , _A = None , _A = False ): """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(_A )) + [1] + ([0] * len(_A )) + [1] return [1] + ([0] * len(_A )) + [1] def __SCREAMING_SNAKE_CASE( self , _A , _A = 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 __SCREAMING_SNAKE_CASE( self , _A , _A = None ): """simple docstring""" if not os.path.isdir(_A ): logger.error("Vocabulary path ({}) should be a directory".format(_A ) ) return __lowerCAmelCase = os.path.join( _A , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ): copyfile(self.vocab_file , _A ) return (out_vocab_file,)
92
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( """The `image_to_image.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionImg2ImgPipeline` instead.""" )
92
1
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib UpperCamelCase__ = get_logger() UpperCamelCase__ = None class a__ ( TensorFormatter[Mapping, """jax.Array""", Mapping] ): def __init__( self , _A=None , _A=None , **_A ): """simple docstring""" super().__init__(features=_A ) import jax from jaxlib.xla_client import Device if isinstance(_A , _A ): raise ValueError( f"""Expected {device} to be a `str` not {type(_A )}, as `jaxlib.xla_extension.Device` """ "is not serializable neither with `pickle` nor with `dill`. Instead you can surround " "the device with `str()` to get its string identifier that will be internally mapped " "to the actual `jaxlib.xla_extension.Device`." ) __lowerCAmelCase = device if isinstance(_A , _A ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: __lowerCAmelCase = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( f"""Device with string identifier {self.device} not listed among the available """ f"""devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default """ f"""device: {str(jax.devices()[0] )}.""" ) __lowerCAmelCase = str(jax.devices()[0] ) __lowerCAmelCase = jnp_array_kwargs @staticmethod def __SCREAMING_SNAKE_CASE( ): """simple docstring""" import jax return {str(_A ): device for device in jax.devices()} def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" import jax import jax.numpy as jnp if isinstance(_A , _A ) and column: if all( isinstance(_A , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(_A , axis=0 ) return column def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" import jax import jax.numpy as jnp if isinstance(_A , (str, bytes, type(_A )) ): return value elif isinstance(_A , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() __lowerCAmelCase = {} if isinstance(_A , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: __lowerCAmelCase = {"dtype": jnp.intaa} else: __lowerCAmelCase = {"dtype": jnp.intaa} elif isinstance(_A , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): __lowerCAmelCase = {"dtype": jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(_A , PIL.Image.Image ): __lowerCAmelCase = np.asarray(_A ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: __lowerCAmelCase = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(_A , **{**default_dtype, **self.jnp_array_kwargs} ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(_A , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(_A , "__array__" ) and not isinstance(_A , jax.Array ): __lowerCAmelCase = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(_A , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(_A ) for substruct in data_struct] ) elif isinstance(_A , (list, tuple) ): return self._consolidate([self.recursive_tensorize(_A ) for substruct in data_struct] ) return self._tensorize(_A ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" return map_nested(self._recursive_tensorize , _A , map_list=_A ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = self.numpy_arrow_extractor().extract_row(_A ) __lowerCAmelCase = self.python_features_decoder.decode_row(_A ) return self.recursive_tensorize(_A ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = self.numpy_arrow_extractor().extract_column(_A ) __lowerCAmelCase = self.python_features_decoder.decode_column(_A , pa_table.column_names[0] ) __lowerCAmelCase = self.recursive_tensorize(_A ) __lowerCAmelCase = self._consolidate(_A ) return column def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = self.numpy_arrow_extractor().extract_batch(_A ) __lowerCAmelCase = self.python_features_decoder.decode_batch(_A ) __lowerCAmelCase = self.recursive_tensorize(_A ) for column_name in batch: __lowerCAmelCase = self._consolidate(batch[column_name] ) return batch
92
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(""">=""", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType UpperCamelCase__ = get_logger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __lowerCAmelCase = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __lowerCAmelCase = F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin""" __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if accelerator.process_index == 0: logger.info(F"""Saving model to {output_model_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __lowerCAmelCase = ( F"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving model to {output_model_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , F"""{MODEL_NAME}_{model_index}""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving model to {ckpt_dir}""" ) __lowerCAmelCase = {"model": state_dict} dist_cp.save_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"""Model saved to {ckpt_dir}""" ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(SCREAMING_SNAKE_CASE_ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( "Set the `sync_module_states` flag to `True` so that model states are synced across processes when " "initializing FSDP object" ) return __lowerCAmelCase = F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin""" __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading model from {input_model_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __lowerCAmelCase = ( F"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading model from {input_model_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __lowerCAmelCase = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"""{MODEL_NAME}_{model_index}""" ) if F"""{MODEL_NAME}""" not in input_dir else input_dir ) logger.info(F"""Loading model from {ckpt_dir}""" ) __lowerCAmelCase = {"model": model.state_dict()} dist_cp.load_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , planner=DefaultLoadPlanner() , ) __lowerCAmelCase = state_dict["model"] logger.info(F"""Model loaded from {ckpt_dir}""" ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __lowerCAmelCase = FSDP.optim_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: __lowerCAmelCase = ( F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving Optimizer state to {output_optimizer_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Optimizer state saved in {output_optimizer_file}""" ) else: __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , F"""{OPTIMIZER_NAME}_{optimizer_index}""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving Optimizer state to {ckpt_dir}""" ) dist_cp.save_state_dict( state_dict={"optimizer": optim_state} , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"""Optimizer state saved in {ckpt_dir}""" ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __lowerCAmelCase = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: __lowerCAmelCase = ( F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading Optimizer state from {input_optimizer_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Optimizer state loaded from {input_optimizer_file}""" ) else: __lowerCAmelCase = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"""{OPTIMIZER_NAME}_{optimizer_index}""" ) if F"""{OPTIMIZER_NAME}""" not in input_dir else input_dir ) logger.info(F"""Loading Optimizer from {ckpt_dir}""" ) __lowerCAmelCase = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key="optimizer" , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , ) __lowerCAmelCase = optim_state["optimizer"] logger.info(F"""Optimizer loaded from {ckpt_dir}""" ) __lowerCAmelCase = FSDP.optim_state_dict_to_load(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) optimizer.load_state_dict(SCREAMING_SNAKE_CASE_ )
92
1
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--user""", type=str, default="""ubuntu""") parser.add_argument("""--host""", type=str, default="""localhost""") parser.add_argument("""--key_path""", type=str, default=None) parser.add_argument("""--instance""", type=str, default="""V100:1""") parser.add_argument("""--provider""", type=str, default="""cheapest""") parser.add_argument("""--use_spot""", type=bool, default=False) parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""") UpperCamelCase__ , UpperCamelCase__ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("""Cannot specify both BYO and on-demand cluster args""") UpperCamelCase__ = rh.cluster( name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path} ) else: UpperCamelCase__ = rh.cluster( name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) UpperCamelCase__ = args.example.rsplit("""/""", 1)[0] # Set up remote environment cluster.install_packages(["""pip:./"""]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f'''pip install -r transformers/examples/{example_dir}/requirements.txt''']) cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f'''python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}''']) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
92
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a__ ( snake_case__ ): def __init__( self , *_A , _A=None , _A=None , **_A ): """simple docstring""" super().__init__(*_A , **_A ) __lowerCAmelCase = eval_examples __lowerCAmelCase = post_process_function def __SCREAMING_SNAKE_CASE( self , _A = None , _A=None , _A = None , _A = "eval" , **_A , ): """simple docstring""" __lowerCAmelCase = gen_kwargs.copy() __lowerCAmelCase = ( gen_kwargs["max_length"] if gen_kwargs.get("max_length" ) is not None else self.args.generation_max_length ) __lowerCAmelCase = ( gen_kwargs["num_beams"] if gen_kwargs.get("num_beams" ) is not None else self.args.generation_num_beams ) __lowerCAmelCase = gen_kwargs __lowerCAmelCase = self.eval_dataset if eval_dataset is None else eval_dataset __lowerCAmelCase = self.get_eval_dataloader(_A ) __lowerCAmelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. __lowerCAmelCase = self.compute_metrics __lowerCAmelCase = None __lowerCAmelCase = time.time() __lowerCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __lowerCAmelCase = eval_loop( _A , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , metric_key_prefix=_A , ) finally: __lowerCAmelCase = compute_metrics __lowerCAmelCase = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _A , _A , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default __lowerCAmelCase = self.post_process_function(_A , _A , _A ) __lowerCAmelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): __lowerCAmelCase = metrics.pop(_A ) metrics.update(output.metrics ) else: __lowerCAmelCase = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_A ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) __lowerCAmelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , _A ) return metrics def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=None , _A = "test" , **_A ): """simple docstring""" __lowerCAmelCase = gen_kwargs.copy() __lowerCAmelCase = self.get_test_dataloader(_A ) # Temporarily disable metric computation, we will do it in the loop here. __lowerCAmelCase = self.compute_metrics __lowerCAmelCase = None __lowerCAmelCase = time.time() __lowerCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __lowerCAmelCase = eval_loop( _A , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , metric_key_prefix=_A , ) finally: __lowerCAmelCase = compute_metrics __lowerCAmelCase = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _A , _A , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output __lowerCAmelCase = self.post_process_function(_A , _A , _A , "predict" ) __lowerCAmelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): __lowerCAmelCase = metrics.pop(_A ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_A )
92
1
import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def _a ( SCREAMING_SNAKE_CASE_ : Any ): def wrapper(*SCREAMING_SNAKE_CASE_ : Optional[Any] , **SCREAMING_SNAKE_CASE_ : str ): __lowerCAmelCase = timeit.default_timer() __lowerCAmelCase = func(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = timeit.default_timer() - starttime return delta __lowerCAmelCase = func.__name__ return wrapper def _a ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : Any=1_00 , SCREAMING_SNAKE_CASE_ : Dict=None ): __lowerCAmelCase = [] __lowerCAmelCase = seq_shapes or {} for i in range(SCREAMING_SNAKE_CASE_ ): __lowerCAmelCase = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(SCREAMING_SNAKE_CASE_ , _ArrayXD ): __lowerCAmelCase = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(SCREAMING_SNAKE_CASE_ , datasets.Value ): if v.dtype == "string": __lowerCAmelCase = "The small grey turtle was surprisingly fast when challenged." else: __lowerCAmelCase = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(SCREAMING_SNAKE_CASE_ , datasets.Sequence ): while isinstance(SCREAMING_SNAKE_CASE_ , datasets.Sequence ): __lowerCAmelCase = v.feature __lowerCAmelCase = seq_shapes[k] __lowerCAmelCase = np.random.rand(*SCREAMING_SNAKE_CASE_ ).astype(v.dtype ) __lowerCAmelCase = data dummy_data.append((i, example) ) return dummy_data def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[Any]=1_00 , SCREAMING_SNAKE_CASE_ : int=None ): __lowerCAmelCase = generate_examples(SCREAMING_SNAKE_CASE_ , num_examples=SCREAMING_SNAKE_CASE_ , seq_shapes=SCREAMING_SNAKE_CASE_ ) with ArrowWriter(features=SCREAMING_SNAKE_CASE_ , path=SCREAMING_SNAKE_CASE_ ) as writer: for key, record in dummy_data: __lowerCAmelCase = features.encode_example(SCREAMING_SNAKE_CASE_ ) writer.write(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase , __lowerCAmelCase = writer.finalize() if not num_final_examples == num_examples: raise ValueError( F"""Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.""" ) __lowerCAmelCase = datasets.Dataset.from_file(filename=SCREAMING_SNAKE_CASE_ , info=datasets.DatasetInfo(features=SCREAMING_SNAKE_CASE_ ) ) return dataset
92
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _a ( SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = filter(lambda SCREAMING_SNAKE_CASE_ : p.requires_grad , model.parameters() ) __lowerCAmelCase = sum([np.prod(p.size() ) for p in model_parameters] ) return params UpperCamelCase__ = logging.getLogger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any ): if metric == "rouge2": __lowerCAmelCase = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": __lowerCAmelCase = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": __lowerCAmelCase = "{val_avg_em:.4f}-{step_count}" else: raise NotImplementedError( F"""seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this""" " function." ) __lowerCAmelCase = ModelCheckpoint( dirpath=SCREAMING_SNAKE_CASE_ , filename=SCREAMING_SNAKE_CASE_ , monitor=F"""val_{metric}""" , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): return EarlyStopping( monitor=F"""val_{metric}""" , mode="min" if "loss" in metric else "max" , patience=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , ) class a__ ( pl.Callback ): def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = {f"""lr_group_{i}""": param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_A ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A=True ): """simple docstring""" logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) __lowerCAmelCase = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results __lowerCAmelCase = Path(pl_module.hparams.output_dir ) if type_path == "test": __lowerCAmelCase = od / "test_results.txt" __lowerCAmelCase = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. __lowerCAmelCase = od / f"""{type_path}_results/{trainer.global_step:05d}.txt""" __lowerCAmelCase = od / f"""{type_path}_generations/{trainer.global_step:05d}.txt""" results_file.parent.mkdir(exist_ok=_A ) generations_file.parent.mkdir(exist_ok=_A ) with open(_A , "a+" ) as writer: for key in sorted(_A ): if key in ["log", "progress_bar", "preds"]: continue __lowerCAmelCase = metrics[key] if isinstance(_A , torch.Tensor ): __lowerCAmelCase = val.item() __lowerCAmelCase = f"""{key}: {val:.6f}\n""" writer.write(_A ) if not save_generations: return if "preds" in metrics: __lowerCAmelCase = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(_A ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: __lowerCAmelCase = pl_module.model.model.num_parameters() except AttributeError: __lowerCAmelCase = pl_module.model.num_parameters() __lowerCAmelCase = count_trainable_parameters(_A ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1E6, "grad_mp": n_trainable_pars / 1E6} ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_A , _A , "test" ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
92
1
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class a__ ( snake_case__ , snake_case__ , unittest.TestCase ): _a : str = IFPipeline _a : List[Any] = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} _a : Any = TEXT_TO_IMAGE_BATCH_PARAMS _a : Dict = PipelineTesterMixin.required_optional_params - {"""latents"""} def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self._get_dummy_components() def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().test_save_load_floataa(expected_max_diff=1E-1 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self._test_save_load_local() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0" , variant="fp16" , torch_dtype=torch.floataa ) __lowerCAmelCase = IFSuperResolutionPipeline.from_pretrained( "DeepFloyd/IF-II-L-v1.0" , variant="fp16" , torch_dtype=torch.floataa , text_encoder=_A , tokenizer=_A ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("cuda" ) __lowerCAmelCase , __lowerCAmelCase = pipe_a.encode_prompt("anime turtle" , device="cuda" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() __lowerCAmelCase = None __lowerCAmelCase = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(_A , _A , _A , _A ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img __lowerCAmelCase = IFImgaImgPipeline(**pipe_a.components ) __lowerCAmelCase = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(_A , _A , _A , _A ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting __lowerCAmelCase = IFInpaintingPipeline(**pipe_a.components ) __lowerCAmelCase = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(_A , _A , _A , _A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A ): """simple docstring""" _start_torch_memory_measurement() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , num_inference_steps=2 , generator=_A , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (6_4, 6_4, 3) __lowerCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 1_3 * 1_0**9 __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy" ) assert_mean_pixel_difference(_A , _A ) # pipeline 2 _start_torch_memory_measurement() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0 ) ).to(_A ) __lowerCAmelCase = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , generator=_A , num_inference_steps=2 , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) __lowerCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy" ) assert_mean_pixel_difference(_A , _A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A ): """simple docstring""" _start_torch_memory_measurement() __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0 ) ).to(_A ) __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , num_inference_steps=2 , generator=_A , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (6_4, 6_4, 3) __lowerCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 1_0 * 1_0**9 __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy" ) assert_mean_pixel_difference(_A , _A ) # pipeline 2 _start_torch_memory_measurement() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = floats_tensor((1, 3, 2_5_6, 2_5_6) , rng=random.Random(0 ) ).to(_A ) __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0 ) ).to(_A ) __lowerCAmelCase = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , original_image=_A , generator=_A , num_inference_steps=2 , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) __lowerCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy" ) assert_mean_pixel_difference(_A , _A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A ): """simple docstring""" _start_torch_memory_measurement() __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0 ) ).to(_A ) __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(1 ) ).to(_A ) __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , mask_image=_A , num_inference_steps=2 , generator=_A , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (6_4, 6_4, 3) __lowerCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 1_0 * 1_0**9 __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy" ) assert_mean_pixel_difference(_A , _A ) # pipeline 2 _start_torch_memory_measurement() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0 ) ).to(_A ) __lowerCAmelCase = floats_tensor((1, 3, 2_5_6, 2_5_6) , rng=random.Random(0 ) ).to(_A ) __lowerCAmelCase = floats_tensor((1, 3, 2_5_6, 2_5_6) , rng=random.Random(1 ) ).to(_A ) __lowerCAmelCase = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , mask_image=_A , original_image=_A , generator=_A , num_inference_steps=2 , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) __lowerCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy" ) assert_mean_pixel_difference(_A , _A ) def _a ( ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
92
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
92
1
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase__ = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
from queue import PriorityQueue from typing import Any import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : set , SCREAMING_SNAKE_CASE_ : set , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : PriorityQueue , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : float | int , ): for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCAmelCase = cst_fwd.get(SCREAMING_SNAKE_CASE_ , np.inf ) __lowerCAmelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCAmelCase = new_cost_f __lowerCAmelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCAmelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : dict ): __lowerCAmelCase = -1 __lowerCAmelCase = set() __lowerCAmelCase = set() __lowerCAmelCase = {source: 0} __lowerCAmelCase = {destination: 0} __lowerCAmelCase = {source: None} __lowerCAmelCase = {destination: None} __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCAmelCase , __lowerCAmelCase = queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase , __lowerCAmelCase = queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = pass_and_relaxation( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) __lowerCAmelCase = pass_and_relaxation( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCAmelCase = shortest_distance return shortest_path_distance UpperCamelCase__ = { """B""": [["""C""", 1]], """C""": [["""D""", 1]], """D""": [["""F""", 1]], """E""": [["""B""", 1], ["""G""", 2]], """F""": [], """G""": [["""F""", 1]], } UpperCamelCase__ = { """B""": [["""E""", 1]], """C""": [["""B""", 1]], """D""": [["""C""", 1]], """F""": [["""D""", 1], ["""G""", 1]], """E""": [[None, np.inf]], """G""": [["""E""", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
92
1
from math import factorial def _a ( SCREAMING_SNAKE_CASE_ : int = 20 ): __lowerCAmelCase = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... __lowerCAmelCase = n // 2 return int(factorial(SCREAMING_SNAKE_CASE_ ) / (factorial(SCREAMING_SNAKE_CASE_ ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCamelCase__ = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
92
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { """edbeeching/decision-transformer-gym-hopper-medium""": ( """https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json""" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class a__ ( snake_case__ ): _a : Optional[int] = """decision_transformer""" _a : Optional[int] = ["""past_key_values"""] _a : Dict = { """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , _A=1_7 , _A=4 , _A=1_2_8 , _A=4_0_9_6 , _A=True , _A=1 , _A=1_0_2_4 , _A=3 , _A=1 , _A=None , _A="relu" , _A=0.1 , _A=0.1 , _A=0.1 , _A=1E-5 , _A=0.02 , _A=True , _A=True , _A=5_0_2_5_6 , _A=5_0_2_5_6 , _A=False , _A=False , **_A , ): """simple docstring""" __lowerCAmelCase = state_dim __lowerCAmelCase = act_dim __lowerCAmelCase = hidden_size __lowerCAmelCase = max_ep_len __lowerCAmelCase = action_tanh __lowerCAmelCase = vocab_size __lowerCAmelCase = n_positions __lowerCAmelCase = n_layer __lowerCAmelCase = n_head __lowerCAmelCase = n_inner __lowerCAmelCase = activation_function __lowerCAmelCase = resid_pdrop __lowerCAmelCase = embd_pdrop __lowerCAmelCase = attn_pdrop __lowerCAmelCase = layer_norm_epsilon __lowerCAmelCase = initializer_range __lowerCAmelCase = scale_attn_weights __lowerCAmelCase = use_cache __lowerCAmelCase = scale_attn_by_inverse_layer_idx __lowerCAmelCase = reorder_and_upcast_attn __lowerCAmelCase = bos_token_id __lowerCAmelCase = eos_token_id super().__init__(bos_token_id=_A , eos_token_id=_A , **_A )
92
1
from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class a__ : def __init__( self , _A , ): """simple docstring""" __lowerCAmelCase = parent __lowerCAmelCase = 1_3 __lowerCAmelCase = 7 __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = 9_9 __lowerCAmelCase = 3_2 __lowerCAmelCase = 2 __lowerCAmelCase = 4 __lowerCAmelCase = 3_7 __lowerCAmelCase = "gelu" __lowerCAmelCase = 0.1 __lowerCAmelCase = 0.1 __lowerCAmelCase = 5_1_2 __lowerCAmelCase = 1_6 __lowerCAmelCase = 2 __lowerCAmelCase = 0.02 __lowerCAmelCase = 3 __lowerCAmelCase = 4 __lowerCAmelCase = None def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase = None if self.use_input_mask: __lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase = None __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 = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = self.prepare_config_and_inputs() __lowerCAmelCase = True __lowerCAmelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = TFEsmModel(config=_A ) __lowerCAmelCase = {"input_ids": input_ids, "attention_mask": input_mask} __lowerCAmelCase = model(_A ) __lowerCAmelCase = [input_ids, input_mask] __lowerCAmelCase = model(_A ) __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A , _A , _A , _A , ): """simple docstring""" __lowerCAmelCase = True __lowerCAmelCase = TFEsmModel(config=_A ) __lowerCAmelCase = { "input_ids": input_ids, "attention_mask": input_mask, "encoder_hidden_states": encoder_hidden_states, "encoder_attention_mask": encoder_attention_mask, } __lowerCAmelCase = model(_A ) __lowerCAmelCase = [input_ids, input_mask] __lowerCAmelCase = model(_A , encoder_hidden_states=_A ) # Also check the case where encoder outputs are not passed __lowerCAmelCase = model(_A , attention_mask=_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = TFEsmForMaskedLM(config=_A ) __lowerCAmelCase = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = self.num_labels __lowerCAmelCase = TFEsmForTokenClassification(config=_A ) __lowerCAmelCase = {"input_ids": input_ids, "attention_mask": input_mask} __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = config_and_inputs __lowerCAmelCase = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class a__ ( snake_case__ , snake_case__ , unittest.TestCase ): _a : Any = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) _a : List[Any] = ( { """feature-extraction""": TFEsmModel, """fill-mask""": TFEsmForMaskedLM, """text-classification""": TFEsmForSequenceClassification, """token-classification""": TFEsmForTokenClassification, """zero-shot""": TFEsmForSequenceClassification, } if is_tf_available() else {} ) _a : Union[str, Any] = False _a : List[Any] = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFEsmModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=_A , hidden_size=3_7 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = TFEsmModel.from_pretrained(_A ) self.assertIsNotNone(_A ) @unittest.skip("Protein models do not support embedding resizing." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass @unittest.skip("Protein models do not support embedding resizing." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer __lowerCAmelCase = model.get_bias() assert isinstance(_A , _A ) for k, v in name.items(): assert isinstance(_A , tf.Variable ) else: __lowerCAmelCase = model.get_output_embeddings() assert x is None __lowerCAmelCase = model.get_bias() assert name is None @require_tf class a__ ( unittest.TestCase ): @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D" ) __lowerCAmelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) __lowerCAmelCase = model(_A )[0] __lowerCAmelCase = [1, 6, 3_3] self.assertEqual(list(output.numpy().shape ) , _A ) # compare the actual values for a slice. __lowerCAmelCase = tf.constant( [ [ [8.92_15_18, -10.58_98_14, -6.4_67_13_07], [-6.3_96_71_56, -13.91_13_77, -1.1_21_19_15], [-7.78_12_47, -13.95_15_57, -3.74_05_92], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D" ) __lowerCAmelCase = tf.constant([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) __lowerCAmelCase = model(_A )[0] # compare the actual values for a slice. __lowerCAmelCase = tf.constant( [ [ [0.14_44_30_92, 0.54_12_53_27, 0.3_24_77_39], [0.30_34_04_84, 0.00_52_66_76, 0.31_07_77_22], [0.32_27_80_43, -0.24_98_70_96, 0.3_41_46_28], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
92
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__ ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): _a : str = StableUnCLIPPipeline _a : Union[str, Any] = TEXT_TO_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_BATCH_PARAMS _a : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _a : Optional[Any] = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 3_2 __lowerCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=_A , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=1_2 , embedding_dim=_A , num_layers=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = DDPMScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1_0_0_0 , clip_sample=_A , clip_sample_range=5.0 , beta_schedule="squaredcos_cap_v2" , ) # regular denoising components torch.manual_seed(0 ) __lowerCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=_A ) __lowerCAmelCase = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = UNetaDConditionModel( sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(3_2, 6_4) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_A , layers_per_block=1 , upcast_attention=_A , use_linear_projection=_A , ) torch.manual_seed(0 ) __lowerCAmelCase = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type="v_prediction" , set_alpha_to_one=_A , steps_offset=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = AutoencoderKL() __lowerCAmelCase = { # prior components "prior_tokenizer": prior_tokenizer, "prior_text_encoder": prior_text_encoder, "prior": prior, "prior_scheduler": prior_scheduler, # image noising components "image_normalizer": image_normalizer, "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder, "unet": unet, "scheduler": scheduler, "vae": vae, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "prior_num_inference_steps": 2, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device == "cpu" self._test_attention_slicing_forward_pass(test_max_difference=_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=_A ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" ) __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = pipe("anime turle" , generator=_A , output_type="np" ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = pipe( "anime turtle" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="np" , ) __lowerCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 1_0**9
92
1
UpperCamelCase__ = frozenset( [ """prompt""", """height""", """width""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", """cross_attention_kwargs""", ] ) UpperCamelCase__ = frozenset(["""prompt""", """negative_prompt"""]) UpperCamelCase__ = frozenset([]) UpperCamelCase__ = frozenset(["""image"""]) UpperCamelCase__ = frozenset( [ """image""", """height""", """width""", """guidance_scale""", ] ) UpperCamelCase__ = frozenset(["""image"""]) UpperCamelCase__ = frozenset( [ """prompt""", """image""", """height""", """width""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", ] ) UpperCamelCase__ = frozenset(["""prompt""", """image""", """negative_prompt"""]) UpperCamelCase__ = frozenset( [ # Text guided image variation with an image mask """prompt""", """image""", """mask_image""", """height""", """width""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", ] ) UpperCamelCase__ = frozenset(["""prompt""", """image""", """mask_image""", """negative_prompt"""]) UpperCamelCase__ = frozenset( [ # image variation with an image mask """image""", """mask_image""", """height""", """width""", """guidance_scale""", ] ) UpperCamelCase__ = frozenset(["""image""", """mask_image"""]) UpperCamelCase__ = frozenset( [ """example_image""", """image""", """mask_image""", """height""", """width""", """guidance_scale""", ] ) UpperCamelCase__ = frozenset(["""example_image""", """image""", """mask_image"""]) UpperCamelCase__ = frozenset(["""class_labels"""]) UpperCamelCase__ = frozenset(["""class_labels"""]) UpperCamelCase__ = frozenset(["""batch_size"""]) UpperCamelCase__ = frozenset([]) UpperCamelCase__ = frozenset(["""batch_size"""]) UpperCamelCase__ = frozenset([]) UpperCamelCase__ = frozenset( [ """prompt""", """audio_length_in_s""", """guidance_scale""", """negative_prompt""", """prompt_embeds""", """negative_prompt_embeds""", """cross_attention_kwargs""", ] ) UpperCamelCase__ = frozenset(["""prompt""", """negative_prompt"""]) UpperCamelCase__ = frozenset(["""input_tokens"""]) UpperCamelCase__ = frozenset(["""input_tokens"""])
92
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase__ = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
1
import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( "files" , [ ["full:README.md", "dataset_infos.json"], ["empty:README.md", "dataset_infos.json"], ["dataset_infos.json"], ["full:README.md"], ] , ) def _a ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = tmp_path_factory.mktemp("dset_infos_dir" ) if "full:README.md" in files: with open(dataset_infos_dir / "README.md" , "w" ) as f: f.write("---\ndataset_info:\n dataset_size: 42\n---" ) if "empty:README.md" in files: with open(dataset_infos_dir / "README.md" , "w" ) as f: f.write("" ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / "dataset_infos.json" , "w" ) as f: f.write("{\"default\": {\"dataset_size\": 42}}" ) __lowerCAmelCase = DatasetInfosDict.from_directory(SCREAMING_SNAKE_CASE_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( "dataset_info" , [ DatasetInfo(), DatasetInfo( description="foo" , features=Features({"a": Value("int32" )} ) , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train"}] , download_size=42 , ), ] , ) def _a ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : DatasetInfo ): __lowerCAmelCase = str(SCREAMING_SNAKE_CASE_ ) dataset_info.write_to_directory(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = DatasetInfo.from_directory(SCREAMING_SNAKE_CASE_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , "dataset_info.json" ) ) def _a ( ): __lowerCAmelCase = DatasetInfo( description="foo" , citation="bar" , homepage="https://foo.bar" , license="CC0" , features=Features({"a": Value("int32" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train", "num_examples": 42}] , download_checksums={} , download_size=13_37 , post_processing_size=4_42 , dataset_size=12_34 , size_in_bytes=13_37 + 4_42 + 12_34 , ) __lowerCAmelCase = dataset_info._to_yaml_dict() assert sorted(SCREAMING_SNAKE_CASE_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __lowerCAmelCase = yaml.safe_dump(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = yaml.safe_load(SCREAMING_SNAKE_CASE_ ) assert dataset_info_yaml_dict == reloaded def _a ( ): __lowerCAmelCase = DatasetInfo() __lowerCAmelCase = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( "dataset_infos_dict" , [ DatasetInfosDict(), DatasetInfosDict({"default": DatasetInfo()} ), DatasetInfosDict({"my_config_name": DatasetInfo()} ), DatasetInfosDict( { "default": DatasetInfo( description="foo" , features=Features({"a": Value("int32" )} ) , builder_name="builder" , config_name="config" , version="1.0.0" , splits=[{"name": "train"}] , download_size=42 , ) } ), DatasetInfosDict( { "v1": DatasetInfo(dataset_size=42 ), "v2": DatasetInfo(dataset_size=13_37 ), } ), ] , ) def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : DatasetInfosDict ): __lowerCAmelCase = str(SCREAMING_SNAKE_CASE_ ) dataset_infos_dict.write_to_directory(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = DatasetInfosDict.from_directory(SCREAMING_SNAKE_CASE_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __lowerCAmelCase = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __lowerCAmelCase = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , "README.md" ) )
92
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase__ = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : Optional[Any] = DebertaVaTokenizer _a : Optional[Any] = DebertaVaTokenizerFast _a : List[str] = True _a : Optional[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = DebertaVaTokenizer(_A , unk_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = "this is a test" __lowerCAmelCase = "this is a test" return input_text, output_text def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<pad>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "[PAD]" ) self.assertEqual(len(_A ) , 3_0_0_0_1 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁hello", "!", "how", "▁are", "▁you", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "This is a test" __lowerCAmelCase = [1_3, 1, 4_3_9_8, 2_5, 2_1, 1_2_8_9] __lowerCAmelCase = ["▁", "T", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = DebertaVaTokenizer(_A , keep_accents=_A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , keep_accents=_A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) # fmt: off __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = [1_3, 1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] __lowerCAmelCase = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ] __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DebertaVaTokenizer(_A ) __lowerCAmelCase = tokenizer.encode("sequence builders" ) __lowerCAmelCase = tokenizer.encode("multi-sequence build" ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_A ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_A , _A ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , _A ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , _A , ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[1, 3_9_8_6_7, 3_6, 1_9_3_9_0, 4_8_6, 2_7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 6_0_6_8_5, 1_2_2_5, 7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 9_3_6_7, 1_6_8_9_9, 1_8, 1_5_9_3_7, 5_3, 5_9_4, 7_7_3, 1_8, 1_6_2_8_7, 3_0_4_6_5, 3_6, 1_5_9_3_7, 6, 4_1_1_3_9, 3_8, 3_6_9_7_9, 6_0_7_6_3, 1_9_1, 6, 3_4_1_3_2, 9_9, 6, 5_0_5_3_8, 3_9_0, 4_3_2_3_0, 6, 3_4_1_3_2, 2_7_7_9, 2_0_8_5_0, 1_4, 6_9_9, 1_0_7_2, 1_1_9_4, 3_6, 3_8_2, 1_0_9_0_1, 5_3, 7, 6_9_9, 1_0_7_2, 2_0_8_4, 3_6, 2_0_4_2_2, 6_3_0, 5_3, 1_9, 1_0_5, 3_0_4_9, 1_8_9_6, 1_0_5_3, 1_6_8_9_9, 1_5_0_6, 1_1, 3_7_9_7_8, 4_2_4_3, 7, 1_2_3_7, 3_1_8_6_9, 2_0_0, 1_6_5_6_6, 6_5_4, 6, 3_5_0_5_2, 8_1_4_3_6, 7, 5_5_6_3_0, 1_3_5_9_3, 4, 2], [1, 2_6, 1_5_0_1_1, 1_3, 6_6_7, 8, 1_0_5_3, 1_8, 2_3_6_1_1, 1_2_3_7, 7_2_3_5_6, 1_2_8_2_0, 3_4, 1_0_4_1_3_4, 1_2_0_9, 3_5, 1_3_3_1_3, 6_6_2_7, 2_1, 2_0_2, 3_4_7, 7, 1_6_4, 2_3_9_9, 1_1, 4_6, 4_4_8_5, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1_2_3_2, 2_8_6_4, 1_5_7_8_5, 1_4_9_5_1, 1_0_5, 5, 8_5_8_1, 1_2_5_0, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name="microsoft/deberta-v2-xlarge" , revision="ad6e42c1532ddf3a15c39246b63f5559d558b670" , )
92
1
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class a__ ( snake_case__ ): def __init__( self , _A , _A , _A , _A , ): """simple docstring""" super().__init__() __lowerCAmelCase = value_function __lowerCAmelCase = unet __lowerCAmelCase = scheduler __lowerCAmelCase = env __lowerCAmelCase = env.get_dataset() __lowerCAmelCase = {} for key in self.data.keys(): try: __lowerCAmelCase = self.data[key].mean() except: # noqa: E722 pass __lowerCAmelCase = {} for key in self.data.keys(): try: __lowerCAmelCase = self.data[key].std() except: # noqa: E722 pass __lowerCAmelCase = env.observation_space.shape[0] __lowerCAmelCase = env.action_space.shape[0] def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" return (x_in - self.means[key]) / self.stds[key] def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" return x_in * self.stds[key] + self.means[key] def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" if type(_A ) is dict: return {k: self.to_torch(_A ) for k, v in x_in.items()} elif torch.is_tensor(_A ): return x_in.to(self.unet.device ) return torch.tensor(_A , device=self.unet.device ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" for key, val in cond.items(): __lowerCAmelCase = val.clone() return x_in def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = x.shape[0] __lowerCAmelCase = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model __lowerCAmelCase = torch.full((batch_size,) , _A , device=self.unet.device , dtype=torch.long ) for _ in range(_A ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models __lowerCAmelCase = self.value_function(x.permute(0 , 2 , 1 ) , _A ).sample __lowerCAmelCase = torch.autograd.grad([y.sum()] , [x] )[0] __lowerCAmelCase = self.scheduler._get_variance(_A ) __lowerCAmelCase = torch.exp(0.5 * posterior_variance ) __lowerCAmelCase = model_std * grad __lowerCAmelCase = 0 __lowerCAmelCase = x.detach() __lowerCAmelCase = x + scale * grad __lowerCAmelCase = self.reset_xa(_A , _A , self.action_dim ) __lowerCAmelCase = self.unet(x.permute(0 , 2 , 1 ) , _A ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg __lowerCAmelCase = self.scheduler.step(_A , _A , _A , predict_epsilon=_A )["prev_sample"] # apply conditions to the trajectory (set the initial state) __lowerCAmelCase = self.reset_xa(_A , _A , self.action_dim ) __lowerCAmelCase = self.to_torch(_A ) return x, y def __call__( self , _A , _A=6_4 , _A=3_2 , _A=2 , _A=0.1 ): """simple docstring""" __lowerCAmelCase = self.normalize(_A , "observations" ) __lowerCAmelCase = obs[None].repeat(_A , axis=0 ) __lowerCAmelCase = {0: self.to_torch(_A )} __lowerCAmelCase = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) __lowerCAmelCase = randn_tensor(_A , device=self.unet.device ) __lowerCAmelCase = self.reset_xa(_A , _A , self.action_dim ) __lowerCAmelCase = self.to_torch(_A ) # run the diffusion process __lowerCAmelCase , __lowerCAmelCase = self.run_diffusion(_A , _A , _A , _A ) # sort output trajectories by value __lowerCAmelCase = y.argsort(0 , descending=_A ).squeeze() __lowerCAmelCase = x[sorted_idx] __lowerCAmelCase = sorted_values[:, :, : self.action_dim] __lowerCAmelCase = actions.detach().cpu().numpy() __lowerCAmelCase = self.de_normalize(_A , key="actions" ) # select the action with the highest value if y is not None: __lowerCAmelCase = 0 else: # if we didn't run value guiding, select a random action __lowerCAmelCase = np.random.randint(0 , _A ) __lowerCAmelCase = denorm_actions[selected_index, 0] return denorm_actions
92
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf UpperCamelCase__ = logging.get_logger(__name__) @dataclass class a__ ( snake_case__ ): _a : List[str] = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **_A ): """simple docstring""" for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __lowerCAmelCase = deprecated_arg[3:] __lowerCAmelCase = not kwargs.pop(_A ) logger.warning( f"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or""" f""" {positive_arg}={kwargs[positive_arg]}""" ) __lowerCAmelCase = kwargs.pop("tpu_name" , self.tpu_name ) __lowerCAmelCase = kwargs.pop("device_idx" , self.device_idx ) __lowerCAmelCase = kwargs.pop("eager_mode" , self.eager_mode ) __lowerCAmelCase = kwargs.pop("use_xla" , self.use_xla ) super().__init__(**_A ) _a : str = field( default=snake_case__ , metadata={"""help""": """Name of TPU"""} , ) _a : int = field( default=0 , metadata={"""help""": """CPU / GPU device index. Defaults to 0."""} , ) _a : bool = field(default=snake_case__ , metadata={"""help""": """Benchmark models in eager model."""} ) _a : bool = field( default=snake_case__ , metadata={ """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.""" } , ) @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) __lowerCAmelCase = None if self.tpu: try: if self.tpu_name: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __lowerCAmelCase = None return tpu @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) __lowerCAmelCase = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , "GPU" ) __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/gpu:{self.device_idx}""" ) else: tf.config.set_visible_devices([] , "GPU" ) # disable GPU __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/cpu:{self.device_idx}""" ) return strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_tpu is not None @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return tf.config.list_physical_devices("GPU" ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.cuda: return len(self.gpu_list ) return 0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.n_gpu > 0
92
1
# Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union UpperCamelCase__ = re.compile(R"""^(?P<major>\d+)""" R"""\.(?P<minor>\d+)""" R"""\.(?P<patch>\d+)$""") @total_ordering @dataclass class a__ : _a : str _a : Optional[str] = None _a : Optional[Union[str, int]] = None _a : Optional[Union[str, int]] = None _a : Optional[Union[str, int]] = None def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = _str_to_version_tuple(self.version_str ) def __repr__( self ): """simple docstring""" return f"""{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}""" @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.major, self.minor, self.patch def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" if isinstance(_A , _A ): return Version(_A ) elif isinstance(_A , _A ): return other raise TypeError(f"""{other} (type {type(_A )}) cannot be compared to version.""" ) def __eq__( self , _A ): """simple docstring""" try: __lowerCAmelCase = self._validate_operand(_A ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self , _A ): """simple docstring""" __lowerCAmelCase = self._validate_operand(_A ) return self.tuple < other.tuple def __hash__( self ): """simple docstring""" return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def __SCREAMING_SNAKE_CASE( cls , _A ): """simple docstring""" __lowerCAmelCase = {f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.version_str def _a ( SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = _VERSION_REG.match(SCREAMING_SNAKE_CASE_ ) if not res: raise ValueError(F"""Invalid version '{version_str}'. Format should be x.y.z with {{x,y,z}} being digits.""" ) return tuple(int(SCREAMING_SNAKE_CASE_ ) for v in [res.group("major" ), res.group("minor" ), res.group("patch" )] ) def _a ( SCREAMING_SNAKE_CASE_ : str ): return ".".join(str(SCREAMING_SNAKE_CASE_ ) for v in version_tuple )
92
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece.model""") UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") UpperCamelCase__ = """pt""" if is_torch_available() else """tf""" @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : int = CamembertTokenizer _a : Dict = CamembertTokenizerFast _a : Tuple = True _a : List[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>NOTUSED" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "<mask>" ) self.assertEqual(len(_A ) , 1_0_0_4 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_5 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) __lowerCAmelCase = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.test_rust_tokenizer: return __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.tokenize(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[5, 5_4, 7_1_9_6, 2_9_7, 3_0, 2_3, 7_7_6, 1_8, 1_1, 3_2_1_5, 3_7_0_5, 8_2_5_2, 2_2, 3_1_6_4, 1_1_8_1, 2_1_1_6, 2_9, 1_6, 8_1_3, 2_5, 7_9_1, 3_3_1_4, 2_0, 3_4_4_6, 3_8, 2_7_5_7_5, 1_2_0, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_6_8, 1_7, 1_1, 9_0_8_8, 2_0, 1_5_1_7, 8, 2_2_8_0_4, 1_8_8_1_8, 1_0, 3_8, 6_2_9, 6_0_7, 6_0_7, 1_4_2, 1_9, 7_1_9_6, 8_6_7, 5_6, 1_0_3_2_6, 2_4, 2_2_6_7, 2_0, 4_1_6, 5_0_7_2, 1_5_6_1_2, 2_3_3, 7_3_4, 7, 2_3_9_9, 2_7, 1_6, 3_0_1_5, 1_6_4_9, 7, 2_4, 2_0, 4_3_3_8, 2_3_9_9, 2_7, 1_3, 3_4_0_0, 1_4, 1_3, 6_1_8_9, 8, 9_3_0, 9, 6]], "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, 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, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. __lowerCAmelCase = [ "Le transformeur est un modèle d'apprentissage profond introduit en 2017, " "utilisé principalement dans le domaine du traitement automatique des langues (TAL).", "À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus " "pour gérer des données séquentielles, telles que le langage naturel, pour des tâches " "telles que la traduction et la synthèse de texte.", ] self.tokenizer_integration_test_util( expected_encoding=_A , model_name="camembert-base" , revision="3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf" , sequences=_A , )
92
1