code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () UpperCAmelCase__ = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). UpperCAmelCase__ = [0, 25, 50] UpperCAmelCase__ = [25, 50, 75] UpperCAmelCase__ = fuzz.membership.trimf(X, abca) UpperCAmelCase__ = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. UpperCAmelCase__ = np.ones(75) UpperCAmelCase__ = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) UpperCAmelCase__ = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) UpperCAmelCase__ = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) UpperCAmelCase__ = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) UpperCAmelCase__ = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] UpperCAmelCase__ = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) UpperCAmelCase__ = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] UpperCAmelCase__ = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] UpperCAmelCase__ = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('''Young''') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('''Middle aged''') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('''union''') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('''intersection''') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('''complement_a''') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('''difference a/b''') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('''alg_sum''') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('''alg_product''') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('''bdd_sum''') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('''bdd_difference''') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
5
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) # TODO Update this UpperCAmelCase__ = { '''facebook/esm-1b''': '''https://huggingface.co/facebook/esm-1b/resolve/main/config.json''', # See all ESM models at https://huggingface.co/models?filter=esm } class lowerCamelCase__ ( lowerCAmelCase): SCREAMING_SNAKE_CASE__ = '''esm''' def __init__(self , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=7_6_8 , UpperCAmelCase=1_2 , UpperCAmelCase=1_2 , UpperCAmelCase=3_0_7_2 , UpperCAmelCase=0.1 , UpperCAmelCase=0.1 , UpperCAmelCase=1_0_2_6 , UpperCAmelCase=0.02 , UpperCAmelCase=1e-12 , UpperCAmelCase="absolute" , UpperCAmelCase=True , UpperCAmelCase=None , UpperCAmelCase=False , UpperCAmelCase=False , UpperCAmelCase=None , UpperCAmelCase=None , **UpperCAmelCase , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase , mask_token_id=UpperCAmelCase , **UpperCAmelCase ) _lowercase =vocab_size _lowercase =hidden_size _lowercase =num_hidden_layers _lowercase =num_attention_heads _lowercase =intermediate_size _lowercase =hidden_dropout_prob _lowercase =attention_probs_dropout_prob _lowercase =max_position_embeddings _lowercase =initializer_range _lowercase =layer_norm_eps _lowercase =position_embedding_type _lowercase =use_cache _lowercase =emb_layer_norm_before _lowercase =token_dropout _lowercase =is_folding_model if is_folding_model: if esmfold_config is None: logger.info('''No esmfold_config supplied for folding model, using default values.''' ) _lowercase =EsmFoldConfig() elif isinstance(UpperCAmelCase , UpperCAmelCase ): _lowercase =EsmFoldConfig(**UpperCAmelCase ) _lowercase =esmfold_config if vocab_list is None: logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!''' ) _lowercase =get_default_vocab_list() else: _lowercase =vocab_list else: _lowercase =None _lowercase =None if self.esmfold_config is not None and getattr(self.esmfold_config , '''use_esm_attn_map''' , UpperCAmelCase ): raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!''' ) def __A (self ) -> List[str]: _lowercase =super().to_dict() if isinstance(self.esmfold_config , UpperCAmelCase ): _lowercase =self.esmfold_config.to_dict() return output @dataclass class lowerCamelCase__ : SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = 128 SCREAMING_SNAKE_CASE__ = None def __A (self ) -> Union[str, Any]: if self.trunk is None: _lowercase =TrunkConfig() elif isinstance(self.trunk , UpperCAmelCase ): _lowercase =TrunkConfig(**self.trunk ) def __A (self ) -> Tuple: _lowercase =asdict(self ) _lowercase =self.trunk.to_dict() return output @dataclass class lowerCamelCase__ : SCREAMING_SNAKE_CASE__ = 48 SCREAMING_SNAKE_CASE__ = 1024 SCREAMING_SNAKE_CASE__ = 128 SCREAMING_SNAKE_CASE__ = 32 SCREAMING_SNAKE_CASE__ = 32 SCREAMING_SNAKE_CASE__ = 32 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = 128 SCREAMING_SNAKE_CASE__ = None def __A (self ) -> List[str]: if self.structure_module is None: _lowercase =StructureModuleConfig() elif isinstance(self.structure_module , UpperCAmelCase ): _lowercase =StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(f"`max_recycles` should be positive, got {self.max_recycles}." ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got''' f" {self.sequence_state_dim} and {self.sequence_state_dim}." ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got''' f" {self.pairwise_state_dim} and {self.pairwise_state_dim}." ) _lowercase =self.sequence_state_dim // self.sequence_head_width _lowercase =self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got''' f" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}." ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got''' f" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}." ) if self.pairwise_state_dim % 2 != 0: raise ValueError(f"`pairwise_state_dim` should be even, got {self.pairwise_state_dim}." ) if self.dropout >= 0.4: raise ValueError(f"`dropout` should not be greater than 0.4, got {self.dropout}." ) def __A (self ) -> Dict: _lowercase =asdict(self ) _lowercase =self.structure_module.to_dict() return output @dataclass class lowerCamelCase__ : SCREAMING_SNAKE_CASE__ = 384 SCREAMING_SNAKE_CASE__ = 128 SCREAMING_SNAKE_CASE__ = 16 SCREAMING_SNAKE_CASE__ = 128 SCREAMING_SNAKE_CASE__ = 12 SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = 8 SCREAMING_SNAKE_CASE__ = 0.1 SCREAMING_SNAKE_CASE__ = 8 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 2 SCREAMING_SNAKE_CASE__ = 7 SCREAMING_SNAKE_CASE__ = 10 SCREAMING_SNAKE_CASE__ = 1E-8 SCREAMING_SNAKE_CASE__ = 1E5 def __A (self ) -> List[Any]: return asdict(self ) def UpperCAmelCase_ ( ) -> Tuple: """simple docstring""" return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
5
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: __snake_case :Optional[int] = None __snake_case :Dict = logging.get_logger(__name__) __snake_case :Union[str, Any] = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} __snake_case :str = { '''vocab_file''': { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/spiece.model''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/spiece.model''', }, '''tokenizer_file''': { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json''', }, } __snake_case :str = { '''google/fnet-base''': 512, '''google/fnet-large''': 512, } __snake_case :Union[str, Any] = '''▁''' class _A ( __UpperCAmelCase ): UpperCamelCase__ : List[str] = VOCAB_FILES_NAMES UpperCamelCase__ : Tuple = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ : Tuple = ['''input_ids''', '''token_type_ids'''] UpperCamelCase__ : List[str] = FNetTokenizer def __init__( self : Any , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : List[str]=None , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : List[Any]=True , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Optional[Any]="<unk>" , __SCREAMING_SNAKE_CASE : int="[SEP]" , __SCREAMING_SNAKE_CASE : List[Any]="<pad>" , __SCREAMING_SNAKE_CASE : Optional[Any]="[CLS]" , __SCREAMING_SNAKE_CASE : str="[MASK]" , **__SCREAMING_SNAKE_CASE : Any , ): '''simple docstring''' __a = ( AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE , normalized=__SCREAMING_SNAKE_CASE) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) else mask_token ) super().__init__( __SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , do_lower_case=__SCREAMING_SNAKE_CASE , remove_space=__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __a = do_lower_case __a = remove_space __a = keep_accents __a = vocab_file __a = False if not self.vocab_file else True def _lowerCamelCase ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : List[int] , __SCREAMING_SNAKE_CASE : Optional[List[int]] = None): '''simple docstring''' __a = [self.sep_token_id] __a = [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 _lowerCamelCase ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : List[int] , __SCREAMING_SNAKE_CASE : Optional[List[int]] = None): '''simple docstring''' __a = [self.sep_token_id] __a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def _lowerCamelCase ( self : str , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None): '''simple docstring''' if not os.path.isdir(__SCREAMING_SNAKE_CASE): logger.error(F'Vocabulary path ({save_directory}) should be a directory') return __a = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']) if os.path.abspath(self.vocab_file) != os.path.abspath(__SCREAMING_SNAKE_CASE): copyfile(self.vocab_file , __SCREAMING_SNAKE_CASE) return (out_vocab_file,)
131
def __snake_case ( _UpperCAmelCase , _UpperCAmelCase ): return base * power(_UpperCAmelCase , (exponent - 1) ) if exponent else 1 if __name__ == "__main__": print('''Raise base to the power of exponent using recursion...''') __snake_case :List[Any] = int(input('''Enter the base: ''').strip()) __snake_case :Dict = int(input('''Enter the exponent: ''').strip()) __snake_case :int = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents __snake_case :Optional[Any] = 1 / result print(f'{base} to the power of {exponent} is {result}')
131
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class __magic_name__ ( __a ): '''simple docstring''' lowerCamelCase__ : str = '''table-transformer''' lowerCamelCase__ : str = ['''past_key_values'''] lowerCamelCase__ : Tuple = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self, lowercase_=True, lowercase_=None, lowercase_=3, lowercase_=100, lowercase_=6, lowercase_=2048, lowercase_=8, lowercase_=6, lowercase_=2048, lowercase_=8, lowercase_=0.0, lowercase_=0.0, lowercase_=True, lowercase_="relu", lowercase_=256, lowercase_=0.1, lowercase_=0.0, lowercase_=0.0, lowercase_=0.02, lowercase_=1.0, lowercase_=False, lowercase_="sine", lowercase_="resnet50", lowercase_=True, lowercase_=False, lowercase_=1, lowercase_=5, lowercase_=2, lowercase_=1, lowercase_=1, lowercase_=5, lowercase_=2, lowercase_=0.1, **lowercase_, ) -> Any: """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a__ =CONFIG_MAPPING["""resnet"""](out_features=['''stage4'''] ) elif isinstance(__a, __a ): a__ =backbone_config.get('''model_type''' ) a__ =CONFIG_MAPPING[backbone_model_type] a__ =config_class.from_dict(__a ) # set timm attributes to None a__ =None, None, None a__ =use_timm_backbone a__ =backbone_config a__ =num_channels a__ =num_queries a__ =d_model a__ =encoder_ffn_dim a__ =encoder_layers a__ =encoder_attention_heads a__ =decoder_ffn_dim a__ =decoder_layers a__ =decoder_attention_heads a__ =dropout a__ =attention_dropout a__ =activation_dropout a__ =activation_function a__ =init_std a__ =init_xavier_std a__ =encoder_layerdrop a__ =decoder_layerdrop a__ =encoder_layers a__ =auxiliary_loss a__ =position_embedding_type a__ =backbone a__ =use_pretrained_backbone a__ =dilation # Hungarian matcher a__ =class_cost a__ =bbox_cost a__ =giou_cost # Loss coefficients a__ =mask_loss_coefficient a__ =dice_loss_coefficient a__ =bbox_loss_coefficient a__ =giou_loss_coefficient a__ =eos_coefficient super().__init__(is_encoder_decoder=__a, **__a ) @property def _UpperCAmelCase ( self ) -> int: """simple docstring""" return self.encoder_attention_heads @property def _UpperCAmelCase ( self ) -> int: """simple docstring""" return self.d_model class __magic_name__ ( __a ): '''simple docstring''' lowerCamelCase__ : int = version.parse('1.11' ) @property def _UpperCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def _UpperCAmelCase ( self ) -> float: """simple docstring""" return 1E-5 @property def _UpperCAmelCase ( self ) -> int: """simple docstring""" return 12
188
lowerCamelCase : Optional[Any] = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def snake_case_ ( ): __lowercase : List[str] = input("""Enter message: """ ) __lowercase : int = input("""Enter key [alphanumeric]: """ ) __lowercase : Optional[Any] = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): __lowercase : Optional[int] = """encrypt""" __lowercase : Dict = encrypt_message(lowerCAmelCase_ , lowerCAmelCase_ ) elif mode.lower().startswith("""d""" ): __lowercase : Union[str, Any] = """decrypt""" __lowercase : Optional[int] = decrypt_message(lowerCAmelCase_ , lowerCAmelCase_ ) print(F"\n{mode.title()}ed message:" ) print(lowerCAmelCase_ ) def snake_case_ ( lowerCAmelCase_ : str , lowerCAmelCase_ : str ): return translate_message(lowerCAmelCase_ , lowerCAmelCase_ , """encrypt""" ) def snake_case_ ( lowerCAmelCase_ : str , lowerCAmelCase_ : str ): return translate_message(lowerCAmelCase_ , lowerCAmelCase_ , """decrypt""" ) def snake_case_ ( lowerCAmelCase_ : str , lowerCAmelCase_ : str , lowerCAmelCase_ : str ): __lowercase : Union[str, Any] = [] __lowercase : Tuple = 0 __lowercase : Dict = key.upper() for symbol in message: __lowercase : Optional[Any] = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(lowerCAmelCase_ ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(lowerCAmelCase_ ): __lowercase : str = 0 else: translated.append(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) if __name__ == "__main__": main()
233
0
'''simple docstring''' lowerCamelCase = 8.3_1_4_4_6_2 # Unit - J mol-1 K-1 def _A ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" if moles < 0 or kelvin < 0 or volume < 0: raise ValueError('Invalid inputs. Enter positive value.' ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def _A ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError('Invalid inputs. Enter positive value.' ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
48
'''simple docstring''' import json import os import unittest from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class _UpperCamelCase ( A , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = XLMTokenizer lowerCAmelCase__ = False def __lowerCamelCase ( self : Union[str, Any]): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __lowercase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] __lowercase =dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase)))) __lowercase =['l o 123', 'lo w 1456', 'e r</w> 1789', ''] __lowercase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file']) __lowercase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file']) with open(self.vocab_file , 'w') as fp: fp.write(json.dumps(_lowerCAmelCase)) with open(self.merges_file , 'w') as fp: fp.write('\n'.join(_lowerCAmelCase)) def __lowerCamelCase ( self : List[str] , _lowerCAmelCase : Any): '''simple docstring''' __lowercase ='lower newer' __lowercase ='lower newer' return input_text, output_text def __lowerCamelCase ( self : str): '''simple docstring''' __lowercase =XLMTokenizer(self.vocab_file , self.merges_file) __lowercase ='lower' __lowercase =['low', 'er</w>'] __lowercase =tokenizer.tokenize(_lowerCAmelCase) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase) __lowercase =tokens + ['<unk>'] __lowercase =[1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase) , _lowerCAmelCase) @slow def __lowerCamelCase ( self : str): '''simple docstring''' __lowercase =XLMTokenizer.from_pretrained('xlm-mlm-en-2048') __lowercase =tokenizer.encode('sequence builders' , add_special_tokens=_lowerCAmelCase) __lowercase =tokenizer.encode('multi-sequence build' , add_special_tokens=_lowerCAmelCase) __lowercase =tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase) __lowercase =tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase , _lowerCAmelCase) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
48
1
"""simple docstring""" import numpy as np def snake_case_ ( A_ : np.ndarray, A_ : float ): '''simple docstring''' return np.where(vector > 0, A_, (alpha * (np.exp(A_ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
72
"""simple docstring""" import argparse import os 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_task_guides.py __UpperCAmelCase = 'src/transformers' __UpperCAmelCase = 'docs/source/en/tasks' def _snake_case ( lowercase__ : str , lowercase__ : List[str] , lowercase__ : Any ) -> str: '''simple docstring''' with open(lowercase__ , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: lowerCAmelCase_ :List[Any] = f.readlines() # Find the start prompt. lowerCAmelCase_ :Tuple = 0 while not lines[start_index].startswith(lowercase__ ): start_index += 1 start_index += 1 lowerCAmelCase_ :Dict = start_index while not lines[end_index].startswith(lowercase__ ): 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 # This is to make sure the transformers module imported is the one in the repo. __UpperCAmelCase = direct_transformers_import(TRANSFORMERS_PATH) __UpperCAmelCase = { 'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, 'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, 'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, 'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, 'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, 'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, 'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, 'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, 'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, 'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, 'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, 'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, 'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, 'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). __UpperCAmelCase = { 'summarization.md': ('nllb',), 'translation.md': ('nllb',), } def _snake_case ( lowercase__ : List[str] ) -> str: '''simple docstring''' lowerCAmelCase_ :Optional[Any] = TASK_GUIDE_TO_MODELS[task_guide] lowerCAmelCase_ :List[Any] = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(lowercase__ , set() ) lowerCAmelCase_ :Union[str, Any] = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([f"""[{name}](../model_doc/{code})""" for code, name in model_names.items()] ) + "\n" def _snake_case ( lowercase__ : int , lowercase__ : str=False ) -> Dict: '''simple docstring''' lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ :List[Any] = _find_text_in_file( filename=os.path.join(lowercase__ , lowercase__ ) , start_prompt="""<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->""" , end_prompt="""<!--End of the generated tip-->""" , ) lowerCAmelCase_ :int = get_model_list_for_task(lowercase__ ) if current_list != new_list: if overwrite: with open(os.path.join(lowercase__ , lowercase__ ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( f"""The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`""" """ to fix this.""" ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __UpperCAmelCase = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
84
0
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class lowercase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = 'ylacombe/bark-small' UpperCAmelCase__ = tempfile.mkdtemp() UpperCAmelCase__ = 'en_speaker_1' UpperCAmelCase__ = 'This is a test string' UpperCAmelCase__ = 'speaker_embeddings_path.json' UpperCAmelCase__ = 'speaker_embeddings' def UpperCamelCase__ (self , **__a ) -> List[Any]: """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **__a ) def UpperCamelCase__ (self ) -> Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = BarkProcessor(tokenizer=__a ) processor.save_pretrained(self.tmpdirname ) UpperCAmelCase__ = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def UpperCamelCase__ (self ) -> int: """simple docstring""" UpperCAmelCase__ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) UpperCAmelCase__ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) UpperCAmelCase__ = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='(BOS)' , eos_token='(EOS)' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def UpperCamelCase__ (self ) -> int: """simple docstring""" UpperCAmelCase__ = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) UpperCAmelCase__ = 35 UpperCAmelCase__ = 2 UpperCAmelCase__ = 8 UpperCAmelCase__ = { 'semantic_prompt': np.ones(__a ), 'coarse_prompt': np.ones((nb_codebooks_coarse, seq_len) ), 'fine_prompt': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset UpperCAmelCase__ = processor(text=self.input_string , voice_preset=__a ) UpperCAmelCase__ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__a , np.array([] ) ).tolist() ) # test loading voice preset from npz file UpperCAmelCase__ = os.path.join(self.tmpdirname , 'file.npz' ) np.savez(__a , **__a ) UpperCAmelCase__ = processor(text=self.input_string , voice_preset=__a ) UpperCAmelCase__ = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__a , np.array([] ) ).tolist() ) # test loading voice preset from the hub UpperCAmelCase__ = processor(text=self.input_string , voice_preset=self.voice_preset ) def UpperCamelCase__ (self ) -> List[str]: """simple docstring""" UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = BarkProcessor(tokenizer=__a ) UpperCAmelCase__ = processor(text=self.input_string ) UpperCAmelCase__ = tokenizer( self.input_string , padding='max_length' , max_length=256 , add_special_tokens=__a , return_attention_mask=__a , return_token_type_ids=__a , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
335
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class lowercase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self , __a ) -> List[Any]: """simple docstring""" for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] , model_result['ss'] ): UpperCAmelCase__ = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(__a ) def UpperCamelCase__ (self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = 'sshleifer/tiny-gpt2' UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__a , inference=__a , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=__a , multi_process=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a ) UpperCAmelCase__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" UpperCAmelCase__ = 'sgugger/tiny-distilbert-classification' UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__a , inference=__a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__a , only_pretrain_model=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a ) UpperCAmelCase__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__ (self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = 'sshleifer/tiny-gpt2' UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__a , inference=__a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a ) UpperCAmelCase__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__ (self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = 'sshleifer/tiny-gpt2' UpperCAmelCase__ = AutoConfig.from_pretrained(__a ) UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__a , inference=__a , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=__a , multi_process=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a , [config] ) UpperCAmelCase__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__ (self ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = 'sshleifer/tiny-gpt2' UpperCAmelCase__ = AutoConfig.from_pretrained(__a ) UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__a , inference=__a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a , [config] ) UpperCAmelCase__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__ (self ) -> Dict: """simple docstring""" UpperCAmelCase__ = 'sshleifer/tiny-gpt2' UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__a , inference=__a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a ) UpperCAmelCase__ = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCamelCase__ (self ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = 'sshleifer/tiny-gpt2' UpperCAmelCase__ = AutoConfig.from_pretrained(__a ) UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__a , inference=__a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a , [config] ) UpperCAmelCase__ = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" UpperCAmelCase__ = 'patrickvonplaten/t5-tiny-random' UpperCAmelCase__ = AutoConfig.from_pretrained(__a ) UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__a , inference=__a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a , configs=[config] ) UpperCAmelCase__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices('GPU' ) ) == 0 , 'Cannot do xla on CPU.' ) def UpperCamelCase__ (self ) -> List[str]: """simple docstring""" UpperCAmelCase__ = 'sshleifer/tiny-gpt2' UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__a , inference=__a , sequence_lengths=[8] , batch_sizes=[1] , use_xla=__a , multi_process=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a ) UpperCAmelCase__ = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCamelCase__ (self ) -> Tuple: """simple docstring""" UpperCAmelCase__ = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=__a , save_to_csv=__a , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(__a , 'inf_time.csv' ) , inference_memory_csv_file=os.path.join(__a , 'inf_mem.csv' ) , env_info_csv_file=os.path.join(__a , 'env.csv' ) , multi_process=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a ) benchmark.run() self.assertTrue(Path(os.path.join(__a , 'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__a , 'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(__a , 'env.csv' ) ).exists() ) def UpperCamelCase__ (self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(__a ): self.assertTrue(hasattr(__a , 'sequential' ) ) self.assertTrue(hasattr(__a , 'cumulative' ) ) self.assertTrue(hasattr(__a , 'current' ) ) self.assertTrue(hasattr(__a , 'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase__ = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=__a , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(__a , 'log.txt' ) , log_print=__a , trace_memory_line_by_line=__a , eager_mode=__a , multi_process=__a , ) UpperCAmelCase__ = TensorFlowBenchmark(__a ) UpperCAmelCase__ = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(__a , 'log.txt' ) ).exists() )
335
1
'''simple docstring''' class _a : '''simple docstring''' def __init__( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = '''''' SCREAMING_SNAKE_CASE : Dict = '''''' SCREAMING_SNAKE_CASE : Union[str, Any] = [] def UpperCamelCase_ ( self, A, A ): '''simple docstring''' if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: SCREAMING_SNAKE_CASE : int = self.__min_dist_top_down_dp(m - 1, n - 1 ) else: SCREAMING_SNAKE_CASE : int = self.__min_dist_top_down_dp(__lowercase, n - 1 ) SCREAMING_SNAKE_CASE : Dict = self.__min_dist_top_down_dp(m - 1, __lowercase ) SCREAMING_SNAKE_CASE : int = self.__min_dist_top_down_dp(m - 1, n - 1 ) SCREAMING_SNAKE_CASE : List[Any] = 1 + min(__lowercase, __lowercase, __lowercase ) return self.dp[m][n] def UpperCamelCase_ ( self, A, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = worda SCREAMING_SNAKE_CASE : Optional[int] = worda SCREAMING_SNAKE_CASE : Any = [[-1 for _ in range(len(__lowercase ) )] for _ in range(len(__lowercase ) )] return self.__min_dist_top_down_dp(len(__lowercase ) - 1, len(__lowercase ) - 1 ) def UpperCamelCase_ ( self, A, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = worda SCREAMING_SNAKE_CASE : Tuple = worda SCREAMING_SNAKE_CASE : str = len(__lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = len(__lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty SCREAMING_SNAKE_CASE : Dict = j elif j == 0: # second string is empty SCREAMING_SNAKE_CASE : Union[str, Any] = i elif worda[i - 1] == worda[j - 1]: # last characters are equal SCREAMING_SNAKE_CASE : List[str] = self.dp[i - 1][j - 1] else: SCREAMING_SNAKE_CASE : str = self.dp[i][j - 1] SCREAMING_SNAKE_CASE : List[str] = self.dp[i - 1][j] SCREAMING_SNAKE_CASE : Union[str, Any] = self.dp[i - 1][j - 1] SCREAMING_SNAKE_CASE : str = 1 + min(__lowercase, __lowercase, __lowercase ) return self.dp[m][n] if __name__ == "__main__": UpperCamelCase_ = EditDistance() print("****************** Testing Edit Distance DP Algorithm ******************") print() UpperCamelCase_ = input("Enter the first string: ").strip() UpperCamelCase_ = input("Enter the second string: ").strip() print() print(F"""The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}""") print(F"""The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}""") print() print("*************** End of Testing Edit Distance DP Algorithm ***************")
251
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging __lowercase = logging.get_logger(__name__) def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :Tuple = R'''\w+[.]\d+''' __UpperCamelCase :List[str] = re.findall(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for pat in pats: __UpperCamelCase :int = key.replace(SCREAMING_SNAKE_CASE , '''_'''.join(pat.split('''.''' ) ) ) return key def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :Tuple = pt_tuple_key[:-1] + ('''scale''',) if ( any('''norm''' in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): __UpperCamelCase :str = pt_tuple_key[:-1] + ('''scale''',) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: __UpperCamelCase :Any = pt_tuple_key[:-1] + ('''scale''',) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: __UpperCamelCase :str = pt_tuple_key[:-1] + ('''embedding''',) return renamed_pt_tuple_key, pt_tensor # conv layer __UpperCamelCase :List[str] = pt_tuple_key[:-1] + ('''kernel''',) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: __UpperCamelCase :List[Any] = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer __UpperCamelCase :List[str] = pt_tuple_key[:-1] + ('''kernel''',) if pt_tuple_key[-1] == "weight": __UpperCamelCase :Any = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight __UpperCamelCase :int = pt_tuple_key[:-1] + ('''weight''',) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias __UpperCamelCase :int = pt_tuple_key[:-1] + ('''bias''',) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=42 ): '''simple docstring''' __UpperCamelCase :Union[str, Any] = {k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params __UpperCamelCase :str = flax_model.init_weights(PRNGKey(SCREAMING_SNAKE_CASE ) ) __UpperCamelCase :int = flatten_dict(SCREAMING_SNAKE_CASE ) __UpperCamelCase :List[Any] = {} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): __UpperCamelCase :List[Any] = rename_key(SCREAMING_SNAKE_CASE ) __UpperCamelCase :List[Any] = tuple(renamed_pt_key.split('''.''' ) ) # Correctly rename weight parameters __UpperCamelCase , __UpperCamelCase :Any = rename_key_and_reshape_tensor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """ f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.""" ) # also add unexpected weight so that warning is thrown __UpperCamelCase :str = jnp.asarray(SCREAMING_SNAKE_CASE ) return unflatten_dict(SCREAMING_SNAKE_CASE )
43
0
'''simple docstring''' __A : Optional[Any] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] __A : List[str] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] __A : List[Any] = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def UpperCamelCase_ ( A__ : int , A__ : int , A__ : int ): '''simple docstring''' assert len(str(A__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: lowerCAmelCase_ : Optional[int] = year // 1_00 lowerCAmelCase_ : Dict = (5 * (century % 4) + 2) % 7 lowerCAmelCase_ : Optional[Any] = year % 1_00 lowerCAmelCase_ : Dict = centurian % 12 lowerCAmelCase_ : Optional[Any] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 lowerCAmelCase_ : Any = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) lowerCAmelCase_ : Tuple = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
89
'''simple docstring''' import requests def UpperCamelCase_ ( A__ : str , A__ : str ): '''simple docstring''' lowerCAmelCase_ : Optional[Any] = {"""Content-Type""": """application/json"""} lowerCAmelCase_ : Union[str, Any] = requests.post(A__ , json={"""text""": message_body} , headers=A__ ) if response.status_code != 2_00: lowerCAmelCase_ : Dict = ( """Request to slack returned an error """ f'{response.status_code}, the response is:\n{response.text}' ) raise ValueError(A__ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
89
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowercase : Optional[Any] = logging.get_logger(__name__) __lowercase : Any = { '''xlm-mlm-en-2048''': '''https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json''', '''xlm-mlm-ende-1024''': '''https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json''', '''xlm-mlm-enfr-1024''': '''https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json''', '''xlm-mlm-enro-1024''': '''https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json''', '''xlm-mlm-tlm-xnli15-1024''': '''https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json''', '''xlm-mlm-xnli15-1024''': '''https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json''', '''xlm-clm-enfr-1024''': '''https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json''', '''xlm-clm-ende-1024''': '''https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json''', '''xlm-mlm-17-1280''': '''https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json''', '''xlm-mlm-100-1280''': '''https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json''', } class __lowercase ( _lowercase ): lowerCamelCase : List[str] = "xlm" lowerCamelCase : Optional[Any] = { "hidden_size": "emb_dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", "n_words": "vocab_size", # For backward compatibility } def __init__(self , A=3_0_1_4_5 , A=2_0_4_8 , A=1_2 , A=1_6 , A=0.1 , A=0.1 , A=True , A=False , A=False , A=False , A=1 , A=True , A=5_1_2 , A=2_0_4_8**-0.5 , A=1E-12 , A=0.02 , A=0 , A=1 , A=2 , A=3 , A=5 , A=True , A="first" , A=True , A=None , A=True , A=0.1 , A=5 , A=5 , A=0 , A=0 , A=2 , A=0 , **A , ): lowerCamelCase_ : List[str] = vocab_size lowerCamelCase_ : Optional[int] = emb_dim lowerCamelCase_ : Optional[Any] = n_layers lowerCamelCase_ : Any = n_heads lowerCamelCase_ : Union[str, Any] = dropout lowerCamelCase_ : str = attention_dropout lowerCamelCase_ : str = gelu_activation lowerCamelCase_ : int = sinusoidal_embeddings lowerCamelCase_ : Optional[Any] = causal lowerCamelCase_ : Optional[Any] = asm lowerCamelCase_ : Any = n_langs lowerCamelCase_ : Union[str, Any] = use_lang_emb lowerCamelCase_ : Any = layer_norm_eps lowerCamelCase_ : str = bos_index lowerCamelCase_ : int = eos_index lowerCamelCase_ : Tuple = pad_index lowerCamelCase_ : Union[str, Any] = unk_index lowerCamelCase_ : Optional[int] = mask_index lowerCamelCase_ : Dict = is_encoder lowerCamelCase_ : int = max_position_embeddings lowerCamelCase_ : List[Any] = embed_init_std lowerCamelCase_ : List[str] = init_std lowerCamelCase_ : Dict = summary_type lowerCamelCase_ : Optional[Any] = summary_use_proj lowerCamelCase_ : int = summary_activation lowerCamelCase_ : Dict = summary_proj_to_labels lowerCamelCase_ : Union[str, Any] = summary_first_dropout lowerCamelCase_ : Optional[Any] = start_n_top lowerCamelCase_ : List[Any] = end_n_top lowerCamelCase_ : List[Any] = mask_token_id lowerCamelCase_ : Union[str, Any] = lang_id if "n_words" in kwargs: lowerCamelCase_ : str = kwargs['''n_words'''] super().__init__(pad_token_id=A , bos_token_id=A , **A ) class __lowercase ( _lowercase ): @property def UpperCAmelCase__ (self ): if self.task == "multiple-choice": lowerCamelCase_ : Any = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowerCamelCase_ : List[str] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
318
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) 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 enable_full_determinism() class __lowercase ( unittest.TestCase ): def UpperCAmelCase__ (self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCAmelCase__ (self ): lowerCamelCase_ : Tuple = 1 lowerCamelCase_ : str = 3 lowerCamelCase_ : Dict = (3_2, 3_2) lowerCamelCase_ : Optional[Any] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(A ) return image @property def UpperCAmelCase__ (self ): torch.manual_seed(0 ) lowerCamelCase_ : Optional[Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=3_2 , ) return model @property def UpperCAmelCase__ (self ): torch.manual_seed(0 ) lowerCamelCase_ : Union[str, Any] = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) return model @property def UpperCAmelCase__ (self ): torch.manual_seed(0 ) lowerCamelCase_ : Any = RobertaSeriesConfig( hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_0_0_6 , ) return RobertaSeriesModelWithTransformation(A ) @property def UpperCAmelCase__ (self ): def extract(*A , **A ): class __lowercase : def __init__(self ): lowerCamelCase_ : Any = torch.ones([0] ) def UpperCAmelCase__ (self , A ): self.pixel_values.to(A ) return self return Out() return extract def UpperCAmelCase__ (self ): lowerCamelCase_ : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ : List[Any] = self.dummy_cond_unet lowerCamelCase_ : Any = PNDMScheduler(skip_prk_steps=A ) lowerCamelCase_ : Union[str, Any] = self.dummy_vae lowerCamelCase_ : List[Any] = self.dummy_text_encoder lowerCamelCase_ : Optional[Any] = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) lowerCamelCase_ : Dict = 7_7 lowerCamelCase_ : Union[str, Any] = self.dummy_image.to(A ) lowerCamelCase_ : Union[str, Any] = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk lowerCamelCase_ : Dict = AltDiffusionImgaImgPipeline( unet=A , scheduler=A , vae=A , text_encoder=A , tokenizer=A , safety_checker=A , feature_extractor=self.dummy_extractor , ) lowerCamelCase_ : Tuple = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=A ) lowerCamelCase_ : int = alt_pipe.to(A ) alt_pipe.set_progress_bar_config(disable=A ) lowerCamelCase_ : Optional[Any] = '''A painting of a squirrel eating a burger''' lowerCamelCase_ : Optional[Any] = torch.Generator(device=A ).manual_seed(0 ) lowerCamelCase_ : Optional[Any] = alt_pipe( [prompt] , generator=A , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=A , ) lowerCamelCase_ : int = output.images lowerCamelCase_ : Union[str, Any] = torch.Generator(device=A ).manual_seed(0 ) lowerCamelCase_ : Union[str, Any] = alt_pipe( [prompt] , generator=A , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=A , return_dict=A , )[0] lowerCamelCase_ : List[str] = image[0, -3:, -3:, -1] lowerCamelCase_ : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCamelCase_ : str = np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5E-3 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def UpperCAmelCase__ (self ): lowerCamelCase_ : Dict = self.dummy_cond_unet lowerCamelCase_ : Optional[Any] = PNDMScheduler(skip_prk_steps=A ) lowerCamelCase_ : List[Any] = self.dummy_vae lowerCamelCase_ : Dict = self.dummy_text_encoder lowerCamelCase_ : Any = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) lowerCamelCase_ : Optional[Any] = 7_7 lowerCamelCase_ : str = self.dummy_image.to(A ) # put models in fp16 lowerCamelCase_ : Optional[int] = unet.half() lowerCamelCase_ : Dict = vae.half() lowerCamelCase_ : Union[str, Any] = bert.half() # make sure here that pndm scheduler skips prk lowerCamelCase_ : Dict = AltDiffusionImgaImgPipeline( unet=A , scheduler=A , vae=A , text_encoder=A , tokenizer=A , safety_checker=A , feature_extractor=self.dummy_extractor , ) lowerCamelCase_ : List[Any] = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=A ) lowerCamelCase_ : Any = alt_pipe.to(A ) alt_pipe.set_progress_bar_config(disable=A ) lowerCamelCase_ : Tuple = '''A painting of a squirrel eating a burger''' lowerCamelCase_ : str = torch.manual_seed(0 ) lowerCamelCase_ : Optional[int] = alt_pipe( [prompt] , generator=A , num_inference_steps=2 , output_type='''np''' , image=A , ).images assert image.shape == (1, 3_2, 3_2, 3) @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def UpperCAmelCase__ (self ): lowerCamelCase_ : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) # resize to resolution that is divisible by 8 but not 16 or 32 lowerCamelCase_ : List[str] = init_image.resize((7_6_0, 5_0_4) ) lowerCamelCase_ : List[Any] = '''BAAI/AltDiffusion''' lowerCamelCase_ : List[Any] = AltDiffusionImgaImgPipeline.from_pretrained( A , safety_checker=A , ) pipe.to(A ) pipe.set_progress_bar_config(disable=A ) pipe.enable_attention_slicing() lowerCamelCase_ : Dict = '''A fantasy landscape, trending on artstation''' lowerCamelCase_ : Any = torch.manual_seed(0 ) lowerCamelCase_ : Optional[Any] = pipe( prompt=A , image=A , strength=0.75 , guidance_scale=7.5 , generator=A , output_type='''np''' , ) lowerCamelCase_ : Dict = output.images[0] lowerCamelCase_ : str = image[2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert image.shape == (5_0_4, 7_6_0, 3) lowerCamelCase_ : Union[str, Any] = np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class __lowercase ( unittest.TestCase ): def UpperCAmelCase__ (self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ (self ): lowerCamelCase_ : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) lowerCamelCase_ : List[str] = init_image.resize((7_6_8, 5_1_2) ) lowerCamelCase_ : str = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy''' ) lowerCamelCase_ : int = '''BAAI/AltDiffusion''' lowerCamelCase_ : List[Any] = AltDiffusionImgaImgPipeline.from_pretrained( A , safety_checker=A , ) pipe.to(A ) pipe.set_progress_bar_config(disable=A ) pipe.enable_attention_slicing() lowerCamelCase_ : Tuple = '''A fantasy landscape, trending on artstation''' lowerCamelCase_ : List[Any] = torch.manual_seed(0 ) lowerCamelCase_ : Dict = pipe( prompt=A , image=A , strength=0.75 , guidance_scale=7.5 , generator=A , output_type='''np''' , ) lowerCamelCase_ : List[str] = output.images[0] assert image.shape == (5_1_2, 7_6_8, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1E-2
318
1
import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = '''▁''' UpperCamelCase = {'''vocab_file''': '''vocab.txt''', '''sentencepiece_model_ckpt''': '''sentencepiece.bpe.model'''} UpperCamelCase = { '''sentencepiece_model_file''': '''sentencepiece.bpe.model''', '''vocab_file''': '''vocab.txt''', } UpperCamelCase = { '''vocab_file''': { '''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''', '''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''', }, '''sentencepiece_model_file''': { '''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''', '''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''', }, } UpperCamelCase = { '''ernie-m-base''': 514, '''ernie-m-large''': 514, } UpperCamelCase = { '''ernie-m-base''': {'''do_lower_case''': False}, '''ernie-m-large''': {'''do_lower_case''': False}, } class __UpperCAmelCase (_UpperCAmelCase ): __snake_case : List[str] = ["input_ids"] __snake_case : Tuple = VOCAB_FILES_NAMES __snake_case : int = PRETRAINED_INIT_CONFIGURATION __snake_case : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case : List[str] = PRETRAINED_VOCAB_FILES_MAP __snake_case : List[Any] = RESOURCE_FILES_NAMES def __init__( self: List[Any] , UpperCAmelCase_: Optional[Any] , UpperCAmelCase_: Optional[int]=None , UpperCAmelCase_: Union[str, Any]=False , UpperCAmelCase_: Any="utf8" , UpperCAmelCase_: str="[UNK]" , UpperCAmelCase_: Any="[SEP]" , UpperCAmelCase_: Optional[int]="[PAD]" , UpperCAmelCase_: List[str]="[CLS]" , UpperCAmelCase_: int="[MASK]" , UpperCAmelCase_: Optional[Dict[str, Any]] = None , **UpperCAmelCase_: Union[str, Any] , ): '''simple docstring''' _SCREAMING_SNAKE_CASE = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , vocab_file=UpperCAmelCase_ , encoding=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) _SCREAMING_SNAKE_CASE = do_lower_case _SCREAMING_SNAKE_CASE = sentencepiece_model_ckpt _SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: _SCREAMING_SNAKE_CASE = self.load_vocab(filepath=UpperCAmelCase_ ) else: _SCREAMING_SNAKE_CASE = {self.sp_model.id_to_piece(UpperCAmelCase_ ): id for id in range(self.sp_model.get_piece_size() )} _SCREAMING_SNAKE_CASE = {v: k for k, v in self.vocab.items()} def UpperCamelCase ( self: str , UpperCAmelCase_: Any ): '''simple docstring''' if text is None: return None _SCREAMING_SNAKE_CASE = self.tokenize(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = """""", [] for i, ch in enumerate(UpperCAmelCase_ ): if ch in self.SP_CHAR_MAPPING: _SCREAMING_SNAKE_CASE = self.SP_CHAR_MAPPING.get(UpperCAmelCase_ ) else: _SCREAMING_SNAKE_CASE = unicodedata.normalize("""NFKC""" , UpperCAmelCase_ ) if self.is_whitespace(UpperCAmelCase_ ): continue normalized_text += ch char_mapping.extend([i] * len(UpperCAmelCase_ ) ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = normalized_text, [], 0 if self.do_lower_case: _SCREAMING_SNAKE_CASE = text.lower() for token in split_tokens: if token[:1] == "▁": _SCREAMING_SNAKE_CASE = token[1:] _SCREAMING_SNAKE_CASE = text[offset:].index(UpperCAmelCase_ ) + offset _SCREAMING_SNAKE_CASE = start + len(UpperCAmelCase_ ) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) ) _SCREAMING_SNAKE_CASE = end return token_mapping @property def UpperCamelCase ( self: List[str] ): '''simple docstring''' return len(self.vocab ) def UpperCamelCase ( self: Any ): '''simple docstring''' return dict(self.vocab , **self.added_tokens_encoder ) def __getstate__( self: Union[str, Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.__dict__.copy() _SCREAMING_SNAKE_CASE = None return state def __setstate__( self: Any , UpperCAmelCase_: List[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.sentencepiece_model_ckpt ) def UpperCamelCase ( self: int , UpperCAmelCase_: List[str] ): '''simple docstring''' return "".join((self.SP_CHAR_MAPPING.get(UpperCAmelCase_ , UpperCAmelCase_ ) for c in text) ) def UpperCamelCase ( self: Optional[Any] , UpperCAmelCase_: Union[str, Any] , UpperCAmelCase_: Union[str, Any]=False , UpperCAmelCase_: Any=64 , UpperCAmelCase_: List[Any]=0.1 ): '''simple docstring''' if self.sp_model_kwargs.get("""enable_sampling""" ) is True: _SCREAMING_SNAKE_CASE = True if self.sp_model_kwargs.get("""alpha""" ) is not None: _SCREAMING_SNAKE_CASE = self.sp_model_kwargs.get("""alpha""" ) if self.sp_model_kwargs.get("""nbest_size""" ) is not None: _SCREAMING_SNAKE_CASE = self.sp_model_kwargs.get("""nbest_size""" ) if not enable_sampling: _SCREAMING_SNAKE_CASE = self.sp_model.EncodeAsPieces(UpperCAmelCase_ ) else: _SCREAMING_SNAKE_CASE = self.sp_model.SampleEncodeAsPieces(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = [] for pi, piece in enumerate(UpperCAmelCase_ ): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(UpperCAmelCase_ ) and pi != 0: new_pieces.append(UpperCAmelCase_ ) continue else: continue _SCREAMING_SNAKE_CASE = 0 for i, chunk in enumerate(UpperCAmelCase_ ): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(UpperCAmelCase_ ) or self.is_punct(UpperCAmelCase_ ): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) new_pieces.append(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) _SCREAMING_SNAKE_CASE = i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) _SCREAMING_SNAKE_CASE = i if len(UpperCAmelCase_ ) > lst_i: new_pieces.append(piece[lst_i:] ) return new_pieces def UpperCamelCase ( self: Union[str, Any] , UpperCAmelCase_: List[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = """""".join(UpperCAmelCase_ ).replace(UpperCAmelCase_ , """ """ ).strip() return out_string def UpperCamelCase ( self: Tuple , UpperCAmelCase_: str ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.convert_ids_to_tokens(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = """""".join(UpperCAmelCase_ ).replace(UpperCAmelCase_ , """ """ ).strip() return out_string def UpperCamelCase ( self: Optional[Any] , UpperCAmelCase_: str ): '''simple docstring''' return self.vocab.get(UpperCAmelCase_ , self.vocab.get(self.unk_token ) ) def UpperCamelCase ( self: Optional[int] , UpperCAmelCase_: Optional[int] ): '''simple docstring''' return self.reverse_vocab.get(UpperCAmelCase_ , self.unk_token ) def UpperCamelCase ( self: Union[str, Any] , UpperCAmelCase_: str , UpperCAmelCase_: Dict=None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _SCREAMING_SNAKE_CASE = [self.cls_token_id] _SCREAMING_SNAKE_CASE = [self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def UpperCamelCase ( self: List[str] , UpperCAmelCase_: Union[str, Any] , UpperCAmelCase_: Dict=None ): '''simple docstring''' if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def UpperCamelCase ( self: Tuple , UpperCAmelCase_: List[Any] , UpperCAmelCase_: Dict=None , UpperCAmelCase_: Tuple=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(UpperCAmelCase_ )) + [1, 1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def UpperCamelCase ( self: str , UpperCAmelCase_: List[int] , UpperCAmelCase_: Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: # [CLS] X [SEP] return (len(UpperCAmelCase_ ) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(UpperCAmelCase_ ) + 1) + [1] * (len(UpperCAmelCase_ ) + 3) def UpperCamelCase ( self: int , UpperCAmelCase_: str ): '''simple docstring''' if "\u4e00" <= char <= "\u9fff": return True return False def UpperCamelCase ( self: Optional[Any] , UpperCAmelCase_: Optional[int] ): '''simple docstring''' if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def UpperCamelCase ( self: List[str] , UpperCAmelCase_: str ): '''simple docstring''' if char in ",;:.?!~,;:。?!《》【】": return True return False def UpperCamelCase ( self: Union[str, Any] , UpperCAmelCase_: str ): '''simple docstring''' if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(UpperCAmelCase_ ) == 1: _SCREAMING_SNAKE_CASE = unicodedata.category(UpperCAmelCase_ ) if cat == "Zs": return True return False def UpperCamelCase ( self: Optional[Any] , UpperCAmelCase_: Tuple ): '''simple docstring''' _SCREAMING_SNAKE_CASE = {} with io.open(UpperCAmelCase_ , """r""" , encoding="""utf-8""" ) as f: for index, line in enumerate(UpperCAmelCase_ ): _SCREAMING_SNAKE_CASE = line.rstrip("""\n""" ) _SCREAMING_SNAKE_CASE = int(UpperCAmelCase_ ) return token_to_idx def UpperCamelCase ( self: Union[str, Any] , UpperCAmelCase_: str , UpperCAmelCase_: Optional[str] = None ): '''simple docstring''' _SCREAMING_SNAKE_CASE = 0 if os.path.isdir(UpperCAmelCase_ ): _SCREAMING_SNAKE_CASE = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) else: _SCREAMING_SNAKE_CASE = (filename_prefix + """-""" if filename_prefix else """""") + save_directory with open(UpperCAmelCase_ , """w""" , encoding="""utf-8""" ) as writer: for token, token_index in sorted(self.vocab.items() , key=lambda UpperCAmelCase_ : kv[1] ): if index != token_index: logger.warning( F'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.' """ Please check that the vocabulary is not corrupted!""" ) _SCREAMING_SNAKE_CASE = token_index writer.write(token + """\n""" ) index += 1 _SCREAMING_SNAKE_CASE = os.path.join(UpperCAmelCase_ , """sentencepiece.bpe.model""" ) with open(UpperCAmelCase_ , """wb""" ) as fi: _SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (vocab_file,)
125
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCamelCase = { '''configuration_layoutlmv3''': [ '''LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LayoutLMv3Config''', '''LayoutLMv3OnnxConfig''', ], '''processing_layoutlmv3''': ['''LayoutLMv3Processor'''], '''tokenization_layoutlmv3''': ['''LayoutLMv3Tokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''LayoutLMv3TokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LayoutLMv3ForQuestionAnswering''', '''LayoutLMv3ForSequenceClassification''', '''LayoutLMv3ForTokenClassification''', '''LayoutLMv3Model''', '''LayoutLMv3PreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFLayoutLMv3ForQuestionAnswering''', '''TFLayoutLMv3ForSequenceClassification''', '''TFLayoutLMv3ForTokenClassification''', '''TFLayoutLMv3Model''', '''TFLayoutLMv3PreTrainedModel''', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''LayoutLMv3FeatureExtractor'''] UpperCamelCase = ['''LayoutLMv3ImageProcessor'''] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
125
1
import qiskit def lowerCAmelCase_ ( snake_case_,snake_case_ ): _A : List[str] = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register _A : Tuple = qiskit.QuantumCircuit(__UpperCAmelCase,__UpperCAmelCase ) # Map the quantum measurement to the classical bits circuit.measure([0],[0] ) # Execute the circuit on the simulator _A : int = qiskit.execute(__UpperCAmelCase,__UpperCAmelCase,shots=1000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(__UpperCAmelCase ) if __name__ == "__main__": print(f"""Total count for various states are: {single_qubit_measure(1, 1)}""")
26
'''simple docstring''' from collections import defaultdict def __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' snake_case_ = 1 snake_case_ = True for v in tree[start]: if v not in visited: ret += dfs(__UpperCAmelCase ) if ret % 2 == 0: cuts.append(__UpperCAmelCase ) return ret def __magic_name__ ( ) -> Union[str, Any]: '''simple docstring''' dfs(1 ) if __name__ == "__main__": a ,a : Dict = 10, 9 a : Dict = defaultdict(list) a : dict[int, bool] = {} a : list[int] = [] a : Tuple = 0 a : str = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
56
0
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib _A = { '''debug''': logging.DEBUG, '''info''': logging.INFO, '''warning''': logging.WARNING, '''error''': logging.ERROR, '''critical''': logging.CRITICAL, } _A = logging.WARNING def lowerCamelCase__ ( ) -> Any: UpperCamelCase_ = os.getenv("""DATASETS_VERBOSITY""" , a__ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f'''Unknown option DATASETS_VERBOSITY={env_level_str}, ''' f'''has to be one of: { ", ".join(log_levels.keys() ) }''' ) return _default_log_level def lowerCamelCase__ ( ) -> str: return __name__.split(""".""" )[0] def lowerCamelCase__ ( ) -> logging.Logger: return logging.getLogger(_get_library_name() ) def lowerCamelCase__ ( ) -> None: # Apply our default configuration to the library root logger. UpperCamelCase_ = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def lowerCamelCase__ ( ) -> None: UpperCamelCase_ = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def lowerCamelCase__ ( a__ : Optional[str] = None ) -> logging.Logger: if name is None: UpperCamelCase_ = _get_library_name() return logging.getLogger(a__ ) def lowerCamelCase__ ( ) -> int: return _get_library_root_logger().getEffectiveLevel() def lowerCamelCase__ ( a__ : int ) -> None: _get_library_root_logger().setLevel(a__ ) def lowerCamelCase__ ( ) -> Dict: return set_verbosity(a__ ) def lowerCamelCase__ ( ) -> str: return set_verbosity(a__ ) def lowerCamelCase__ ( ) -> str: return set_verbosity(a__ ) def lowerCamelCase__ ( ) -> List[str]: return set_verbosity(a__ ) def lowerCamelCase__ ( ) -> None: UpperCamelCase_ = False def lowerCamelCase__ ( ) -> None: UpperCamelCase_ = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class lowercase_ : def __init__( self , *__UpperCamelCase , **__UpperCamelCase ): # pylint: disable=unused-argument """simple docstring""" UpperCamelCase_ = args[0] if args else None def __iter__( self ): """simple docstring""" return iter(self._iterator ) def __getattr__( self , __UpperCamelCase ): """simple docstring""" def empty_fn(*__UpperCamelCase , **__UpperCamelCase ): # pylint: disable=unused-argument return return empty_fn def __enter__( self ): """simple docstring""" return self def __exit__( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return _A = True class lowercase_ : def __call__( self , *__UpperCamelCase , __UpperCamelCase=False , **__UpperCamelCase ): """simple docstring""" if _tqdm_active and not disable: return tqdm_lib.tqdm(*__UpperCamelCase , **__UpperCamelCase ) else: return EmptyTqdm(*__UpperCamelCase , **__UpperCamelCase ) def lowerCamelCase_ ( self , *__UpperCamelCase , **__UpperCamelCase ): """simple docstring""" UpperCamelCase_ = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*__UpperCamelCase , **__UpperCamelCase ) def lowerCamelCase_ ( self ): """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm.get_lock() _A = _tqdm_cls() def lowerCamelCase__ ( ) -> bool: global _tqdm_active return bool(_tqdm_active ) def lowerCamelCase__ ( ) -> Union[str, Any]: global _tqdm_active UpperCamelCase_ = True def lowerCamelCase__ ( ) -> Tuple: global _tqdm_active UpperCamelCase_ = False
261
from math import pow, sqrt def lowerCamelCase__ ( *a__ : float ) -> bool: UpperCamelCase_ = len(a__ ) > 0 and all(value > 0.0 for value in values ) return result def lowerCamelCase__ ( a__ : float , a__ : float ) -> float | ValueError: return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(a__ , a__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def lowerCamelCase__ ( a__ : float , a__ : float , a__ : float ) -> float | ValueError: return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(a__ , a__ , a__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def lowerCamelCase__ ( a__ : float , a__ : float , a__ : float ) -> float | ValueError: return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(a__ , a__ , a__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def lowerCamelCase__ ( a__ : float , a__ : float , a__ : float ) -> float | ValueError: return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(a__ , a__ , a__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def lowerCamelCase__ ( a__ : float , a__ : float , a__ : float ) -> float | ValueError: return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(a__ , a__ , a__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
261
1
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, 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(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase__ ) class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' def __init__( self , **UpperCamelCase__ ) -> Optional[Any]: super().__init__(**UpperCamelCase__ ) requires_backends(self , "vision" ) self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING ) def __call__( self , UpperCamelCase__ , **UpperCamelCase__ ) -> Optional[int]: return super().__call__(UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self , **UpperCamelCase__ ) -> List[Any]: lowerCamelCase : Optional[int] = {} if "candidate_labels" in kwargs: lowerCamelCase : str = kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase : str = kwargs["hypothesis_template"] return preprocess_params, {}, {} def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__="This is a photo of {}." ) -> List[Any]: lowerCamelCase : Optional[Any] = load_image(UpperCamelCase__ ) lowerCamelCase : List[Any] = self.image_processor(images=[image] , return_tensors=self.framework ) lowerCamelCase : Dict = candidate_labels lowerCamelCase : Dict = [hypothesis_template.format(UpperCamelCase__ ) for x in candidate_labels] lowerCamelCase : Dict = self.tokenizer(UpperCamelCase__ , return_tensors=self.framework , padding=UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = [text_inputs] return inputs def _lowercase ( self , UpperCamelCase__ ) -> Union[str, Any]: lowerCamelCase : List[str] = model_inputs.pop("candidate_labels" ) lowerCamelCase : Dict = model_inputs.pop("text_inputs" ) if isinstance(text_inputs[0] , UpperCamelCase__ ): lowerCamelCase : Dict = text_inputs[0] else: # Batching case. lowerCamelCase : int = text_inputs[0][0] lowerCamelCase : List[Any] = self.model(**UpperCamelCase__ , **UpperCamelCase__ ) lowerCamelCase : Tuple = { "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def _lowercase ( self , UpperCamelCase__ ) -> str: lowerCamelCase : Union[str, Any] = model_outputs.pop("candidate_labels" ) lowerCamelCase : Tuple = model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase : Any = logits.softmax(dim=-1 ).squeeze(-1 ) lowerCamelCase : Optional[Any] = probs.tolist() if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase : List[Any] = [scores] elif self.framework == "tf": lowerCamelCase : str = stable_softmax(UpperCamelCase__ , axis=-1 ) lowerCamelCase : str = probs.numpy().tolist() else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) lowerCamelCase : Any = [ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCamelCase__ , UpperCamelCase__ ) , key=lambda UpperCamelCase__ : -x[0] ) ] return result
48
import os import re import sys import traceback import warnings from pathlib import Path from typing import Dict, Optional, Union from uuid import uuida from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami from huggingface_hub.file_download import REGEX_COMMIT_HASH from huggingface_hub.utils import ( EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError, is_jinja_available, ) from packaging import version from requests import HTTPError from .. import __version__ from .constants import ( DEPRECATED_REVISION_ARGS, DIFFUSERS_CACHE, HUGGINGFACE_CO_RESOLVE_ENDPOINT, SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME, ) from .import_utils import ( ENV_VARS_TRUE_VALUES, _flax_version, _jax_version, _onnxruntime_version, _torch_version, is_flax_available, is_onnx_available, is_torch_available, ) from .logging import get_logger __a :Dict = get_logger(__name__) __a :Union[str, Any] = Path(__file__).parent / 'model_card_template.md' __a :Tuple = uuida().hex __a :List[Any] = os.getenv('HF_HUB_OFFLINE', '').upper() in ENV_VARS_TRUE_VALUES __a :Union[str, Any] = os.getenv('DISABLE_TELEMETRY', '').upper() in ENV_VARS_TRUE_VALUES __a :Tuple = HUGGINGFACE_CO_RESOLVE_ENDPOINT + '/api/telemetry/' def __snake_case ( __UpperCamelCase : Union[Dict, str, None] = None ): """simple docstring""" A_ = f'''diffusers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}''' if DISABLE_TELEMETRY or HF_HUB_OFFLINE: return ua + "; telemetry/off" if is_torch_available(): ua += f'''; torch/{_torch_version}''' if is_flax_available(): ua += f'''; jax/{_jax_version}''' ua += f'''; flax/{_flax_version}''' if is_onnx_available(): ua += f'''; onnxruntime/{_onnxruntime_version}''' # CI will set this value to True if os.environ.get("DIFFUSERS_IS_CI" ,"" ).upper() in ENV_VARS_TRUE_VALUES: ua += "; is_ci/true" if isinstance(__UpperCamelCase ,__UpperCamelCase ): ua += "; " + "; ".join(f'''{k}/{v}''' for k, v in user_agent.items() ) elif isinstance(__UpperCamelCase ,__UpperCamelCase ): ua += "; " + user_agent return ua def __snake_case ( __UpperCamelCase : str ,__UpperCamelCase : Optional[str] = None ,__UpperCamelCase : Optional[str] = None ): """simple docstring""" if token is None: A_ = HfFolder.get_token() if organization is None: A_ = whoami(__UpperCamelCase )["name"] return f'''{username}/{model_id}''' else: return f'''{organization}/{model_id}''' def __snake_case ( __UpperCamelCase : Tuple ,__UpperCamelCase : Union[str, Any] ): """simple docstring""" if not is_jinja_available(): raise ValueError( "Modelcard rendering is based on Jinja templates." " Please make sure to have `jinja` installed before using `create_model_card`." " To install it, please run `pip install Jinja2`." ) if hasattr(__UpperCamelCase ,"local_rank" ) and args.local_rank not in [-1, 0]: return A_ = args.hub_token if hasattr(__UpperCamelCase ,"hub_token" ) else None A_ = get_full_repo_name(__UpperCamelCase ,token=__UpperCamelCase ) A_ = ModelCard.from_template( card_data=ModelCardData( # Card metadata object that will be converted to YAML block language="en" ,license="apache-2.0" ,library_name="diffusers" ,tags=[] ,datasets=args.dataset_name ,metrics=[] ,) ,template_path=__UpperCamelCase ,model_name=__UpperCamelCase ,repo_name=__UpperCamelCase ,dataset_name=args.dataset_name if hasattr(__UpperCamelCase ,"dataset_name" ) else None ,learning_rate=args.learning_rate ,train_batch_size=args.train_batch_size ,eval_batch_size=args.eval_batch_size ,gradient_accumulation_steps=( args.gradient_accumulation_steps if hasattr(__UpperCamelCase ,"gradient_accumulation_steps" ) else None ) ,adam_betaa=args.adam_betaa if hasattr(__UpperCamelCase ,"adam_beta1" ) else None ,adam_betaa=args.adam_betaa if hasattr(__UpperCamelCase ,"adam_beta2" ) else None ,adam_weight_decay=args.adam_weight_decay if hasattr(__UpperCamelCase ,"adam_weight_decay" ) else None ,adam_epsilon=args.adam_epsilon if hasattr(__UpperCamelCase ,"adam_epsilon" ) else None ,lr_scheduler=args.lr_scheduler if hasattr(__UpperCamelCase ,"lr_scheduler" ) else None ,lr_warmup_steps=args.lr_warmup_steps if hasattr(__UpperCamelCase ,"lr_warmup_steps" ) else None ,ema_inv_gamma=args.ema_inv_gamma if hasattr(__UpperCamelCase ,"ema_inv_gamma" ) else None ,ema_power=args.ema_power if hasattr(__UpperCamelCase ,"ema_power" ) else None ,ema_max_decay=args.ema_max_decay if hasattr(__UpperCamelCase ,"ema_max_decay" ) else None ,mixed_precision=args.mixed_precision ,) A_ = os.path.join(args.output_dir ,"README.md" ) model_card.save(__UpperCamelCase ) def __snake_case ( __UpperCamelCase : Optional[str] ,__UpperCamelCase : Optional[str] = None ): """simple docstring""" if resolved_file is None or commit_hash is not None: return commit_hash A_ = str(Path(__UpperCamelCase ).as_posix() ) A_ = re.search(R"snapshots/([^/]+)/" ,__UpperCamelCase ) if search is None: return None A_ = search.groups()[0] return commit_hash if REGEX_COMMIT_HASH.match(__UpperCamelCase ) else None # Old default cache path, potentially to be migrated. # This logic was more or less taken from `transformers`, with the following differences: # - Diffusers doesn't use custom environment variables to specify the cache path. # - There is no need to migrate the cache format, just move the files to the new location. __a :str = os.path.expanduser( os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface')) ) __a :List[Any] = os.path.join(hf_cache_home, 'diffusers') def __snake_case ( __UpperCamelCase : Optional[str] = None ,__UpperCamelCase : Optional[str] = None ): """simple docstring""" if new_cache_dir is None: A_ = DIFFUSERS_CACHE if old_cache_dir is None: A_ = old_diffusers_cache A_ = Path(__UpperCamelCase ).expanduser() A_ = Path(__UpperCamelCase ).expanduser() for old_blob_path in old_cache_dir.glob("**/blobs/*" ): if old_blob_path.is_file() and not old_blob_path.is_symlink(): A_ = new_cache_dir / old_blob_path.relative_to(__UpperCamelCase ) new_blob_path.parent.mkdir(parents=__UpperCamelCase ,exist_ok=__UpperCamelCase ) os.replace(__UpperCamelCase ,__UpperCamelCase ) try: os.symlink(__UpperCamelCase ,__UpperCamelCase ) except OSError: logger.warning( "Could not create symlink between old cache and new cache. If you use an older version of diffusers again, files will be re-downloaded." ) # At this point, old_cache_dir contains symlinks to the new cache (it can still be used). __a :Dict = os.path.join(DIFFUSERS_CACHE, 'version_diffusers_cache.txt') if not os.path.isfile(cache_version_file): __a :Optional[int] = 0 else: with open(cache_version_file) as f: try: __a :Dict = int(f.read()) except ValueError: __a :str = 0 if cache_version < 1: __a :Optional[Any] = os.path.isdir(old_diffusers_cache) and len(os.listdir(old_diffusers_cache)) > 0 if old_cache_is_not_empty: logger.warning( 'The cache for model files in Diffusers v0.14.0 has moved to a new location. Moving your ' 'existing cached models. This is a one-time operation, you can interrupt it or run it ' 'later by calling `diffusers.utils.hub_utils.move_cache()`.' ) try: move_cache() except Exception as e: __a :Optional[Any] = '\n'.join(traceback.format_tb(e.__traceback__)) logger.error( F"There was a problem when trying to move your cache:\n\n{trace}\n{e.__class__.__name__}: {e}\n\nPlease " 'file an issue at https://github.com/huggingface/diffusers/issues/new/choose, copy paste this whole ' 'message and we will do our best to help.' ) if cache_version < 1: try: os.makedirs(DIFFUSERS_CACHE, exist_ok=True) with open(cache_version_file, 'w') as f: f.write('1') except Exception: logger.warning( F"There was a problem when trying to write in your cache folder ({DIFFUSERS_CACHE}). Please, ensure " 'the directory exists and can be written to.' ) def __snake_case ( __UpperCamelCase : str ,__UpperCamelCase : Optional[str] = None ): """simple docstring""" if variant is not None: A_ = weights_name.split("." ) A_ = splits[:-1] + [variant] + splits[-1:] A_ = ".".join(__UpperCamelCase ) return weights_name def __snake_case ( __UpperCamelCase : Optional[Any] ,*, __UpperCamelCase : Union[str, Any] ,__UpperCamelCase : Any ,__UpperCamelCase : Tuple ,__UpperCamelCase : Union[str, Any] ,__UpperCamelCase : str ,__UpperCamelCase : int ,__UpperCamelCase : Union[str, Any] ,__UpperCamelCase : int ,__UpperCamelCase : Optional[int] ,__UpperCamelCase : Tuple ,__UpperCamelCase : Optional[int]=None ,): """simple docstring""" A_ = str(__UpperCamelCase ) if os.path.isfile(__UpperCamelCase ): return pretrained_model_name_or_path elif os.path.isdir(__UpperCamelCase ): if os.path.isfile(os.path.join(__UpperCamelCase ,__UpperCamelCase ) ): # Load from a PyTorch checkpoint A_ = os.path.join(__UpperCamelCase ,__UpperCamelCase ) return model_file elif subfolder is not None and os.path.isfile( os.path.join(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) ): A_ = os.path.join(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) return model_file else: raise EnvironmentError( f'''Error no file named {weights_name} found in directory {pretrained_model_name_or_path}.''' ) else: # 1. First check if deprecated way of loading from branches is used if ( revision in DEPRECATED_REVISION_ARGS and (weights_name == WEIGHTS_NAME or weights_name == SAFETENSORS_WEIGHTS_NAME) and version.parse(version.parse(__UpperCamelCase ).base_version ) >= version.parse("0.20.0" ) ): try: A_ = hf_hub_download( __UpperCamelCase ,filename=_add_variant(__UpperCamelCase ,__UpperCamelCase ) ,cache_dir=__UpperCamelCase ,force_download=__UpperCamelCase ,proxies=__UpperCamelCase ,resume_download=__UpperCamelCase ,local_files_only=__UpperCamelCase ,use_auth_token=__UpperCamelCase ,user_agent=__UpperCamelCase ,subfolder=__UpperCamelCase ,revision=revision or commit_hash ,) warnings.warn( f'''Loading the variant {revision} from {pretrained_model_name_or_path} via `revision=\'{revision}\'` is deprecated. Loading instead from `revision=\'main\'` with `variant={revision}`. Loading model variants via `revision=\'{revision}\'` will be removed in diffusers v1. Please use `variant=\'{revision}\'` instead.''' ,__UpperCamelCase ,) return model_file except: # noqa: E722 warnings.warn( f'''You are loading the variant {revision} from {pretrained_model_name_or_path} via `revision=\'{revision}\'`. This behavior is deprecated and will be removed in diffusers v1. One should use `variant=\'{revision}\'` instead. However, it appears that {pretrained_model_name_or_path} currently does not have a {_add_variant(__UpperCamelCase ,__UpperCamelCase )} file in the \'main\' branch of {pretrained_model_name_or_path}. \n The Diffusers team and community would be very grateful if you could open an issue: https://github.com/huggingface/diffusers/issues/new with the title \'{pretrained_model_name_or_path} is missing {_add_variant(__UpperCamelCase ,__UpperCamelCase )}\' so that the correct variant file can be added.''' ,__UpperCamelCase ,) try: # 2. Load model file as usual A_ = hf_hub_download( __UpperCamelCase ,filename=__UpperCamelCase ,cache_dir=__UpperCamelCase ,force_download=__UpperCamelCase ,proxies=__UpperCamelCase ,resume_download=__UpperCamelCase ,local_files_only=__UpperCamelCase ,use_auth_token=__UpperCamelCase ,user_agent=__UpperCamelCase ,subfolder=__UpperCamelCase ,revision=revision or commit_hash ,) return model_file except RepositoryNotFoundError: raise EnvironmentError( f'''{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier ''' "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a " "token having permission to this repo with `use_auth_token` or log in with `huggingface-cli " "login`." ) except RevisionNotFoundError: raise EnvironmentError( f'''{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for ''' "this model name. Check the model page at " f'''\'https://huggingface.co/{pretrained_model_name_or_path}\' for available revisions.''' ) except EntryNotFoundError: raise EnvironmentError( f'''{pretrained_model_name_or_path} does not appear to have a file named {weights_name}.''' ) except HTTPError as err: raise EnvironmentError( f'''There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{err}''' ) except ValueError: raise EnvironmentError( f'''We couldn\'t connect to \'{HUGGINGFACE_CO_RESOLVE_ENDPOINT}\' to load this model, couldn\'t find it''' f''' in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a''' f''' directory containing a file named {weights_name} or''' " \nCheckout your internet connection or see how to run the library in" " offline mode at 'https://huggingface.co/docs/diffusers/installation#offline-mode'." ) except EnvironmentError: raise EnvironmentError( f'''Can\'t load the model for \'{pretrained_model_name_or_path}\'. If you were trying to load it from ''' "'https://huggingface.co/models', make sure you don't have a local directory with the same name. " f'''Otherwise, make sure \'{pretrained_model_name_or_path}\' is the correct path to a directory ''' f'''containing a file named {weights_name}''' )
312
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'vinvino02/glpn-kitti': 'https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json', # See all GLPN models at https://huggingface.co/models?filter=glpn } class _lowercase ( snake_case_ ): lowercase = 'glpn' def __init__( self : Optional[Any] , snake_case : str=3 , snake_case : List[Any]=4 , snake_case : Optional[Any]=[2, 2, 2, 2] , snake_case : Union[str, Any]=[8, 4, 2, 1] , snake_case : Optional[Any]=[3_2, 6_4, 1_6_0, 2_5_6] , snake_case : List[Any]=[7, 3, 3, 3] , snake_case : Any=[4, 2, 2, 2] , snake_case : Any=[1, 2, 5, 8] , snake_case : Union[str, Any]=[4, 4, 4, 4] , snake_case : Optional[Any]="gelu" , snake_case : str=0.0 , snake_case : Tuple=0.0 , snake_case : Optional[int]=0.02 , snake_case : Tuple=0.1 , snake_case : Union[str, Any]=1e-6 , snake_case : str=6_4 , snake_case : Optional[int]=1_0 , snake_case : Union[str, Any]=-1 , **snake_case : Any , ) -> str: """simple docstring""" super().__init__(**snake_case ) UpperCamelCase_ : Any = num_channels UpperCamelCase_ : Union[str, Any] = num_encoder_blocks UpperCamelCase_ : Dict = depths UpperCamelCase_ : List[Any] = sr_ratios UpperCamelCase_ : str = hidden_sizes UpperCamelCase_ : str = patch_sizes UpperCamelCase_ : str = strides UpperCamelCase_ : str = mlp_ratios UpperCamelCase_ : Union[str, Any] = num_attention_heads UpperCamelCase_ : Optional[Any] = hidden_act UpperCamelCase_ : Optional[Any] = hidden_dropout_prob UpperCamelCase_ : Optional[int] = attention_probs_dropout_prob UpperCamelCase_ : List[str] = initializer_range UpperCamelCase_ : Tuple = drop_path_rate UpperCamelCase_ : Optional[int] = layer_norm_eps UpperCamelCase_ : Optional[int] = decoder_hidden_size UpperCamelCase_ : str = max_depth UpperCamelCase_ : List[str] = head_in_index
50
def __lowercase ( lowerCamelCase : list[int] ): if not numbers: return 0 if not isinstance(lowerCamelCase , (list, tuple) ) or not all( isinstance(lowerCamelCase , lowerCamelCase ) for number in numbers ): raise ValueError('numbers must be an iterable of integers' ) UpperCamelCase_ : Optional[Any] = numbers[0] for i in range(1 , len(lowerCamelCase ) ): # update the maximum and minimum subarray products UpperCamelCase_ : Tuple = numbers[i] if number < 0: UpperCamelCase_, UpperCamelCase_ : List[str] = min_till_now, max_till_now UpperCamelCase_ : List[str] = max(lowerCamelCase , max_till_now * number ) UpperCamelCase_ : Dict = min(lowerCamelCase , min_till_now * number ) # update the maximum product found till now UpperCamelCase_ : List[str] = max(lowerCamelCase , lowerCamelCase ) return max_prod
50
1
"""simple docstring""" import os import re import shutil from argparse import ArgumentParser, Namespace from datasets.commands import BaseDatasetsCLICommand from datasets.utils.logging import get_logger a : int = '''<<<<<<< This should probably be modified because it mentions: ''' a : Tuple = '''======= >>>>>>> ''' a : List[Any] = [ '''TextEncoderConfig''', '''ByteTextEncoder''', '''SubwordTextEncoder''', '''encoder_config''', '''maybe_build_from_corpus''', '''manual_dir''', ] a : Union[str, Any] = [ # (pattern, replacement) # Order is important here for some replacements (R'''tfds\.core''', R'''datasets'''), (R'''tf\.io\.gfile\.GFile''', R'''open'''), (R'''tf\.([\w\d]+)''', R'''datasets.Value(\'\1\')'''), (R'''tfds\.features\.Text\(\)''', R'''datasets.Value(\'string\')'''), (R'''tfds\.features\.Text\(''', R'''datasets.Value(\'string\'),'''), (R'''features\s*=\s*tfds.features.FeaturesDict\(''', R'''features=datasets.Features('''), (R'''tfds\.features\.FeaturesDict\(''', R'''dict('''), (R'''The TensorFlow Datasets Authors''', R'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''), (R'''tfds\.''', R'''datasets.'''), (R'''dl_manager\.manual_dir''', R'''self.config.data_dir'''), (R'''self\.builder_config''', R'''self.config'''), ] def _SCREAMING_SNAKE_CASE ( _lowercase : Namespace ) ->Any: '''simple docstring''' return ConvertCommand(args.tfds_path , args.datasets_directory ) class __UpperCamelCase ( a__ ): @staticmethod def __a ( lowerCAmelCase__ ) -> int: a : Any = parser.add_parser( "convert" , help="Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset." , ) train_parser.add_argument( "--tfds_path" , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="Path to a TensorFlow Datasets folder to convert or a single tfds file to convert." , ) train_parser.add_argument( "--datasets_directory" , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help="Path to the HuggingFace Datasets folder." ) train_parser.set_defaults(func=lowerCAmelCase__ ) def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ ) -> Tuple: a : List[str] = get_logger("datasets-cli/converting" ) a : Optional[int] = tfds_path a : str = datasets_directory def __a ( self ) -> str: if os.path.isdir(self._tfds_path ): a : int = os.path.abspath(self._tfds_path ) elif os.path.isfile(self._tfds_path ): a : Optional[Any] = os.path.dirname(self._tfds_path ) else: raise ValueError("--tfds_path is neither a directory nor a file. Please check path." ) a : str = os.path.abspath(self._datasets_directory ) self._logger.info(f"""Converting datasets from {abs_tfds_path} to {abs_datasets_path}""" ) a : str = [] a : Union[str, Any] = [] a : str = {} if os.path.isdir(self._tfds_path ): a : Dict = os.listdir(lowerCAmelCase__ ) else: a : Dict = [os.path.basename(self._tfds_path )] for f_name in file_names: self._logger.info(f"""Looking at file {f_name}""" ) a : Any = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) a : Dict = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) if not os.path.isfile(lowerCAmelCase__ ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name: self._logger.info("Skipping file" ) continue with open(lowerCAmelCase__ , encoding="utf-8" ) as f: a : Any = f.readlines() a : Tuple = [] a : Any = False a : Dict = False a : Dict = [] for line in lines: a : Tuple = line # Convert imports if "import tensorflow.compat.v2 as tf" in out_line: continue elif "@tfds.core" in out_line: continue elif "builder=self" in out_line: continue elif "import tensorflow_datasets.public_api as tfds" in out_line: a : Optional[int] = "import datasets\n" elif "import tensorflow" in out_line: # order is important here a : Optional[Any] = "" continue elif "from absl import logging" in out_line: a : Any = "from datasets import logging\n" elif "getLogger" in out_line: a : int = out_line.replace("getLogger" , "get_logger" ) elif any(expression in out_line for expression in TO_HIGHLIGHT ): a : Optional[Any] = True a : Optional[Any] = list(filter(lambda lowerCAmelCase__ : e in out_line , lowerCAmelCase__ ) ) out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(lowerCAmelCase__ ) + "\n" ) out_lines.append(lowerCAmelCase__ ) out_lines.append(lowerCAmelCase__ ) continue else: for pattern, replacement in TO_CONVERT: a : int = re.sub(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Take care of saving utilities (to later move them together with main script) if "tensorflow_datasets" in out_line: a : int = re.match(R"from\stensorflow_datasets.*import\s([^\.\r\n]+)" , lowerCAmelCase__ ) tfds_imports.extend(imp.strip() for imp in match.group(1 ).split("," ) ) a : List[str] = "from . import " + match.group(1 ) # Check we have not forget anything if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line: raise ValueError(f"""Error converting {out_line.strip()}""" ) if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line: a : str = True out_lines.append(lowerCAmelCase__ ) if is_builder or "wmt" in f_name: # We create a new directory for each dataset a : Tuple = f_name.replace(".py" , "" ) a : Optional[Any] = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) a : Dict = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) self._logger.info(f"""Adding directory {output_dir}""" ) imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} ) else: # Utilities will be moved at the end utils_files.append(lowerCAmelCase__ ) if needs_manual_update: with_manual_update.append(lowerCAmelCase__ ) with open(lowerCAmelCase__ , "w" , encoding="utf-8" ) as f: f.writelines(lowerCAmelCase__ ) self._logger.info(f"""Converted in {output_file}""" ) for utils_file in utils_files: try: a : int = os.path.basename(lowerCAmelCase__ ) a : int = imports_to_builder_map[f_name.replace(".py" , "" )] self._logger.info(f"""Moving {dest_folder} to {utils_file}""" ) shutil.copy(lowerCAmelCase__ , lowerCAmelCase__ ) except KeyError: self._logger.error(f"""Cannot find destination folder for {utils_file}. Please copy manually.""" ) if with_manual_update: for file_path in with_manual_update: self._logger.warning( f"""You need to manually update file {file_path} to remove configurations using 'TextEncoderConfig'.""" )
105
"""simple docstring""" def _SCREAMING_SNAKE_CASE ( _lowercase : list ) ->int: '''simple docstring''' if not grid or not grid[0]: raise TypeError("The grid does not contain the appropriate information" ) for cell_n in range(1 , len(grid[0] ) ): grid[0][cell_n] += grid[0][cell_n - 1] a : Union[str, Any] = grid[0] for row_n in range(1 , len(_lowercase ) ): a : Optional[Any] = grid[row_n] a : Tuple = fill_row(_lowercase , _lowercase ) a : List[Any] = grid[row_n] return grid[-1][-1] def _SCREAMING_SNAKE_CASE ( _lowercase : list , _lowercase : list ) ->list: '''simple docstring''' current_row[0] += row_above[0] for cell_n in range(1 , len(_lowercase ) ): current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n] ) return current_row if __name__ == "__main__": import doctest doctest.testmod()
105
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_rembert import RemBertTokenizer else: SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : int = {"vocab_file": "sentencepiece.model", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE : List[str] = { "vocab_file": { "google/rembert": "https://huggingface.co/google/rembert/resolve/main/sentencepiece.model", }, "tokenizer_file": { "google/rembert": "https://huggingface.co/google/rembert/resolve/main/tokenizer.json", }, } SCREAMING_SNAKE_CASE : List[Any] = { "google/rembert": 256, } SCREAMING_SNAKE_CASE : Any = "▁" class _lowerCamelCase( _a ): lowercase_ : Any = VOCAB_FILES_NAMES lowercase_ : List[Any] = PRETRAINED_VOCAB_FILES_MAP lowercase_ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ : Any = RemBertTokenizer def __init__( self, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=False, lowerCamelCase="[CLS]", lowerCamelCase="[SEP]", lowerCamelCase="<unk>", lowerCamelCase="[SEP]", lowerCamelCase="<pad>", lowerCamelCase="[CLS]", lowerCamelCase="[MASK]", **lowerCamelCase, ) -> Any: """simple docstring""" _lowercase : Optional[int] = AddedToken(lowerCamelCase, lstrip=lowerCamelCase, rstrip=lowerCamelCase) if isinstance(lowerCamelCase, lowerCamelCase) else mask_token super().__init__( lowerCamelCase, tokenizer_file=lowerCamelCase, do_lower_case=lowerCamelCase, remove_space=lowerCamelCase, keep_accents=lowerCamelCase, bos_token=lowerCamelCase, eos_token=lowerCamelCase, unk_token=lowerCamelCase, sep_token=lowerCamelCase, pad_token=lowerCamelCase, cls_token=lowerCamelCase, mask_token=lowerCamelCase, **lowerCamelCase, ) _lowercase : Tuple = do_lower_case _lowercase : int = remove_space _lowercase : List[str] = keep_accents _lowercase : Tuple = vocab_file _lowercase : str = False if not self.vocab_file else True def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None) -> List[int]: """simple docstring""" _lowercase : List[Any] = [self.sep_token_id] _lowercase : Any = [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 UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None, lowerCamelCase = False) -> List[int]: """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(lowerCamelCase)) + [1] + ([0] * len(lowerCamelCase)) + [1] return [1] + ([0] * len(lowerCamelCase)) + [1] def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None) -> List[int]: """simple docstring""" _lowercase : str = [self.sep_token_id] _lowercase : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None) -> Tuple[str]: """simple docstring""" if not os.path.isdir(lowerCamelCase): logger.error('Vocabulary path ({}) should be a directory'.format(lowerCamelCase)) return _lowercase : List[Any] = os.path.join( lowerCamelCase, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowerCamelCase): copyfile(self.vocab_file, lowerCamelCase) return (out_vocab_file,)
84
import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) class _lowerCamelCase( _a ): def __init__( self, lowerCamelCase) -> List[Any]: """simple docstring""" super().__init__() _lowercase : Union[str, Any] = nn.ModuleList(lowerCamelCase) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = False, lowerCamelCase = True, ) -> Union[ControlNetOutput, Tuple]: """simple docstring""" for i, (image, scale, controlnet) in enumerate(zip(lowerCamelCase, lowerCamelCase, self.nets)): _lowercase , _lowercase : List[Any] = controlnet( lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) # merge samples if i == 0: _lowercase , _lowercase : int = down_samples, mid_sample else: _lowercase : Dict = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(lowerCamelCase, lowerCamelCase) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = True, lowerCamelCase = None, lowerCamelCase = False, lowerCamelCase = None, ) -> Tuple: """simple docstring""" _lowercase : Tuple = 0 _lowercase : int = save_directory for controlnet in self.nets: controlnet.save_pretrained( lowerCamelCase, is_main_process=lowerCamelCase, save_function=lowerCamelCase, safe_serialization=lowerCamelCase, variant=lowerCamelCase, ) idx += 1 _lowercase : Any = model_path_to_save + F'''_{idx}''' @classmethod def UpperCamelCase ( cls, lowerCamelCase, **lowerCamelCase) -> List[str]: """simple docstring""" _lowercase : Optional[int] = 0 _lowercase : int = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... _lowercase : Union[str, Any] = pretrained_model_path while os.path.isdir(lowerCamelCase): _lowercase : Optional[int] = ControlNetModel.from_pretrained(lowerCamelCase, **lowerCamelCase) controlnets.append(lowerCamelCase) idx += 1 _lowercase : List[Any] = pretrained_model_path + F'''_{idx}''' logger.info(F'''{len(lowerCamelCase)} controlnets loaded from {pretrained_model_path}.''') if len(lowerCamelCase) == 0: raise ValueError( F'''No ControlNets found under {os.path.dirname(lowerCamelCase)}. Expected at least {pretrained_model_path + "_0"}.''') return cls(lowerCamelCase)
84
1
import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class UpperCamelCase__ : '''simple docstring''' @staticmethod def _lowercase ( *UpperCamelCase__ , **UpperCamelCase__ ) -> Union[str, Any]: pass @is_pipeline_test @require_vision class UpperCamelCase__ (unittest.TestCase ): '''simple docstring''' @require_torch def _lowercase ( self ) -> Union[str, Any]: lowerCamelCase : Tuple = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , ) lowerCamelCase : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) lowerCamelCase : List[Any] = image_classifier(UpperCamelCase__ , candidate_labels=["a", "b", "c"] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(UpperCamelCase__ ) , [ [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}], ] , ) lowerCamelCase : List[Any] = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ [ {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, ], [ {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, ], [ {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, ], [ {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, ], [ {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, ], ] , ) @require_tf def _lowercase ( self ) -> int: lowerCamelCase : str = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , framework="tf" ) lowerCamelCase : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) lowerCamelCase : Dict = image_classifier(UpperCamelCase__ , candidate_labels=["a", "b", "c"] ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}] , ) lowerCamelCase : str = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ [ {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, ], [ {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, ], [ {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, ], [ {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, ], [ {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, {"score": 0.333, "label": ANY(UpperCamelCase__ )}, ], ] , ) @slow @require_torch def _lowercase ( self ) -> Optional[Any]: lowerCamelCase : int = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , ) # This is an image of 2 cats with remotes and no planes lowerCamelCase : Union[str, Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) lowerCamelCase : Optional[int] = image_classifier(UpperCamelCase__ , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) lowerCamelCase : Tuple = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , ) @slow @require_tf def _lowercase ( self ) -> Tuple: lowerCamelCase : str = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , framework="tf" ) # This is an image of 2 cats with remotes and no planes lowerCamelCase : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) lowerCamelCase : Tuple = image_classifier(UpperCamelCase__ , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ] , ) lowerCamelCase : int = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(UpperCamelCase__ ) , [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5 , )
48
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = { 'salesforce/blip2-opt-2.7b': 'https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json', } class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Union[str, Any] = """blip_2_vision_model""" def __init__( self , UpperCamelCase__=1408 , UpperCamelCase__=6144 , UpperCamelCase__=39 , UpperCamelCase__=16 , UpperCamelCase__=224 , UpperCamelCase__=14 , UpperCamelCase__="gelu" , UpperCamelCase__=0.00001 , UpperCamelCase__=0.0 , UpperCamelCase__=1e-10 , UpperCamelCase__=True , **UpperCamelCase__ , ) -> Optional[Any]: super().__init__(**UpperCamelCase__ ) lowerCamelCase : Dict = hidden_size lowerCamelCase : Union[str, Any] = intermediate_size lowerCamelCase : List[str] = num_hidden_layers lowerCamelCase : List[str] = num_attention_heads lowerCamelCase : Dict = patch_size lowerCamelCase : Tuple = image_size lowerCamelCase : Dict = initializer_range lowerCamelCase : Union[str, Any] = attention_dropout lowerCamelCase : Dict = layer_norm_eps lowerCamelCase : Optional[Any] = hidden_act lowerCamelCase : str = qkv_bias @classmethod def _lowercase ( cls , UpperCamelCase__ , **UpperCamelCase__ ) -> "PretrainedConfig": cls._set_token_in_kwargs(UpperCamelCase__ ) lowerCamelCase , lowerCamelCase : List[str] = cls.get_config_dict(UpperCamelCase__ , **UpperCamelCase__ ) # get the vision config dict if we are loading from Blip2Config if config_dict.get("model_type" ) == "blip-2": lowerCamelCase : Optional[int] = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(UpperCamelCase__ , **UpperCamelCase__ ) class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Dict = """blip_2_qformer""" def __init__( self , UpperCamelCase__=3_0522 , UpperCamelCase__=768 , UpperCamelCase__=12 , UpperCamelCase__=12 , UpperCamelCase__=3072 , UpperCamelCase__="gelu" , UpperCamelCase__=0.1 , UpperCamelCase__=0.1 , UpperCamelCase__=512 , UpperCamelCase__=0.02 , UpperCamelCase__=1e-12 , UpperCamelCase__=0 , UpperCamelCase__="absolute" , UpperCamelCase__=2 , UpperCamelCase__=1408 , **UpperCamelCase__ , ) -> int: super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ ) lowerCamelCase : Optional[int] = vocab_size lowerCamelCase : int = hidden_size lowerCamelCase : Dict = num_hidden_layers lowerCamelCase : Union[str, Any] = num_attention_heads lowerCamelCase : int = hidden_act lowerCamelCase : Optional[Any] = intermediate_size lowerCamelCase : Dict = hidden_dropout_prob lowerCamelCase : Dict = attention_probs_dropout_prob lowerCamelCase : Dict = max_position_embeddings lowerCamelCase : List[str] = initializer_range lowerCamelCase : List[str] = layer_norm_eps lowerCamelCase : int = position_embedding_type lowerCamelCase : Tuple = cross_attention_frequency lowerCamelCase : Optional[int] = encoder_hidden_size @classmethod def _lowercase ( cls , UpperCamelCase__ , **UpperCamelCase__ ) -> "PretrainedConfig": cls._set_token_in_kwargs(UpperCamelCase__ ) lowerCamelCase , lowerCamelCase : str = cls.get_config_dict(UpperCamelCase__ , **UpperCamelCase__ ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get("model_type" ) == "blip-2": lowerCamelCase : int = config_dict["qformer_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(UpperCamelCase__ , **UpperCamelCase__ ) class UpperCamelCase__ (lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : List[str] = """blip-2""" lowerCamelCase_ : int = True def __init__( self , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=32 , **UpperCamelCase__ ) -> str: super().__init__(**UpperCamelCase__ ) if vision_config is None: lowerCamelCase : List[Any] = {} logger.info("vision_config is None. initializing the Blip2VisionConfig with default values." ) if qformer_config is None: lowerCamelCase : List[Any] = {} logger.info("qformer_config is None. Initializing the Blip2QFormerConfig with default values." ) if text_config is None: lowerCamelCase : Any = {} logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`)." ) lowerCamelCase : Optional[int] = BlipaVisionConfig(**UpperCamelCase__ ) lowerCamelCase : str = BlipaQFormerConfig(**UpperCamelCase__ ) lowerCamelCase : List[str] = text_config["model_type"] if "model_type" in text_config else "opt" lowerCamelCase : str = CONFIG_MAPPING[text_model_type](**UpperCamelCase__ ) lowerCamelCase : Optional[Any] = self.text_config.tie_word_embeddings lowerCamelCase : int = self.text_config.is_encoder_decoder lowerCamelCase : Optional[Any] = num_query_tokens lowerCamelCase : int = self.vision_config.hidden_size lowerCamelCase : Tuple = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES lowerCamelCase : Dict = 1.0 lowerCamelCase : List[Any] = 0.02 @classmethod def _lowercase ( cls , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ , ) -> str: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **UpperCamelCase__ , ) def _lowercase ( self ) -> Optional[Any]: lowerCamelCase : Tuple = copy.deepcopy(self.__dict__ ) lowerCamelCase : Tuple = self.vision_config.to_dict() lowerCamelCase : int = self.qformer_config.to_dict() lowerCamelCase : Optional[Any] = self.text_config.to_dict() lowerCamelCase : int = self.__class__.model_type return output
48
1
from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets _lowerCamelCase : Optional[int] = '''\ @inproceedings{wang2019glue, title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding}, author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.}, note={In the Proceedings of ICLR.}, year={2019} } ''' _lowerCamelCase : Dict = '''\ GLUE, the General Language Understanding Evaluation benchmark (https://gluebenchmark.com/) is a collection of resources for training, evaluating, and analyzing natural language understanding systems. ''' _lowerCamelCase : Optional[Any] = ''' Compute GLUE evaluation metric associated to each GLUE dataset. Args: predictions: list of predictions to score. Each translation should be tokenized into a list of tokens. references: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. Returns: depending on the GLUE subset, one or several of: "accuracy": Accuracy "f1": F1 score "pearson": Pearson Correlation "spearmanr": Spearman Correlation "matthews_correlation": Matthew Correlation Examples: >>> glue_metric = datasets.load_metric(\'glue\', \'sst2\') # \'sst2\' or any of ["mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> glue_metric = datasets.load_metric(\'glue\', \'mrpc\') # \'mrpc\' or \'qqp\' >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> glue_metric = datasets.load_metric(\'glue\', \'stsb\') >>> references = [0., 1., 2., 3., 4., 5.] >>> predictions = [0., 1., 2., 3., 4., 5.] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print({"pearson": round(results["pearson"], 2), "spearmanr": round(results["spearmanr"], 2)}) {\'pearson\': 1.0, \'spearmanr\': 1.0} >>> glue_metric = datasets.load_metric(\'glue\', \'cola\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def _a ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: '''simple docstring''' return float((preds == labels).mean() ) def _a ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = simple_accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = float(fa_score(y_true=SCREAMING_SNAKE_CASE__ , y_pred=SCREAMING_SNAKE_CASE__ ) ) return { "accuracy": acc, "f1": fa, } def _a ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = float(pearsonr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = float(spearmanr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase (datasets.Metric ): """simple docstring""" def A_ ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( "You should supply a configuration name selected in " "[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", " "\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]" ) return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { "predictions": datasets.Value("int64" if self.config_name != "stsb" else "float32" ), "references": datasets.Value("int64" if self.config_name != "stsb" else "float32" ), } ), codebase_urls=[], reference_urls=[], format="numpy", ) def A_ ( self : List[str], _UpperCAmelCase : List[str], _UpperCAmelCase : List[str] ) -> Any: """simple docstring""" if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(_UpperCAmelCase, _UpperCAmelCase )} elif self.config_name == "stsb": return pearson_and_spearman(_UpperCAmelCase, _UpperCAmelCase ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(_UpperCAmelCase, _UpperCAmelCase ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(_UpperCAmelCase, _UpperCAmelCase )} else: raise KeyError( "You should supply a configuration name selected in " "[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", " "\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]" )
191
import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCamelCase : """simple docstring""" def __init__( self : List[Any], _UpperCAmelCase : Optional[Any], _UpperCAmelCase : List[Any]=1_3, _UpperCAmelCase : Optional[Any]=3_0, _UpperCAmelCase : List[str]=2, _UpperCAmelCase : str=3, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : Optional[Any]=3_2, _UpperCAmelCase : Any=5, _UpperCAmelCase : Optional[Any]=4, _UpperCAmelCase : List[Any]=3_7, _UpperCAmelCase : Optional[int]="gelu", _UpperCAmelCase : int=0.1, _UpperCAmelCase : List[str]=0.1, _UpperCAmelCase : List[str]=1_0, _UpperCAmelCase : List[Any]=0.02, _UpperCAmelCase : List[Any]=None, ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = parent SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : List[str] = is_training SCREAMING_SNAKE_CASE__ : Any = use_labels SCREAMING_SNAKE_CASE__ : List[Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : str = num_attention_heads SCREAMING_SNAKE_CASE__ : str = intermediate_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : Any = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : str = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : str = num_patches + 1 def A_ ( self : Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) 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__ : int = self.get_config() return config, pixel_values, labels def A_ ( self : int ) -> Tuple: """simple docstring""" return ViTMSNConfig( 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, initializer_range=self.initializer_range, ) def A_ ( self : Dict, _UpperCAmelCase : List[str], _UpperCAmelCase : List[Any], _UpperCAmelCase : List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = ViTMSNModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def A_ ( self : int, _UpperCAmelCase : Dict, _UpperCAmelCase : List[Any], _UpperCAmelCase : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = ViTMSNForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : int = model(_UpperCAmelCase, labels=_UpperCAmelCase ) print("Pixel and labels shape: {pixel_values.shape}, {labels.shape}" ) print("Labels: {labels}" ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ViTMSNForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[str] = model(_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) def A_ ( self : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Any = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCamelCase (__lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" UpperCAmelCase_ = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () UpperCAmelCase_ = ( {"feature-extraction": ViTMSNModel, "image-classification": ViTMSNForImageClassification} if is_torch_available() else {} ) UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False UpperCAmelCase_ = False def A_ ( self : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ViTMSNModelTester(self ) SCREAMING_SNAKE_CASE__ : str = ConfigTester(self, config_class=_UpperCAmelCase, has_text_modality=_UpperCAmelCase, hidden_size=3_7 ) def A_ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="ViTMSN does not use inputs_embeds" ) def A_ ( self : List[str] ) -> Tuple: """simple docstring""" pass def A_ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] = model_class(_UpperCAmelCase ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) SCREAMING_SNAKE_CASE__ : List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_UpperCAmelCase, nn.Linear ) ) def A_ ( self : List[Any] ) -> Dict: """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__ : int = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : str = ["pixel_values"] self.assertListEqual(arg_names[:1], _UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @slow def A_ ( self : Optional[int] ) -> List[Any]: """simple docstring""" for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = ViTMSNModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def _a ( ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class lowerCamelCase (unittest.TestCase ): """simple docstring""" @cached_property def A_ ( self : List[str] ) -> Optional[Any]: """simple docstring""" return ViTImageProcessor.from_pretrained("facebook/vit-msn-small" ) if is_vision_available() else None @slow def A_ ( self : Any ) -> Dict: """simple docstring""" torch.manual_seed(2 ) SCREAMING_SNAKE_CASE__ : List[str] = ViTMSNForImageClassification.from_pretrained("facebook/vit-msn-small" ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Dict = image_processor(images=_UpperCAmelCase, return_tensors="pt" ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Dict = model(**_UpperCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE__ : Tuple = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape, _UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3], _UpperCAmelCase, atol=1E-4 ) )
191
1
'''simple docstring''' import gc import unittest from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline from transformers.pipelines import PipelineException from transformers.testing_utils import ( is_pipeline_test, is_torch_available, nested_simplify, require_tf, require_torch, require_torch_gpu, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class __UpperCamelCase ( unittest.TestCase ): lowercase : Optional[int] =MODEL_FOR_MASKED_LM_MAPPING lowercase : Any =TF_MODEL_FOR_MASKED_LM_MAPPING def lowercase__ ( self ): """simple docstring""" super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() if is_torch_available(): import torch torch.cuda.empty_cache() @require_tf def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =pipeline(task='''fill-mask''', model='''sshleifer/tiny-distilroberta-base''', top_k=2, framework='''tf''' ) lowerCamelCase_ =unmasker('''My name is <mask>''' ) self.assertEqual( nested_simplify(lowerCAmelCase, decimals=6 ), [ {'''sequence''': '''My name is grouped''', '''score''': 2.1e-05, '''token''': 38_015, '''token_str''': ''' grouped'''}, {'''sequence''': '''My name is accuser''', '''score''': 2.1e-05, '''token''': 25_506, '''token_str''': ''' accuser'''}, ], ) lowerCamelCase_ =unmasker('''The largest city in France is <mask>''' ) self.assertEqual( nested_simplify(lowerCAmelCase, decimals=6 ), [ { '''sequence''': '''The largest city in France is grouped''', '''score''': 2.1e-05, '''token''': 38_015, '''token_str''': ''' grouped''', }, { '''sequence''': '''The largest city in France is accuser''', '''score''': 2.1e-05, '''token''': 25_506, '''token_str''': ''' accuser''', }, ], ) lowerCamelCase_ =unmasker('''My name is <mask>''', targets=[''' Patrick''', ''' Clara''', ''' Teven'''], top_k=3 ) self.assertEqual( nested_simplify(lowerCAmelCase, decimals=6 ), [ {'''sequence''': '''My name is Clara''', '''score''': 2e-05, '''token''': 13_606, '''token_str''': ''' Clara'''}, {'''sequence''': '''My name is Patrick''', '''score''': 2e-05, '''token''': 3_499, '''token_str''': ''' Patrick'''}, {'''sequence''': '''My name is Te''', '''score''': 1.9e-05, '''token''': 2_941, '''token_str''': ''' Te'''}, ], ) @require_torch def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =pipeline(task='''fill-mask''', model='''sshleifer/tiny-distilroberta-base''', top_k=2, framework='''pt''' ) lowerCamelCase_ =unmasker('''My name is <mask>''' ) self.assertEqual( nested_simplify(lowerCAmelCase, decimals=6 ), [ {'''sequence''': '''My name is Maul''', '''score''': 2.2e-05, '''token''': 35_676, '''token_str''': ''' Maul'''}, {'''sequence''': '''My name isELS''', '''score''': 2.2e-05, '''token''': 16_416, '''token_str''': '''ELS'''}, ], ) lowerCamelCase_ =unmasker('''The largest city in France is <mask>''' ) self.assertEqual( nested_simplify(lowerCAmelCase, decimals=6 ), [ { '''sequence''': '''The largest city in France is Maul''', '''score''': 2.2e-05, '''token''': 35_676, '''token_str''': ''' Maul''', }, {'''sequence''': '''The largest city in France isELS''', '''score''': 2.2e-05, '''token''': 16_416, '''token_str''': '''ELS'''}, ], ) lowerCamelCase_ =unmasker('''My name is <mask>''', targets=[''' Patrick''', ''' Clara''', ''' Teven'''], top_k=3 ) self.assertEqual( nested_simplify(lowerCAmelCase, decimals=6 ), [ {'''sequence''': '''My name is Patrick''', '''score''': 2.1e-05, '''token''': 3_499, '''token_str''': ''' Patrick'''}, {'''sequence''': '''My name is Te''', '''score''': 2e-05, '''token''': 2_941, '''token_str''': ''' Te'''}, {'''sequence''': '''My name is Clara''', '''score''': 2e-05, '''token''': 13_606, '''token_str''': ''' Clara'''}, ], ) lowerCamelCase_ =unmasker('''My name is <mask> <mask>''', top_k=2 ) self.assertEqual( nested_simplify(lowerCAmelCase, decimals=6 ), [ [ { '''score''': 2.2e-05, '''token''': 35_676, '''token_str''': ''' Maul''', '''sequence''': '''<s>My name is Maul<mask></s>''', }, {'''score''': 2.2e-05, '''token''': 16_416, '''token_str''': '''ELS''', '''sequence''': '''<s>My name isELS<mask></s>'''}, ], [ { '''score''': 2.2e-05, '''token''': 35_676, '''token_str''': ''' Maul''', '''sequence''': '''<s>My name is<mask> Maul</s>''', }, {'''score''': 2.2e-05, '''token''': 16_416, '''token_str''': '''ELS''', '''sequence''': '''<s>My name is<mask>ELS</s>'''}, ], ], ) @require_torch_gpu def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =pipeline('''fill-mask''', model='''hf-internal-testing/tiny-random-distilbert''', device=0, framework='''pt''' ) # convert model to fp16 pipe.model.half() lowerCamelCase_ =pipe('''Paris is the [MASK] of France.''' ) # We actually don't care about the result, we just want to make sure # it works, meaning the float16 tensor got casted back to float32 # for postprocessing. self.assertIsInstance(lowerCAmelCase, lowerCAmelCase ) @slow @require_torch def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =pipeline(task='''fill-mask''', model='''distilroberta-base''', top_k=2, framework='''pt''' ) self.run_large_test(lowerCAmelCase ) @slow @require_tf def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =pipeline(task='''fill-mask''', model='''distilroberta-base''', top_k=2, framework='''tf''' ) self.run_large_test(lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =unmasker('''My name is <mask>''' ) self.assertEqual( nested_simplify(lowerCAmelCase ), [ {'''sequence''': '''My name is John''', '''score''': 0.0_0_8, '''token''': 610, '''token_str''': ''' John'''}, {'''sequence''': '''My name is Chris''', '''score''': 0.0_0_7, '''token''': 1_573, '''token_str''': ''' Chris'''}, ], ) lowerCamelCase_ =unmasker('''The largest city in France is <mask>''' ) self.assertEqual( nested_simplify(lowerCAmelCase ), [ { '''sequence''': '''The largest city in France is Paris''', '''score''': 0.2_5_1, '''token''': 2_201, '''token_str''': ''' Paris''', }, { '''sequence''': '''The largest city in France is Lyon''', '''score''': 0.2_1_4, '''token''': 12_790, '''token_str''': ''' Lyon''', }, ], ) lowerCamelCase_ =unmasker('''My name is <mask>''', targets=[''' Patrick''', ''' Clara''', ''' Teven'''], top_k=3 ) self.assertEqual( nested_simplify(lowerCAmelCase ), [ {'''sequence''': '''My name is Patrick''', '''score''': 0.0_0_5, '''token''': 3_499, '''token_str''': ''' Patrick'''}, {'''sequence''': '''My name is Clara''', '''score''': 0.0_0_0, '''token''': 13_606, '''token_str''': ''' Clara'''}, {'''sequence''': '''My name is Te''', '''score''': 0.0_0_0, '''token''': 2_941, '''token_str''': ''' Te'''}, ], ) @require_torch def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =pipeline(task='''fill-mask''', model='''sshleifer/tiny-distilroberta-base''', framework='''pt''' ) lowerCamelCase_ =None lowerCamelCase_ =None self.run_pipeline_test(lowerCAmelCase, [] ) @require_tf def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =pipeline(task='''fill-mask''', model='''sshleifer/tiny-distilroberta-base''', framework='''tf''' ) lowerCamelCase_ =None lowerCamelCase_ =None self.run_pipeline_test(lowerCAmelCase, [] ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" if tokenizer is None or tokenizer.mask_token_id is None: self.skipTest('''The provided tokenizer has no mask token, (probably reformer or wav2vec2)''' ) lowerCamelCase_ =FillMaskPipeline(model=lowerCAmelCase, tokenizer=lowerCAmelCase ) lowerCamelCase_ =[ f'''This is another {tokenizer.mask_token} test''', ] return fill_masker, examples def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =fill_masker.tokenizer lowerCamelCase_ =fill_masker.model lowerCamelCase_ =fill_masker( f'''This is a {tokenizer.mask_token}''', ) self.assertEqual( lowerCAmelCase, [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], ) lowerCamelCase_ =fill_masker([f'''This is a {tokenizer.mask_token}'''] ) self.assertEqual( lowerCAmelCase, [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], ) lowerCamelCase_ =fill_masker([f'''This is a {tokenizer.mask_token}''', f'''Another {tokenizer.mask_token} great test.'''] ) self.assertEqual( lowerCAmelCase, [ [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], ], ) with self.assertRaises(lowerCAmelCase ): fill_masker([None] ) # No mask_token is not supported with self.assertRaises(lowerCAmelCase ): fill_masker('''This is''' ) self.run_test_top_k(lowerCAmelCase, lowerCAmelCase ) self.run_test_targets(lowerCAmelCase, lowerCAmelCase ) self.run_test_top_k_targets(lowerCAmelCase, lowerCAmelCase ) self.fill_mask_with_duplicate_targets_and_top_k(lowerCAmelCase, lowerCAmelCase ) self.fill_mask_with_multiple_masks(lowerCAmelCase, lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =tokenizer.get_vocab() lowerCamelCase_ =sorted(vocab.keys() )[:2] # Pipeline argument lowerCamelCase_ =FillMaskPipeline(model=lowerCAmelCase, tokenizer=lowerCAmelCase, targets=lowerCAmelCase ) lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''' ) self.assertEqual( lowerCAmelCase, [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], ) lowerCamelCase_ ={vocab[el] for el in targets} self.assertEqual({el['''token'''] for el in outputs}, lowerCAmelCase ) lowerCamelCase_ =[tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el['''token_str'''] for el in outputs}, set(lowerCAmelCase ) ) # Call argument lowerCamelCase_ =FillMaskPipeline(model=lowerCAmelCase, tokenizer=lowerCAmelCase ) lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''', targets=lowerCAmelCase ) self.assertEqual( lowerCAmelCase, [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], ) lowerCamelCase_ ={vocab[el] for el in targets} self.assertEqual({el['''token'''] for el in outputs}, lowerCAmelCase ) lowerCamelCase_ =[tokenizer.decode([x] ) for x in target_ids] self.assertEqual({el['''token_str'''] for el in outputs}, set(lowerCAmelCase ) ) # Score equivalence lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''', targets=lowerCAmelCase ) lowerCamelCase_ =[top_mask['''token_str'''] for top_mask in outputs] lowerCamelCase_ =[top_mask['''score'''] for top_mask in outputs] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(lowerCAmelCase ) == set(lowerCAmelCase ): lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''', targets=lowerCAmelCase ) lowerCamelCase_ =[top_mask['''score'''] for top_mask in unmasked_targets] self.assertEqual(nested_simplify(lowerCAmelCase ), nested_simplify(lowerCAmelCase ) ) # Raises with invalid with self.assertRaises(lowerCAmelCase ): lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''', targets=[] ) # For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised if "" not in tokenizer.get_vocab(): with self.assertRaises(lowerCAmelCase ): lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''', targets=[''''''] ) with self.assertRaises(lowerCAmelCase ): lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''', targets='''''' ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =FillMaskPipeline(model=lowerCAmelCase, tokenizer=lowerCAmelCase, top_k=2 ) lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''' ) self.assertEqual( lowerCAmelCase, [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], ) lowerCamelCase_ =FillMaskPipeline(model=lowerCAmelCase, tokenizer=lowerCAmelCase ) lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''', top_k=2 ) self.assertEqual( lowerCAmelCase, [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], ) self.assertEqual(nested_simplify(lowerCAmelCase ), nested_simplify(lowerCAmelCase ) ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =tokenizer.get_vocab() lowerCamelCase_ =FillMaskPipeline(model=lowerCAmelCase, tokenizer=lowerCAmelCase ) # top_k=2, ntargets=3 lowerCamelCase_ =sorted(vocab.keys() )[:3] lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''', top_k=2, targets=lowerCAmelCase ) # If we use the most probably targets, and filter differently, we should still # have the same results lowerCamelCase_ =[el['''token_str'''] for el in sorted(lowerCAmelCase, key=lambda lowerCAmelCase : x["score"], reverse=lowerCAmelCase )] # For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`. if set(lowerCAmelCase ).issubset(lowerCAmelCase ): lowerCamelCase_ =fill_masker(f'''This is a {tokenizer.mask_token}''', top_k=3, targets=lowerCAmelCase ) # They should yield exactly the same result self.assertEqual(nested_simplify(lowerCAmelCase ), nested_simplify(lowerCAmelCase ) ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =FillMaskPipeline(model=lowerCAmelCase, tokenizer=lowerCAmelCase ) lowerCamelCase_ =tokenizer.get_vocab() # String duplicates + id duplicates lowerCamelCase_ =sorted(vocab.keys() )[:3] lowerCamelCase_ =[targets[0], targets[1], targets[0], targets[2], targets[1]] lowerCamelCase_ =fill_masker(f'''My name is {tokenizer.mask_token}''', targets=lowerCAmelCase, top_k=10 ) # The target list contains duplicates, so we can't output more # than them self.assertEqual(len(lowerCAmelCase ), 3 ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =FillMaskPipeline(model=lowerCAmelCase, tokenizer=lowerCAmelCase ) lowerCamelCase_ =fill_masker( f'''This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}''', top_k=2 ) self.assertEqual( lowerCAmelCase, [ [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], [ {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, {'''sequence''': ANY(lowerCAmelCase ), '''score''': ANY(lowerCAmelCase ), '''token''': ANY(lowerCAmelCase ), '''token_str''': ANY(lowerCAmelCase )}, ], ], )
75
"""simple docstring""" def __lowercase ( snake_case_ : dict ) ->set: '''simple docstring''' __A : List[str] = set() # edges = list of graph's edges __A : Optional[int] = get_edges(snake_case_ ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: __A , __A : str = edges.pop() chosen_vertices.add(snake_case_ ) chosen_vertices.add(snake_case_ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(snake_case_ ) return chosen_vertices def __lowercase ( snake_case_ : dict ) ->set: '''simple docstring''' __A : Tuple = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
179
0
import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a__ ( UpperCamelCase__ , unittest.TestCase ): a : Optional[Any] = LxmertTokenizer a : Dict = LxmertTokenizerFast a : Dict = True a : Dict = True def lowerCAmelCase_ ( self ) -> List[str]: '''simple docstring''' super().setUp() a = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def lowerCAmelCase_ ( self , A ) -> Optional[Any]: '''simple docstring''' a = "UNwant\u00E9d,running" a = "unwanted, running" return input_text, output_text def lowerCAmelCase_ ( self ) -> Union[str, Any]: '''simple docstring''' a = self.tokenizer_class(self.vocab_file ) a = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(A , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) , [7, 4, 5, 10, 8, 9] ) def lowerCAmelCase_ ( self ) -> int: '''simple docstring''' if not self.test_rust_tokenizer: return a = self.get_tokenizer() a = self.get_rust_tokenizer() a = "I was born in 92000, and this is falsé." a = tokenizer.tokenize(A ) a = rust_tokenizer.tokenize(A ) self.assertListEqual(A , A ) a = tokenizer.encode(A , add_special_tokens=A ) a = rust_tokenizer.encode(A , add_special_tokens=A ) self.assertListEqual(A , A ) a = self.get_rust_tokenizer() a = tokenizer.encode(A ) a = rust_tokenizer.encode(A ) self.assertListEqual(A , A )
180
from math import isqrt def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> bool: return all(number % divisor != 0 for divisor in range(2 , isqrt(__UpperCamelCase) + 1)) def SCREAMING_SNAKE_CASE ( __UpperCamelCase = 10**6) -> int: a = 0 a = 1 a = 7 while prime_candidate < max_prime: primes_count += is_prime(__UpperCamelCase) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F'{solution() = }')
180
1
'''simple docstring''' import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : str , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Optional[int]=1_0_0 , _lowerCAmelCase : List[str]=1_3 , _lowerCAmelCase : List[str]=3_0 , _lowerCAmelCase : Optional[int]=2 , _lowerCAmelCase : Optional[int]=3 , _lowerCAmelCase : List[Any]=True , _lowerCAmelCase : Optional[int]=True , _lowerCAmelCase : List[Any]=3_2 , _lowerCAmelCase : Any=5 , _lowerCAmelCase : Optional[int]=4 , _lowerCAmelCase : Dict=3_7 , _lowerCAmelCase : Any="gelu" , _lowerCAmelCase : Optional[int]=0.1 , _lowerCAmelCase : Optional[Any]=0.1 , _lowerCAmelCase : Dict=1_0 , _lowerCAmelCase : Dict=0.02 , _lowerCAmelCase : Any=3 , ): '''simple docstring''' __lowercase =parent __lowercase =vocab_size __lowercase =batch_size __lowercase =image_size __lowercase =patch_size __lowercase =num_channels __lowercase =is_training __lowercase =use_labels __lowercase =hidden_size __lowercase =num_hidden_layers __lowercase =num_attention_heads __lowercase =intermediate_size __lowercase =hidden_act __lowercase =hidden_dropout_prob __lowercase =attention_probs_dropout_prob __lowercase =type_sequence_label_size __lowercase =initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __lowercase =(image_size // patch_size) ** 2 __lowercase =num_patches + 1 def __lowerCamelCase ( self : Optional[int]): '''simple docstring''' __lowercase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __lowercase =None if self.use_labels: __lowercase =ids_tensor([self.batch_size] , self.type_sequence_label_size) __lowercase =BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowerCAmelCase , initializer_range=self.initializer_range , ) return config, pixel_values, labels def __lowerCamelCase ( self : Optional[Any] , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : List[Any]): '''simple docstring''' __lowercase =FlaxBeitModel(config=_lowerCAmelCase) __lowercase =model(_lowerCAmelCase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def __lowerCamelCase ( self : str , _lowerCAmelCase : Dict , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Any): '''simple docstring''' __lowercase =FlaxBeitForMaskedImageModeling(config=_lowerCAmelCase) __lowercase =model(_lowerCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size)) def __lowerCamelCase ( self : Tuple , _lowerCAmelCase : Any , _lowerCAmelCase : Any , _lowerCAmelCase : Tuple): '''simple docstring''' __lowercase =self.type_sequence_label_size __lowercase =FlaxBeitForImageClassification(config=_lowerCAmelCase) __lowercase =model(_lowerCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images __lowercase =1 __lowercase =FlaxBeitForImageClassification(_lowerCAmelCase) __lowercase =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) __lowercase =model(_lowerCAmelCase) def __lowerCamelCase ( self : Optional[Any]): '''simple docstring''' __lowercase =self.prepare_config_and_inputs() ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) =config_and_inputs __lowercase ={'pixel_values': pixel_values} return config, inputs_dict @require_flax class _UpperCamelCase ( A , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ = ( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def __lowerCamelCase ( self : Optional[Any]): '''simple docstring''' __lowercase =FlaxBeitModelTester(self) __lowercase =ConfigTester(self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase , hidden_size=3_7) def __lowerCamelCase ( self : Optional[int]): '''simple docstring''' self.config_tester.run_common_tests() def __lowerCamelCase ( self : Tuple): '''simple docstring''' __lowercase , __lowercase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowercase =model_class(_lowerCAmelCase) __lowercase =inspect.signature(model.__call__) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowercase =[*signature.parameters.keys()] __lowercase =['pixel_values'] self.assertListEqual(arg_names[:1] , _lowerCAmelCase) def __lowerCamelCase ( self : Union[str, Any]): '''simple docstring''' __lowercase , __lowercase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): __lowercase =self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase) __lowercase =model_class(_lowerCAmelCase) @jax.jit def model_jitted(_lowerCAmelCase : Dict , **_lowerCAmelCase : Tuple): return model(pixel_values=_lowerCAmelCase , **_lowerCAmelCase) with self.subTest('JIT Enabled'): __lowercase =model_jitted(**_lowerCAmelCase).to_tuple() with self.subTest('JIT Disabled'): with jax.disable_jit(): __lowercase =model_jitted(**_lowerCAmelCase).to_tuple() self.assertEqual(len(_lowerCAmelCase) , len(_lowerCAmelCase)) for jitted_output, output in zip(_lowerCAmelCase , _lowerCAmelCase): self.assertEqual(jitted_output.shape , output.shape) def __lowerCamelCase ( self : Union[str, Any]): '''simple docstring''' __lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase) def __lowerCamelCase ( self : str): '''simple docstring''' __lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCAmelCase) def __lowerCamelCase ( self : Dict): '''simple docstring''' __lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase) @slow def __lowerCamelCase ( self : Dict): '''simple docstring''' for model_class_name in self.all_model_classes: __lowercase =model_class_name.from_pretrained('microsoft/beit-base-patch16-224') __lowercase =model(np.ones((1, 3, 2_2_4, 2_2_4))) self.assertIsNotNone(_lowerCAmelCase) def _A ( ): """simple docstring""" __lowercase =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @require_flax class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __lowerCamelCase ( self : Dict): '''simple docstring''' return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224') if is_vision_available() else None @slow def __lowerCamelCase ( self : Optional[Any]): '''simple docstring''' __lowercase =FlaxBeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k') __lowercase =self.default_image_processor __lowercase =prepare_img() __lowercase =image_processor(images=_lowerCAmelCase , return_tensors='np').pixel_values # prepare bool_masked_pos __lowercase =np.ones((1, 1_9_6) , dtype=_lowerCAmelCase) # forward pass __lowercase =model(pixel_values=_lowerCAmelCase , bool_masked_pos=_lowerCAmelCase) __lowercase =outputs.logits # verify the logits __lowercase =(1, 1_9_6, 8_1_9_2) self.assertEqual(logits.shape , _lowerCAmelCase) __lowercase =np.array( [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , _lowerCAmelCase , atol=1e-2)) @slow def __lowerCamelCase ( self : Any): '''simple docstring''' __lowercase =FlaxBeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224') __lowercase =self.default_image_processor __lowercase =prepare_img() __lowercase =image_processor(images=_lowerCAmelCase , return_tensors='np') # forward pass __lowercase =model(**_lowerCAmelCase) __lowercase =outputs.logits # verify the logits __lowercase =(1, 1_0_0_0) self.assertEqual(logits.shape , _lowerCAmelCase) __lowercase =np.array([-1.2385, -1.0987, -1.0108]) self.assertTrue(np.allclose(logits[0, :3] , _lowerCAmelCase , atol=1e-4)) __lowercase =2_8_1 self.assertEqual(logits.argmax(-1).item() , _lowerCAmelCase) @slow def __lowerCamelCase ( self : int): '''simple docstring''' __lowercase =FlaxBeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k') __lowercase =self.default_image_processor __lowercase =prepare_img() __lowercase =image_processor(images=_lowerCAmelCase , return_tensors='np') # forward pass __lowercase =model(**_lowerCAmelCase) __lowercase =outputs.logits # verify the logits __lowercase =(1, 2_1_8_4_1) self.assertEqual(logits.shape , _lowerCAmelCase) __lowercase =np.array([1.6881, -0.2787, 0.5901]) self.assertTrue(np.allclose(logits[0, :3] , _lowerCAmelCase , atol=1e-4)) __lowercase =2_3_9_6 self.assertEqual(logits.argmax(-1).item() , _lowerCAmelCase)
166
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input lowerCamelCase = """Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine""" def _A ( ): """simple docstring""" __lowercase =_ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: __lowercase =get_sagemaker_input() else: __lowercase =get_cluster_input() return config def _A ( _lowerCAmelCase=None ): """simple docstring""" if subparsers is not None: __lowercase =subparsers.add_parser('config' , description=_lowerCAmelCase ) else: __lowercase =argparse.ArgumentParser('Accelerate config command' , description=_lowerCAmelCase ) parser.add_argument( '--config_file' , default=_lowerCAmelCase , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=_lowerCAmelCase ) return parser def _A ( _lowerCAmelCase ): """simple docstring""" __lowercase =get_user_input() if args.config_file is not None: __lowercase =args.config_file else: if not os.path.isdir(_lowerCAmelCase ): os.makedirs(_lowerCAmelCase ) __lowercase =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(_lowerCAmelCase ) else: config.to_yaml_file(_lowerCAmelCase ) print(f"""accelerate configuration saved at {config_file}""" ) def _A ( ): """simple docstring""" __lowercase =config_command_parser() __lowercase =parser.parse_args() config_command(_lowerCAmelCase ) if __name__ == "__main__": main()
166
1
'''simple docstring''' import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def SCREAMING_SNAKE_CASE_ (UpperCamelCase=None , UpperCamelCase=None ) -> Any: return field(default_factory=lambda: default , metadata=UpperCamelCase ) @dataclass class _lowercase : a = field( metadata={"""help""": """The csv file to plot."""} , ) a = field( default=_lowercase , metadata={"""help""": """Whether to plot along batch size or sequence length. Defaults to sequence length."""} , ) a = field( default=_lowercase , metadata={"""help""": """Whether the csv file has time results or memory results. Defaults to memory results."""} , ) a = field( default=_lowercase , metadata={"""help""": """Disable logarithmic scale when plotting"""} , ) a = field( default=_lowercase , metadata={ """help""": """Whether the csv file has training results or inference results. Defaults to inference results.""" } , ) a = field( default=_lowercase , metadata={"""help""": """Filename under which the plot will be saved. If unused no plot is saved."""} , ) a = list_field( default=_lowercase , metadata={"""help""": """List of model names that are used instead of the ones in the csv file."""} ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Dict: try: int(UpperCamelCase ) return True except ValueError: return False def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> int: try: float(UpperCamelCase ) return True except ValueError: return False class _lowercase : def __init__( self: Tuple , UpperCamelCase__: str ): lowerCamelCase__ : int = args lowerCamelCase__ : Optional[int] = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline="""""" ) as csv_file: lowerCamelCase__ : str = csv.DictReader(UpperCamelCase__ ) for row in reader: lowerCamelCase__ : Optional[int] = row["""model"""] self.result_dict[model_name]["bsz"].append(int(row["""batch_size"""] ) ) self.result_dict[model_name]["seq_len"].append(int(row["""sequence_length"""] ) ) if can_convert_to_int(row["""result"""] ): # value is not None lowerCamelCase__ : Tuple = int(row["""result"""] ) elif can_convert_to_float(row["""result"""] ): # value is not None lowerCamelCase__ : Any = float(row["""result"""] ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ , lowerCamelCase__ : Tuple = plt.subplots() lowerCamelCase__ : Any = """Time usage""" if self.args.is_time else """Memory usage""" lowerCamelCase__ : List[str] = title_str + """ for training""" if self.args.is_train else title_str + """ for inference""" if not self.args.no_log_scale: # set logarithm scales ax.set_xscale("""log""" ) ax.set_yscale("""log""" ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): lowerCamelCase__ : Any = sorted(set(self.result_dict[model_name]["""bsz"""] ) ) lowerCamelCase__ : int = sorted(set(self.result_dict[model_name]["""seq_len"""] ) ) lowerCamelCase__ : Any = self.result_dict[model_name]["""result"""] ((lowerCamelCase__) , (lowerCamelCase__)) : Dict = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) lowerCamelCase__ : Any = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: lowerCamelCase__ : int = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=UpperCamelCase__ , ) else: lowerCamelCase__ : List[Any] = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((lowerCamelCase__) , (lowerCamelCase__)) : List[str] = ( ("""batch_size""", """len""") if self.args.plot_along_batch else ("""in #tokens""", """bsz""") ) lowerCamelCase__ : int = np.asarray(UpperCamelCase__ , UpperCamelCase__ )[: len(UpperCamelCase__ )] plt.scatter( UpperCamelCase__ , UpperCamelCase__ , label=F'''{label_model_name} - {inner_loop_label}: {inner_loop_value}''' ) plt.plot(UpperCamelCase__ , UpperCamelCase__ , """--""" ) title_str += F''' {label_model_name} vs.''' lowerCamelCase__ : Any = title_str[:-4] lowerCamelCase__ : Optional[int] = """Time in s""" if self.args.is_time else """Memory in MB""" # plot plt.title(UpperCamelCase__ ) plt.xlabel(UpperCamelCase__ ) plt.ylabel(UpperCamelCase__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def SCREAMING_SNAKE_CASE_ () -> str: lowerCamelCase__ : str = HfArgumentParser(UpperCamelCase ) lowerCamelCase__ : str = parser.parse_args_into_dataclasses()[0] lowerCamelCase__ : Any = Plot(args=UpperCamelCase ) plot.plot() if __name__ == "__main__": main()
129
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging _A : Optional[Any] =logging.get_logger(__name__) _A : List[str] ={ '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json''', # See all Marian models at https://huggingface.co/models?filter=marian } class _lowercase ( _lowercase ): a = """marian""" a = ["""past_key_values"""] a = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self: Tuple , UpperCamelCase__: Optional[Any]=58_101 , UpperCamelCase__: Optional[int]=None , UpperCamelCase__: Union[str, Any]=1_024 , UpperCamelCase__: Any=12 , UpperCamelCase__: Optional[int]=4_096 , UpperCamelCase__: Tuple=16 , UpperCamelCase__: Dict=12 , UpperCamelCase__: Optional[Any]=4_096 , UpperCamelCase__: Any=16 , UpperCamelCase__: List[str]=0.0 , UpperCamelCase__: Tuple=0.0 , UpperCamelCase__: str=True , UpperCamelCase__: Optional[int]=True , UpperCamelCase__: Optional[int]="gelu" , UpperCamelCase__: Union[str, Any]=1_024 , UpperCamelCase__: Optional[int]=0.1 , UpperCamelCase__: Optional[Any]=0.0 , UpperCamelCase__: Optional[Any]=0.0 , UpperCamelCase__: Optional[int]=0.02 , UpperCamelCase__: str=58_100 , UpperCamelCase__: Tuple=False , UpperCamelCase__: Optional[Any]=58_100 , UpperCamelCase__: int=0 , UpperCamelCase__: Union[str, Any]=0 , UpperCamelCase__: List[str]=True , **UpperCamelCase__: str , ): lowerCamelCase__ : int = vocab_size lowerCamelCase__ : Tuple = decoder_vocab_size or vocab_size lowerCamelCase__ : List[str] = max_position_embeddings lowerCamelCase__ : Optional[Any] = d_model lowerCamelCase__ : int = encoder_ffn_dim lowerCamelCase__ : Union[str, Any] = encoder_layers lowerCamelCase__ : Dict = encoder_attention_heads lowerCamelCase__ : Optional[int] = decoder_ffn_dim lowerCamelCase__ : List[str] = decoder_layers lowerCamelCase__ : Dict = decoder_attention_heads lowerCamelCase__ : int = dropout lowerCamelCase__ : str = attention_dropout lowerCamelCase__ : Dict = activation_dropout lowerCamelCase__ : List[str] = activation_function lowerCamelCase__ : Union[str, Any] = init_std lowerCamelCase__ : str = encoder_layerdrop lowerCamelCase__ : Any = decoder_layerdrop lowerCamelCase__ : List[str] = use_cache lowerCamelCase__ : List[str] = encoder_layers lowerCamelCase__ : int = scale_embedding # scale factor will be sqrt(d_model) if True lowerCamelCase__ : str = share_encoder_decoder_embeddings super().__init__( pad_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , forced_eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) class _lowercase ( _lowercase ): @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs def lowerCamelCase_ ( self: Union[str, Any] ): if self.task in ["default", "seq2seq-lm"]: lowerCamelCase__ : List[str] = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: lowerCamelCase__ : Dict = {0: """batch"""} lowerCamelCase__ : Union[str, Any] = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: lowerCamelCase__ : Any = {0: """batch""", 1: """decoder_sequence"""} lowerCamelCase__ : Dict = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(UpperCamelCase__ , direction="""inputs""" ) elif self.task == "causal-lm": # TODO: figure this case out. lowerCamelCase__ : Union[str, Any] = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: lowerCamelCase__ , lowerCamelCase__ : Tuple = self.num_layers for i in range(UpperCamelCase__ ): lowerCamelCase__ : Union[str, Any] = {0: """batch""", 2: """past_sequence + sequence"""} lowerCamelCase__ : List[str] = {0: """batch""", 2: """past_sequence + sequence"""} else: lowerCamelCase__ : int = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}), ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}), ] ) return common_inputs @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs def lowerCamelCase_ ( self: Optional[Any] ): if self.task in ["default", "seq2seq-lm"]: lowerCamelCase__ : Dict = super().outputs else: lowerCamelCase__ : Any = super(UpperCamelCase__ , self ).outputs if self.use_past: lowerCamelCase__ , lowerCamelCase__ : str = self.num_layers for i in range(UpperCamelCase__ ): lowerCamelCase__ : Tuple = {0: """batch""", 2: """past_sequence + sequence"""} lowerCamelCase__ : Union[str, Any] = {0: """batch""", 2: """past_sequence + sequence"""} return common_outputs def lowerCamelCase_ ( self: str , UpperCamelCase__: PreTrainedTokenizer , UpperCamelCase__: int = -1 , UpperCamelCase__: int = -1 , UpperCamelCase__: bool = False , UpperCamelCase__: Optional[TensorType] = None , ): lowerCamelCase__ : Union[str, Any] = self._generate_dummy_inputs_for_encoder_and_decoder( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Generate decoder inputs lowerCamelCase__ : Any = seq_length if not self.use_past else 1 lowerCamelCase__ : Optional[Any] = self._generate_dummy_inputs_for_encoder_and_decoder( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : str = {F'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()} lowerCamelCase__ : Optional[int] = dict(**UpperCamelCase__ , **UpperCamelCase__ ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = common_inputs["""input_ids"""].shape lowerCamelCase__ : Tuple = common_inputs["""decoder_input_ids"""].shape[1] lowerCamelCase__ , lowerCamelCase__ : List[str] = self.num_attention_heads lowerCamelCase__ : Any = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) lowerCamelCase__ : Tuple = decoder_seq_length + 3 lowerCamelCase__ : int = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) lowerCamelCase__ : Optional[int] = torch.cat( [common_inputs["""decoder_attention_mask"""], torch.ones(UpperCamelCase__ , UpperCamelCase__ )] , dim=1 ) lowerCamelCase__ : Any = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered lowerCamelCase__ , lowerCamelCase__ : Any = self.num_layers lowerCamelCase__ : str = min(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase__ : str = max(UpperCamelCase__ , UpperCamelCase__ ) - min_num_layers lowerCamelCase__ : int = """encoder""" if num_encoder_layers > num_decoder_layers else """decoder""" for _ in range(UpperCamelCase__ ): common_inputs["past_key_values"].append( ( torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ ), ) ) # TODO: test this. lowerCamelCase__ : Union[str, Any] = encoder_shape if remaining_side_name == """encoder""" else decoder_shape for _ in range(UpperCamelCase__ , UpperCamelCase__ ): common_inputs["past_key_values"].append((torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ )) ) return common_inputs def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: PreTrainedTokenizer , UpperCamelCase__: int = -1 , UpperCamelCase__: int = -1 , UpperCamelCase__: bool = False , UpperCamelCase__: Optional[TensorType] = None , ): lowerCamelCase__ : Any = self._generate_dummy_inputs_for_encoder_and_decoder( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch lowerCamelCase__ , lowerCamelCase__ : Any = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values lowerCamelCase__ : Optional[Any] = seqlen + 2 lowerCamelCase__ , lowerCamelCase__ : Dict = self.num_layers lowerCamelCase__ , lowerCamelCase__ : Dict = self.num_attention_heads lowerCamelCase__ : Optional[Any] = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) lowerCamelCase__ : Optional[Any] = common_inputs["""attention_mask"""].dtype lowerCamelCase__ : int = torch.cat( [common_inputs["""attention_mask"""], torch.ones(UpperCamelCase__ , UpperCamelCase__ , dtype=UpperCamelCase__ )] , dim=1 ) lowerCamelCase__ : int = [ (torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ )) for _ in range(UpperCamelCase__ ) ] return common_inputs def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: PreTrainedTokenizer , UpperCamelCase__: int = -1 , UpperCamelCase__: int = -1 , UpperCamelCase__: bool = False , UpperCamelCase__: Optional[TensorType] = None , ): # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX lowerCamelCase__ : List[Any] = compute_effective_axis_dimension( UpperCamelCase__ , 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 lowerCamelCase__ : Union[str, Any] = tokenizer.num_special_tokens_to_add(UpperCamelCase__ ) lowerCamelCase__ : Any = compute_effective_axis_dimension( UpperCamelCase__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCamelCase__ ) # Generate dummy inputs according to compute batch and sequence lowerCamelCase__ : Union[str, Any] = [""" """.join([tokenizer.unk_token] ) * seq_length] * batch_size lowerCamelCase__ : str = dict(tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ ) ) return common_inputs def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: PreTrainedTokenizer , UpperCamelCase__: int = -1 , UpperCamelCase__: int = -1 , UpperCamelCase__: bool = False , UpperCamelCase__: Optional[TensorType] = None , ): if self.task in ["default", "seq2seq-lm"]: lowerCamelCase__ : Dict = self._generate_dummy_inputs_for_default_and_seqaseq_lm( UpperCamelCase__ , batch_size=UpperCamelCase__ , seq_length=UpperCamelCase__ , is_pair=UpperCamelCase__ , framework=UpperCamelCase__ ) else: lowerCamelCase__ : Tuple = self._generate_dummy_inputs_for_causal_lm( UpperCamelCase__ , batch_size=UpperCamelCase__ , seq_length=UpperCamelCase__ , is_pair=UpperCamelCase__ , framework=UpperCamelCase__ ) return common_inputs def lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Dict , UpperCamelCase__: Optional[Any] ): if self.task in ["default", "seq2seq-lm"]: lowerCamelCase__ : Dict = super()._flatten_past_key_values_(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: lowerCamelCase__ : List[Any] = super(UpperCamelCase__ , self )._flatten_past_key_values_( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) @property def lowerCamelCase_ ( self: Union[str, Any] ): return 1e-4
129
1
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 10**-10 )-> float: lowerCAmelCase_ : int = a while True: lowerCAmelCase_ : Dict = Decimal(lowerCAmelCase_ ) - ( Decimal(eval(lowerCAmelCase_ ) ) / Decimal(eval(str(diff(lowerCAmelCase_ ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(lowerCAmelCase_ ) ) < precision: # noqa: S307 return float(lowerCAmelCase_ ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f"""The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}""") # Find root of polynomial print(f"""The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}""") # Find Square Root of 5 print(f"""The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}""") # Exponential Roots print(f"""The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}""")
262
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 : str ="""docs/source/en""" _UpperCAmelCase : Optional[int] =""".""" def lowerCAmelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )-> List[str]: with open(lowerCAmelCase_ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: lowerCAmelCase_ : int = f.readlines() # Find the start prompt. lowerCAmelCase_ : List[Any] = 0 while not lines[start_index].startswith(lowerCAmelCase_ ): start_index += 1 start_index += 1 lowerCAmelCase_ : List[str] = start_index while not lines[end_index].startswith(lowerCAmelCase_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | _UpperCAmelCase : Optional[Any] ="""Model|Encoder|Decoder|ForConditionalGeneration""" # Regexes that match TF/Flax/PT model names. _UpperCAmelCase : Optional[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 : Optional[Any] =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 lowerCAmelCase ( lowerCAmelCase_ )-> Optional[int]: lowerCAmelCase_ : str = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , lowerCAmelCase_ ) return [m.group(0 ) for m in matches] def lowerCAmelCase ( lowerCAmelCase_ , lowerCAmelCase_ )-> Optional[int]: lowerCAmelCase_ : Tuple = 2 if text == '''✅''' or text == '''❌''' else len(lowerCAmelCase_ ) lowerCAmelCase_ : int = (width - text_length) // 2 lowerCAmelCase_ : Union[str, Any] = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def lowerCAmelCase ( )-> str: lowerCAmelCase_ : Any = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES lowerCAmelCase_ : Dict = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } lowerCAmelCase_ : 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. lowerCAmelCase_ : Tuple = collections.defaultdict(lowerCAmelCase_ ) lowerCAmelCase_ : List[str] = collections.defaultdict(lowerCAmelCase_ ) lowerCAmelCase_ : Optional[Any] = collections.defaultdict(lowerCAmelCase_ ) lowerCAmelCase_ : Optional[int] = collections.defaultdict(lowerCAmelCase_ ) lowerCAmelCase_ : List[str] = collections.defaultdict(lowerCAmelCase_ ) # Let's lookup through all transformers object (once). for attr_name in dir(lowerCAmelCase_ ): lowerCAmelCase_ : Optional[int] = None if attr_name.endswith('''Tokenizer''' ): lowerCAmelCase_ : Union[str, Any] = slow_tokenizers lowerCAmelCase_ : List[str] = attr_name[:-9] elif attr_name.endswith('''TokenizerFast''' ): lowerCAmelCase_ : int = fast_tokenizers lowerCAmelCase_ : Union[str, Any] = attr_name[:-13] elif _re_tf_models.match(lowerCAmelCase_ ) is not None: lowerCAmelCase_ : Tuple = tf_models lowerCAmelCase_ : str = _re_tf_models.match(lowerCAmelCase_ ).groups()[0] elif _re_flax_models.match(lowerCAmelCase_ ) is not None: lowerCAmelCase_ : Tuple = flax_models lowerCAmelCase_ : Union[str, Any] = _re_flax_models.match(lowerCAmelCase_ ).groups()[0] elif _re_pt_models.match(lowerCAmelCase_ ) is not None: lowerCAmelCase_ : Any = pt_models lowerCAmelCase_ : List[Any] = _re_pt_models.match(lowerCAmelCase_ ).groups()[0] if lookup_dict is not None: while len(lowerCAmelCase_ ) > 0: if attr_name in model_name_to_prefix.values(): lowerCAmelCase_ : Union[str, Any] = True break # Try again after removing the last word in the name lowerCAmelCase_ : Any = ''''''.join(camel_case_split(lowerCAmelCase_ )[:-1] ) # Let's build that table! lowerCAmelCase_ : int = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) lowerCAmelCase_ : Tuple = ['''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). lowerCAmelCase_ : Union[str, Any] = [len(lowerCAmelCase_ ) + 2 for c in columns] lowerCAmelCase_ : Optional[Any] = max([len(lowerCAmelCase_ ) for name in model_names] ) + 2 # Build the table per se lowerCAmelCase_ : Dict = '''|''' + '''|'''.join([_center_text(lowerCAmelCase_ , lowerCAmelCase_ ) for c, w in zip(lowerCAmelCase_ , lowerCAmelCase_ )] ) + '''|\n''' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n" lowerCAmelCase_ : List[str] = {True: '''✅''', False: '''❌'''} for name in model_names: lowerCAmelCase_ : List[Any] = model_name_to_prefix[name] lowerCAmelCase_ : Union[str, Any] = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(lowerCAmelCase_ , lowerCAmelCase_ ) for l, w in zip(lowerCAmelCase_ , lowerCAmelCase_ )] ) + "|\n" return table def lowerCAmelCase ( lowerCAmelCase_=False )-> Tuple: lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ : str = _find_text_in_file( filename=os.path.join(lowerCAmelCase_ , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , ) lowerCAmelCase_ : Tuple = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(lowerCAmelCase_ , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( '''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' ) if __name__ == "__main__": _UpperCAmelCase : List[Any] =argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") _UpperCAmelCase : Tuple =parser.parse_args() check_model_table(args.fix_and_overwrite)
262
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase : Dict = { 'configuration_mctct': ['MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MCTCTConfig'], 'feature_extraction_mctct': ['MCTCTFeatureExtractor'], 'processing_mctct': ['MCTCTProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] = [ 'MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MCTCTForCTC', 'MCTCTModel', 'MCTCTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys UpperCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
369
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer UpperCAmelCase : Tuple = logging.get_logger(__name__) UpperCAmelCase : List[str] = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase : str = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } UpperCAmelCase : int = { "distilbert-base-uncased": 5_12, "distilbert-base-uncased-distilled-squad": 5_12, "distilbert-base-cased": 5_12, "distilbert-base-cased-distilled-squad": 5_12, "distilbert-base-german-cased": 5_12, "distilbert-base-multilingual-cased": 5_12, } UpperCAmelCase : str = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class __lowercase ( a_ ): """simple docstring""" UpperCamelCase : Any = VOCAB_FILES_NAMES UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Tuple = PRETRAINED_INIT_CONFIGURATION UpperCamelCase : List[str] = ["input_ids", "attention_mask"] UpperCamelCase : List[str] = DistilBertTokenizer def __init__( self , A=None , A=None , A=True , A="[UNK]" , A="[SEP]" , A="[PAD]" , A="[CLS]" , A="[MASK]" , A=True , A=None , **A , ) -> Optional[Any]: '''simple docstring''' super().__init__( A , tokenizer_file=A , do_lower_case=A , unk_token=A , sep_token=A , pad_token=A , cls_token=A , mask_token=A , tokenize_chinese_chars=A , strip_accents=A , **A , ) lowerCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , A ) != do_lower_case or normalizer_state.get("""strip_accents""" , A ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , A ) != tokenize_chinese_chars ): lowerCamelCase = getattr(A , normalizer_state.pop("""type""" ) ) lowerCamelCase = do_lower_case lowerCamelCase = strip_accents lowerCamelCase = tokenize_chinese_chars lowerCamelCase = normalizer_class(**A ) lowerCamelCase = do_lower_case def __A ( self , A , A=None ) -> Tuple: '''simple docstring''' lowerCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , A , A = None ) -> List[int]: '''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 __A ( self , A , A = None ) -> Tuple[str]: '''simple docstring''' lowerCamelCase = self._tokenizer.model.save(A , name=A ) return tuple(A )
66
0
"""simple docstring""" from __future__ import annotations from collections import deque class snake_case__ : def __init__( self , lowerCamelCase ): __a = [] self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []} ) for keyword in keywords: self.add_keyword(lowerCamelCase ) self.set_fail_transitions() def a__ ( self , lowerCamelCase , lowerCamelCase ): for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def a__ ( self , lowerCamelCase ): __a = 0 for character in keyword: __a = self.find_next_state(lowerCamelCase , lowerCamelCase ) if next_state is None: self.adlist.append( { "value": character, "next_states": [], "fail_state": 0, "output": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) __a = len(self.adlist ) - 1 else: __a = next_state self.adlist[current_state]["output"].append(lowerCamelCase ) def a__ ( self ): __a = deque() for node in self.adlist[0]["next_states"]: q.append(lowerCamelCase ) __a = 0 while q: __a = q.popleft() for child in self.adlist[r]["next_states"]: q.append(lowerCamelCase ) __a = self.adlist[r]["fail_state"] while ( self.find_next_state(lowerCamelCase , self.adlist[child]["value"] ) is None and state != 0 ): __a = self.adlist[state]["fail_state"] __a = self.find_next_state( lowerCamelCase , self.adlist[child]["value"] ) if self.adlist[child]["fail_state"] is None: __a = 0 __a = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] ) def a__ ( self , lowerCamelCase ): __a = {} # returns a dict with keywords and list of its occurrences __a = 0 for i in range(len(lowerCamelCase ) ): while ( self.find_next_state(lowerCamelCase , string[i] ) is None and current_state != 0 ): __a = self.adlist[current_state]["fail_state"] __a = self.find_next_state(lowerCamelCase , string[i] ) if next_state is None: __a = 0 else: __a = next_state for key in self.adlist[current_state]["output"]: if key not in result: __a = [] result[key].append(i - len(lowerCamelCase ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
261
"""simple docstring""" import copy import re class snake_case__ : _snake_case : Dict = """hp""" _snake_case : List[str] = {} _snake_case : int = None @classmethod def a__ ( cls , lowerCamelCase , lowerCamelCase ): __a = prefix __a = defaults cls.build_naming_info() @staticmethod def a__ ( lowerCamelCase , lowerCamelCase ): if len(lowerCamelCase ) == 0: return "" __a = None if any(char.isdigit() for char in word ): raise Exception(F"Parameters should not contain numbers: '{word}' contains a number" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(lowerCamelCase ) + 1 ): __a = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: __a = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(lowerCamelCase ): __a = "" while integer != 0: __a = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s __a = 0 while True: __a = word + "#" + int_to_alphabetic(lowerCamelCase ) if sword in info["reverse_short_word"]: continue else: __a = sword break __a = short_word __a = word return short_word @staticmethod def a__ ( lowerCamelCase , lowerCamelCase ): __a = param_name.split("_" ) __a = [TrialShortNamer.shortname_for_word(lowerCamelCase , lowerCamelCase ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name __a = ["", "_"] for separator in separators: __a = separator.join(lowerCamelCase ) if shortname not in info["reverse_short_param"]: __a = shortname __a = param_name return shortname return param_name @staticmethod def a__ ( lowerCamelCase , lowerCamelCase ): __a = TrialShortNamer.shortname_for_key(lowerCamelCase , lowerCamelCase ) __a = short_name __a = param_name @classmethod def a__ ( cls ): if cls.NAMING_INFO is not None: return __a = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } __a = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(lowerCamelCase , lowerCamelCase ) __a = info @classmethod def a__ ( cls , lowerCamelCase ): cls.build_naming_info() assert cls.PREFIX is not None __a = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(F"You should provide a default value for the param name {k} with value {v}" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue __a = cls.NAMING_INFO["short_param"][k] if isinstance(lowerCamelCase , lowerCamelCase ): __a = 1 if v else 0 __a = "" if isinstance(lowerCamelCase , (int, float) ) else "-" __a = F"{key}{sep}{v}" name.append(lowerCamelCase ) return "_".join(lowerCamelCase ) @classmethod def a__ ( cls , lowerCamelCase ): __a = repr[len(cls.PREFIX ) + 1 :] if repr == "": __a = [] else: __a = repr.split("_" ) __a = {} for value in values: if "-" in value: __a , __a = value.split("-" ) else: __a = re.sub("[0-9.]" , "" , lowerCamelCase ) __a = float(re.sub("[^0-9.]" , "" , lowerCamelCase ) ) __a = cls.NAMING_INFO["reverse_short_param"][p_k] __a = p_v for k in cls.DEFAULTS: if k not in parameters: __a = cls.DEFAULTS[k] return parameters
261
1
"""simple docstring""" import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Optional[int] = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg' __lowerCAmelCase : int = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ).convert('RGB' ) __lowerCAmelCase : List[Any] = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48145466, 0.4578275, 0.40821073) , (0.26862954, 0.26130258, 0.27577711) ), ] ) __lowerCAmelCase : Union[str, Any] = transform(_UpperCamelCase ).unsqueeze(0 ).to(_UpperCamelCase ) return image def __lowerCAmelCase (_UpperCamelCase ): if "visual_encoder" in key: __lowerCAmelCase : int = re.sub('visual_encoder*' , 'vision_model.encoder' , _UpperCamelCase ) if "blocks" in key: __lowerCAmelCase : Tuple = re.sub(r'blocks' , 'layers' , _UpperCamelCase ) if "attn" in key: __lowerCAmelCase : Union[str, Any] = re.sub(r'attn' , 'self_attn' , _UpperCamelCase ) if "norm1" in key: __lowerCAmelCase : int = re.sub(r'norm1' , 'layer_norm1' , _UpperCamelCase ) if "norm2" in key: __lowerCAmelCase : Optional[Any] = re.sub(r'norm2' , 'layer_norm2' , _UpperCamelCase ) if "encoder.norm" in key: __lowerCAmelCase : Dict = re.sub(r'encoder.norm' , 'post_layernorm' , _UpperCamelCase ) if "encoder.patch_embed.proj" in key: __lowerCAmelCase : List[str] = re.sub(r'encoder.patch_embed.proj' , 'embeddings.patch_embedding' , _UpperCamelCase ) if "encoder.pos_embed" in key: __lowerCAmelCase : List[Any] = re.sub(r'encoder.pos_embed' , 'embeddings.position_embedding' , _UpperCamelCase ) if "encoder.cls_token" in key: __lowerCAmelCase : List[str] = re.sub(r'encoder.cls_token' , 'embeddings.class_embedding' , _UpperCamelCase ) if "self_attn" in key: __lowerCAmelCase : Optional[int] = re.sub(r'self_attn.proj' , 'self_attn.projection' , _UpperCamelCase ) return key @torch.no_grad() def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase=None ): if config_path is not None: __lowerCAmelCase : Union[str, Any] = BlipConfig.from_pretrained(_UpperCamelCase ) else: __lowerCAmelCase : Any = BlipConfig(projection_dim=512 , text_config={} , vision_config={} ) __lowerCAmelCase : Dict = BlipForConditionalGeneration(_UpperCamelCase ).eval() __lowerCAmelCase : str = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth' __lowerCAmelCase : Optional[Any] = blip_decoder(pretrained=_UpperCamelCase , image_size=384 , vit='base' ) __lowerCAmelCase : Any = pt_model.eval() __lowerCAmelCase : Dict = pt_model.state_dict() for key in modified_state_dict.copy(): __lowerCAmelCase : Any = modified_state_dict.pop(_UpperCamelCase ) __lowerCAmelCase : Any = rename_key(_UpperCamelCase ) __lowerCAmelCase : str = value hf_model.load_state_dict(_UpperCamelCase ) __lowerCAmelCase : int = 384 __lowerCAmelCase : Any = load_demo_image(image_size=_UpperCamelCase , device='cpu' ) __lowerCAmelCase : Union[str, Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) __lowerCAmelCase : List[str] = tokenizer(['a picture of'] ).input_ids __lowerCAmelCase : Dict = hf_model.generate(_UpperCamelCase , _UpperCamelCase ) assert out[0].tolist() == [3_0522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] __lowerCAmelCase : int = hf_model.generate(_UpperCamelCase ) assert out[0].tolist() == [3_0522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(_UpperCamelCase ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' __lowerCAmelCase : Any = ( 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth' ) __lowerCAmelCase : str = blip_vqa(pretrained=_UpperCamelCase , image_size=_UpperCamelCase , vit='base' ) vqa_model.eval() __lowerCAmelCase : Optional[int] = vqa_model.state_dict() for key in modified_state_dict.copy(): __lowerCAmelCase : str = modified_state_dict.pop(_UpperCamelCase ) __lowerCAmelCase : List[Any] = rename_key(_UpperCamelCase ) __lowerCAmelCase : Union[str, Any] = value __lowerCAmelCase : Union[str, Any] = BlipForQuestionAnswering(_UpperCamelCase ) hf_vqa_model.load_state_dict(_UpperCamelCase ) __lowerCAmelCase : Tuple = ['How many dogs are in this image?'] __lowerCAmelCase : List[str] = tokenizer(_UpperCamelCase , return_tensors='pt' ).input_ids __lowerCAmelCase : str = hf_vqa_model.generate(_UpperCamelCase , _UpperCamelCase ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '_vqa' ) __lowerCAmelCase : Optional[int] = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth' __lowerCAmelCase : Union[str, Any] = blip_itm(pretrained=_UpperCamelCase , image_size=_UpperCamelCase , vit='base' ) itm_model.eval() __lowerCAmelCase : List[Any] = itm_model.state_dict() for key in modified_state_dict.copy(): __lowerCAmelCase : Tuple = modified_state_dict.pop(_UpperCamelCase ) __lowerCAmelCase : int = rename_key(_UpperCamelCase ) __lowerCAmelCase : Any = value __lowerCAmelCase : Any = BlipForImageTextRetrieval(_UpperCamelCase ) __lowerCAmelCase : Union[str, Any] = ['A picture of a woman with a dog sitting in a beach'] __lowerCAmelCase : Optional[Any] = tokenizer( _UpperCamelCase , return_tensors='pt' , padding='max_length' , truncation=_UpperCamelCase , max_length=35 , ).input_ids hf_itm_model.load_state_dict(_UpperCamelCase ) hf_itm_model.eval() __lowerCAmelCase : Optional[Any] = hf_itm_model(_UpperCamelCase , _UpperCamelCase , use_itm_head=_UpperCamelCase ) __lowerCAmelCase : int = hf_itm_model(_UpperCamelCase , _UpperCamelCase , use_itm_head=_UpperCamelCase ) assert out[0].item() == 0.2110687494277954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.45698845386505127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '_itm' ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") lowerCamelCase__ = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
182
"""simple docstring""" import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params lowerCamelCase__ = getLogger(__name__) lowerCamelCase__ = """cuda""" if torch.cuda.is_available() else """cpu""" def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 8 , _UpperCamelCase = DEFAULT_DEVICE , _UpperCamelCase=False , _UpperCamelCase="summarization" , _UpperCamelCase=None , **_UpperCamelCase , ): __lowerCAmelCase : str = Path(_UpperCamelCase ).open('w' , encoding='utf-8' ) __lowerCAmelCase : Union[str, Any] = str(_UpperCamelCase ) __lowerCAmelCase : List[str] = AutoModelForSeqaSeqLM.from_pretrained(_UpperCamelCase ).to(_UpperCamelCase ) if fpaa: __lowerCAmelCase : Optional[Any] = model.half() __lowerCAmelCase : List[str] = AutoTokenizer.from_pretrained(_UpperCamelCase ) logger.info(F"Inferred tokenizer type: {tokenizer.__class__}" ) # if this is wrong, check config.model_type. __lowerCAmelCase : List[Any] = time.time() # update config with task specific params use_task_specific_params(_UpperCamelCase , _UpperCamelCase ) if prefix is None: __lowerCAmelCase : Optional[int] = prefix or getattr(model.config , 'prefix' , '' ) or '' for examples_chunk in tqdm(list(chunks(_UpperCamelCase , _UpperCamelCase ) ) ): __lowerCAmelCase : List[str] = [prefix + text for text in examples_chunk] __lowerCAmelCase : List[str] = tokenizer(_UpperCamelCase , return_tensors='pt' , truncation=_UpperCamelCase , padding='longest' ).to(_UpperCamelCase ) __lowerCAmelCase : str = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **_UpperCamelCase , ) __lowerCAmelCase : str = tokenizer.batch_decode(_UpperCamelCase , skip_special_tokens=_UpperCamelCase , clean_up_tokenization_spaces=_UpperCamelCase ) for hypothesis in dec: fout.write(hypothesis + '\n' ) fout.flush() fout.close() __lowerCAmelCase : Optional[int] = int(time.time() - start_time ) # seconds __lowerCAmelCase : List[Any] = len(_UpperCamelCase ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def __lowerCAmelCase (): return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' ) def __lowerCAmelCase (_UpperCamelCase=True ): __lowerCAmelCase : List[Any] = argparse.ArgumentParser() parser.add_argument('model_name' , type=_UpperCamelCase , help='like facebook/bart-large-cnn,t5-base, etc.' ) parser.add_argument('input_path' , type=_UpperCamelCase , help='like cnn_dm/test.source' ) parser.add_argument('save_path' , type=_UpperCamelCase , help='where to save summaries' ) parser.add_argument('--reference_path' , type=_UpperCamelCase , required=_UpperCamelCase , help='like cnn_dm/test.target' ) parser.add_argument('--score_path' , type=_UpperCamelCase , required=_UpperCamelCase , default='metrics.json' , help='where to save metrics' ) parser.add_argument('--device' , type=_UpperCamelCase , required=_UpperCamelCase , default=_UpperCamelCase , help='cuda, cuda:1, cpu etc.' ) parser.add_argument( '--prefix' , type=_UpperCamelCase , required=_UpperCamelCase , default=_UpperCamelCase , help='will be added to the begininng of src examples' ) parser.add_argument('--task' , type=_UpperCamelCase , default='summarization' , help='used for task_specific_params + metrics' ) parser.add_argument('--bs' , type=_UpperCamelCase , default=8 , required=_UpperCamelCase , help='batch size' ) parser.add_argument( '--n_obs' , type=_UpperCamelCase , default=-1 , required=_UpperCamelCase , help='How many observations. Defaults to all.' ) parser.add_argument('--fp16' , action='store_true' ) parser.add_argument('--dump-args' , action='store_true' , help='print the custom hparams with the results' ) parser.add_argument( '--info' , nargs='?' , type=_UpperCamelCase , const=datetime_now() , help=( 'use in conjunction w/ --dump-args to print with the results whatever other info you\'d like, e.g.' ' lang=en-ru. If no value is passed, the current datetime string will be used.' ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate __lowerCAmelCase , __lowerCAmelCase : Optional[int] = parser.parse_known_args() __lowerCAmelCase : Optional[int] = parse_numeric_n_bool_cl_kwargs(_UpperCamelCase ) if parsed_args and verbose: print(F"parsed the following generate kwargs: {parsed_args}" ) __lowerCAmelCase : Dict = [' ' + x.rstrip() if 't5' in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: __lowerCAmelCase : int = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=_UpperCamelCase ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(F"score_path {args.score_path} will be overwritten unless you type ctrl-c." ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError('Can\'t mix --fp16 and --device cpu' ) __lowerCAmelCase : Optional[Any] = generate_summaries_or_translations( _UpperCamelCase , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **_UpperCamelCase , ) if args.reference_path is None: return {} # Compute scores __lowerCAmelCase : str = calculate_bleu if 'translation' in args.task else calculate_rouge __lowerCAmelCase : Dict = [x.rstrip() for x in open(args.save_path ).readlines()] __lowerCAmelCase : Dict = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(_UpperCamelCase )] __lowerCAmelCase : dict = score_fn(_UpperCamelCase , _UpperCamelCase ) scores.update(_UpperCamelCase ) if args.dump_args: scores.update(_UpperCamelCase ) if args.info: __lowerCAmelCase : Optional[Any] = args.info if verbose: print(_UpperCamelCase ) if args.score_path is not None: json.dump(_UpperCamelCase , open(args.score_path , 'w' ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
182
1
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class lowerCAmelCase ( __UpperCamelCase ): def __init__( self : Optional[int] , UpperCAmelCase : pyspark.sql.DataFrame , UpperCAmelCase : Optional[NamedSplit] = None , UpperCAmelCase : Optional[Features] = None , UpperCAmelCase : bool = True , UpperCAmelCase : str = None , UpperCAmelCase : bool = False , UpperCAmelCase : str = None , UpperCAmelCase : bool = True , UpperCAmelCase : str = "arrow" , **UpperCAmelCase : List[Any] , ) -> List[Any]: super().__init__( split=UpperCAmelCase , features=UpperCAmelCase , cache_dir=UpperCAmelCase , keep_in_memory=UpperCAmelCase , streaming=UpperCAmelCase , **UpperCAmelCase , ) lowerCamelCase__ : str = load_from_cache_file lowerCamelCase__ : Dict = file_format lowerCamelCase__ : Union[str, Any] = Spark( df=UpperCAmelCase , features=UpperCAmelCase , cache_dir=UpperCAmelCase , working_dir=UpperCAmelCase , **UpperCAmelCase , ) def A_ ( self : int ) -> List[Any]: if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) lowerCamelCase__ : List[Any] = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=UpperCAmelCase , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
50
import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() _UpperCAmelCase : Dict = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> List[str]: lowerCamelCase__ : str = OrderedDict() for key, value in state_dict.items(): if key.startswith('module.encoder' ): lowerCamelCase__ : Optional[Any] = key.replace('module.encoder' , 'glpn.encoder' ) if key.startswith('module.decoder' ): lowerCamelCase__ : List[str] = key.replace('module.decoder' , 'decoder.stages' ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 lowerCamelCase__ : Dict = key[key.find('patch_embed' ) + len('patch_embed' )] lowerCamelCase__ : Tuple = key.replace(F"""patch_embed{idx}""" , F"""patch_embeddings.{int(_UpperCAmelCase )-1}""" ) if "norm" in key: lowerCamelCase__ : str = key.replace('norm' , 'layer_norm' ) if "glpn.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 lowerCamelCase__ : Dict = key[key.find('glpn.encoder.layer_norm' ) + len('glpn.encoder.layer_norm' )] lowerCamelCase__ : str = key.replace(F"""layer_norm{idx}""" , F"""layer_norm.{int(_UpperCAmelCase )-1}""" ) if "layer_norm1" in key: lowerCamelCase__ : Optional[int] = key.replace('layer_norm1' , 'layer_norm_1' ) if "layer_norm2" in key: lowerCamelCase__ : Optional[int] = key.replace('layer_norm2' , 'layer_norm_2' ) if "block" in key: # replace for example block1 by block.0 lowerCamelCase__ : List[Any] = key[key.find('block' ) + len('block' )] lowerCamelCase__ : int = key.replace(F"""block{idx}""" , F"""block.{int(_UpperCAmelCase )-1}""" ) if "attn.q" in key: lowerCamelCase__ : Union[str, Any] = key.replace('attn.q' , 'attention.self.query' ) if "attn.proj" in key: lowerCamelCase__ : Union[str, Any] = key.replace('attn.proj' , 'attention.output.dense' ) if "attn" in key: lowerCamelCase__ : Dict = key.replace('attn' , 'attention.self' ) if "fc1" in key: lowerCamelCase__ : Dict = key.replace('fc1' , 'dense1' ) if "fc2" in key: lowerCamelCase__ : Any = key.replace('fc2' , 'dense2' ) if "linear_pred" in key: lowerCamelCase__ : Dict = key.replace('linear_pred' , 'classifier' ) if "linear_fuse" in key: lowerCamelCase__ : Tuple = key.replace('linear_fuse.conv' , 'linear_fuse' ) lowerCamelCase__ : List[str] = key.replace('linear_fuse.bn' , 'batch_norm' ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 lowerCamelCase__ : Optional[Any] = key[key.find('linear_c' ) + len('linear_c' )] lowerCamelCase__ : Dict = key.replace(F"""linear_c{idx}""" , F"""linear_c.{int(_UpperCAmelCase )-1}""" ) if "bot_conv" in key: lowerCamelCase__ : str = key.replace('bot_conv' , '0.convolution' ) if "skip_conv1" in key: lowerCamelCase__ : Union[str, Any] = key.replace('skip_conv1' , '1.convolution' ) if "skip_conv2" in key: lowerCamelCase__ : List[Any] = key.replace('skip_conv2' , '2.convolution' ) if "fusion1" in key: lowerCamelCase__ : Optional[int] = key.replace('fusion1' , '1.fusion' ) if "fusion2" in key: lowerCamelCase__ : Union[str, Any] = key.replace('fusion2' , '2.fusion' ) if "fusion3" in key: lowerCamelCase__ : List[Any] = key.replace('fusion3' , '3.fusion' ) if "fusion" in key and "conv" in key: lowerCamelCase__ : str = key.replace('conv' , 'convolutional_layer' ) if key.startswith('module.last_layer_depth' ): lowerCamelCase__ : Dict = key.replace('module.last_layer_depth' , 'head.head' ) lowerCamelCase__ : str = value return new_state_dict def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Optional[int]: # for each of the encoder blocks: for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) lowerCamelCase__ : Any = state_dict.pop(F"""glpn.encoder.block.{i}.{j}.attention.self.kv.weight""" ) lowerCamelCase__ : Optional[Any] = state_dict.pop(F"""glpn.encoder.block.{i}.{j}.attention.self.kv.bias""" ) # next, add keys and values (in that order) to the state dict lowerCamelCase__ : Optional[int] = kv_weight[ : config.hidden_sizes[i], : ] lowerCamelCase__ : Optional[int] = kv_bias[: config.hidden_sizes[i]] lowerCamelCase__ : Any = kv_weight[ config.hidden_sizes[i] :, : ] lowerCamelCase__ : Dict = kv_bias[config.hidden_sizes[i] :] def SCREAMING_SNAKE_CASE ( ) -> str: lowerCamelCase__ : List[str] = 'http://images.cocodataset.org/val2017/000000039769.jpg' lowerCamelCase__ : Tuple = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False , _UpperCAmelCase=None ) -> Optional[int]: lowerCamelCase__ : str = GLPNConfig(hidden_sizes=[64, 128, 320, 512] , decoder_hidden_size=64 , depths=[3, 8, 27, 3] ) # load image processor (only resize + rescale) lowerCamelCase__ : Union[str, Any] = GLPNImageProcessor() # prepare image lowerCamelCase__ : str = prepare_img() lowerCamelCase__ : Tuple = image_processor(images=_UpperCAmelCase , return_tensors='pt' ).pixel_values logger.info('Converting model...' ) # load original state dict lowerCamelCase__ : Any = torch.load(_UpperCAmelCase , map_location=torch.device('cpu' ) ) # rename keys lowerCamelCase__ : str = rename_keys(_UpperCAmelCase ) # key and value matrices need special treatment read_in_k_v(_UpperCAmelCase , _UpperCAmelCase ) # create HuggingFace model and load state dict lowerCamelCase__ : Dict = GLPNForDepthEstimation(_UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ) model.eval() # forward pass lowerCamelCase__ : List[str] = model(_UpperCAmelCase ) lowerCamelCase__ : Tuple = outputs.predicted_depth # verify output if model_name is not None: if "nyu" in model_name: lowerCamelCase__ : List[Any] = torch.tensor( [[4.4_147, 4.0_873, 4.0_673], [3.7_890, 3.2_881, 3.1_525], [3.7_674, 3.5_423, 3.4_913]] ) elif "kitti" in model_name: lowerCamelCase__ : List[str] = torch.tensor( [[3.4_291, 2.7_865, 2.5_151], [3.2_841, 2.7_021, 2.3_502], [3.1_147, 2.4_625, 2.2_481]] ) else: raise ValueError(F"""Unknown model name: {model_name}""" ) lowerCamelCase__ : Tuple = torch.Size([1, 480, 640] ) assert predicted_depth.shape == expected_shape assert torch.allclose(predicted_depth[0, :3, :3] , _UpperCAmelCase , atol=1e-4 ) print('Looks ok!' ) # finally, push to hub if required if push_to_hub: logger.info('Pushing model and image processor to the hub...' ) model.push_to_hub( repo_path_or_name=Path(_UpperCAmelCase , _UpperCAmelCase ) , organization='nielsr' , commit_message='Add model' , use_temp_dir=_UpperCAmelCase , ) image_processor.push_to_hub( repo_path_or_name=Path(_UpperCAmelCase , _UpperCAmelCase ) , organization='nielsr' , commit_message='Add image processor' , use_temp_dir=_UpperCAmelCase , ) if __name__ == "__main__": _UpperCAmelCase : Tuple = argparse.ArgumentParser() parser.add_argument( """--checkpoint_path""", default=None, type=str, help="""Path to the original PyTorch checkpoint (.pth file).""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to upload the model to the HuggingFace hub.""" ) parser.add_argument( """--model_name""", default="""glpn-kitti""", type=str, help="""Name of the model in case you're pushing to the hub.""", ) _UpperCAmelCase : int = parser.parse_args() convert_glpn_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
50
1
"""simple docstring""" SCREAMING_SNAKE_CASE = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" SCREAMING_SNAKE_CASE = [{"type": "code", "content": INSTALL_CONTENT}] SCREAMING_SNAKE_CASE = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
366
"""simple docstring""" from typing import Any class UpperCAmelCase_ : def __init__( self : Optional[Any] , snake_case_ : Any ) -> List[str]: '''simple docstring''' A__ = data A__ = None def __repr__( self : Optional[int] ) -> str: '''simple docstring''' return F"""Node({self.data})""" class UpperCAmelCase_ : def __init__( self : Dict ) -> Any: '''simple docstring''' A__ = None def __iter__( self : List[Any] ) -> Any: '''simple docstring''' A__ = self.head while node: yield node.data A__ = node.next def __len__( self : Any ) -> int: '''simple docstring''' return sum(1 for _ in self ) def __repr__( self : List[str] ) -> str: '''simple docstring''' return "->".join([str(snake_case_ ) for item in self] ) def __getitem__( self : str , snake_case_ : int ) -> Any: '''simple docstring''' if not 0 <= index < len(self ): raise ValueError("list index out of range." ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Tuple , snake_case_ : int , snake_case_ : Any ) -> None: '''simple docstring''' if not 0 <= index < len(self ): raise ValueError("list index out of range." ) A__ = self.head for _ in range(snake_case_ ): A__ = current.next A__ = data def __magic_name__ ( self : List[Any] , snake_case_ : Any ) -> None: '''simple docstring''' self.insert_nth(len(self ) , snake_case_ ) def __magic_name__ ( self : Tuple , snake_case_ : Any ) -> None: '''simple docstring''' self.insert_nth(0 , snake_case_ ) def __magic_name__ ( self : Dict , snake_case_ : int , snake_case_ : Any ) -> None: '''simple docstring''' if not 0 <= index <= len(self ): raise IndexError("list index out of range" ) A__ = Node(snake_case_ ) if self.head is None: A__ = new_node elif index == 0: A__ = self.head # link new_node to head A__ = new_node else: A__ = self.head for _ in range(index - 1 ): A__ = temp.next A__ = temp.next A__ = new_node def __magic_name__ ( self : Dict ) -> None: # print every node data '''simple docstring''' print(self ) def __magic_name__ ( self : Dict ) -> Any: '''simple docstring''' return self.delete_nth(0 ) def __magic_name__ ( self : Optional[Any] ) -> Any: # delete from tail '''simple docstring''' return self.delete_nth(len(self ) - 1 ) def __magic_name__ ( self : Any , snake_case_ : int = 0 ) -> Any: '''simple docstring''' if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("List index out of range." ) A__ = self.head # default first node if index == 0: A__ = self.head.next else: A__ = self.head for _ in range(index - 1 ): A__ = temp.next A__ = temp.next A__ = temp.next.next return delete_node.data def __magic_name__ ( self : Dict ) -> bool: '''simple docstring''' return self.head is None def __magic_name__ ( self : List[Any] ) -> None: '''simple docstring''' A__ = None A__ = self.head while current: # Store the current node's next node. A__ = current.next # Make the current node's next point backwards A__ = prev # Make the previous node be the current node A__ = current # Make the current node the next node (to progress iteration) A__ = next_node # Return prev in order to put the head at the end A__ = prev def _SCREAMING_SNAKE_CASE ( ) -> None: A__ = LinkedList() assert linked_list.is_empty() is True assert str(lowercase_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(lowercase_ ) == i linked_list.insert_nth(lowercase_ , i + 1 ) assert str(lowercase_ ) == "->".join(str(lowercase_ ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(lowercase_ ) == "->".join(str(lowercase_ ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(lowercase_ ) == 9 assert str(lowercase_ ) == "->".join(str(lowercase_ ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): A__ = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(lowercase_ ) == "->".join(str(lowercase_ ) for i in range(-8 , 1 ) ) def _SCREAMING_SNAKE_CASE ( ) -> None: A__ = [ -9, 1_00, Node(77_34_51_12 ), "dlrow olleH", 7, 55_55, 0, -1_9_2.5_5_5_5_5, "Hello, world!", 7_7.9, Node(10 ), None, None, 1_2.2_0, ] A__ = LinkedList() for i in test_input: linked_list.insert_tail(lowercase_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(lowercase_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head A__ = linked_list.delete_head() assert result == -9 assert ( str(lowercase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail A__ = linked_list.delete_tail() assert result == 1_2.2 assert ( str(lowercase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list A__ = linked_list.delete_nth(10 ) assert result is None assert ( str(lowercase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!" ) ) assert ( str(lowercase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(lowercase_ ) assert ( str(lowercase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(lowercase_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def _SCREAMING_SNAKE_CASE ( ) -> Optional[int]: from doctest import testmod testmod() A__ = LinkedList() linked_list.insert_head(input("Inserting 1st at head " ).strip() ) linked_list.insert_head(input("Inserting 2nd at head " ).strip() ) print("\nPrint list:" ) linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail " ).strip() ) linked_list.insert_tail(input("Inserting 2nd at tail " ).strip() ) print("\nPrint list:" ) linked_list.print_list() print("\nDelete head" ) linked_list.delete_head() print("Delete tail" ) linked_list.delete_tail() print("\nPrint list:" ) linked_list.print_list() print("\nReverse linked list" ) linked_list.reverse() print("\nPrint list:" ) linked_list.print_list() print("\nString representation of linked list:" ) print(lowercase_ ) print("\nReading/changing Node data using indexing:" ) print(f"""Element at Position 1: {linked_list[1]}""" ) A__ = input("Enter New Value: " ).strip() print("New list:" ) print(lowercase_ ) print(f"""length of linked_list is : {len(lowercase_ )}""" ) if __name__ == "__main__": main()
230
0
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass __lowerCAmelCase : Any = (3, 9, -11, 0, 7, 5, 1, -1) __lowerCAmelCase : Tuple = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class __lowerCAmelCase : """simple docstring""" A__ : int A__ : Node | None class __lowerCAmelCase : """simple docstring""" def __init__( self : Optional[Any] , _snake_case : Iterable[int] ): __lowercase : Node | None = None for i in sorted(_snake_case , reverse=_snake_case ): __lowercase : List[Any] = Node(_snake_case , self.head ) def __iter__( self : str ): __lowercase : Union[str, Any] = self.head while node: yield node.data __lowercase : List[Any] = node.next_node def __len__( self : str ): return sum(1 for _ in self ) def __str__( self : List[str] ): return " -> ".join([str(_snake_case ) for node in self] ) def UpperCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase ) -> SortedLinkedList: return SortedLinkedList(list(__lowerCAmelCase ) + list(__lowerCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() __lowerCAmelCase : Dict = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
156
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer __lowerCAmelCase : Optional[int] = ["bert-base-uncased", "bert-base-cased"] __lowerCAmelCase : List[str] = "hf-internal-testing/tiny-bert-tf-only" if is_tf_available(): class __lowerCAmelCase ( tf.keras.Model ): """simple docstring""" def __init__( self : Any , _snake_case : str ): super().__init__() __lowercase : str = tokenizer __lowercase : Any = AutoConfig.from_pretrained(_snake_case ) __lowercase : Union[str, Any] = TFAutoModel.from_config(_snake_case ) def snake_case_ ( self : str , _snake_case : int ): __lowercase : Optional[Any] = self.tokenizer(_snake_case ) __lowercase : int = self.bert(**_snake_case ) return out["pooler_output"] @require_tf @require_tensorflow_text class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case_ ( self : int ): super().setUp() __lowercase : Optional[int] = [ BertTokenizer.from_pretrained(_snake_case ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false __lowercase : Optional[Any] = [TFBertTokenizer.from_pretrained(_snake_case ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(_snake_case , use_fast_bert_tokenizer=_snake_case ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __lowercase : Optional[int] = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] __lowercase : Tuple = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def snake_case_ ( self : List[str] ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): __lowercase : Dict = tokenizer(_snake_case , return_tensors='''tf''' , padding='''longest''' ) __lowercase : int = tf_tokenizer(_snake_case ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def snake_case_ ( self : Union[str, Any] ): for tf_tokenizer in self.tf_tokenizers: __lowercase : Union[str, Any] = tf_tokenizer(self.paired_sentences ) __lowercase : List[str] = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def snake_case_ ( self : Optional[Any] ): for tf_tokenizer in self.tf_tokenizers: __lowercase : Any = tf.function(_snake_case ) for test_inputs in (self.test_sentences, self.paired_sentences): __lowercase : List[Any] = tf.constant(_snake_case ) __lowercase : Any = compiled_tokenizer(_snake_case ) __lowercase : Union[str, Any] = tf_tokenizer(_snake_case ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def snake_case_ ( self : Tuple ): for tf_tokenizer in self.tf_tokenizers: __lowercase : Any = ModelToSave(tokenizer=_snake_case ) __lowercase : str = tf.convert_to_tensor(self.test_sentences ) __lowercase : Union[str, Any] = model(_snake_case ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __lowercase : Union[str, Any] = Path(_snake_case ) / '''saved.model''' model.save(_snake_case ) __lowercase : List[str] = tf.keras.models.load_model(_snake_case ) __lowercase : Tuple = loaded_model(_snake_case ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
156
1
"""simple docstring""" from __future__ import annotations def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : List[str] = 2 __lowerCAmelCase : Any = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCamelCase ) if n > 1: factors.append(_UpperCamelCase ) return factors if __name__ == "__main__": import doctest doctest.testmod()
182
"""simple docstring""" import os def __lowerCAmelCase (_UpperCamelCase = "input.txt" ): with open(os.path.join(os.path.dirname(_UpperCamelCase ) , _UpperCamelCase ) ) as input_file: __lowerCAmelCase : Optional[Any] = [ [int(_UpperCamelCase ) for element in line.split(',' )] for line in input_file.readlines() ] __lowerCAmelCase : List[str] = len(_UpperCamelCase ) __lowerCAmelCase : Tuple = len(matrix[0] ) __lowerCAmelCase : int = [[-1 for _ in range(_UpperCamelCase )] for _ in range(_UpperCamelCase )] for i in range(_UpperCamelCase ): __lowerCAmelCase : Any = matrix[i][0] for j in range(1 , _UpperCamelCase ): for i in range(_UpperCamelCase ): __lowerCAmelCase : Optional[Any] = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1 , _UpperCamelCase ): __lowerCAmelCase : Optional[Any] = min( minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2 , -1 , -1 ): __lowerCAmelCase : List[str] = min( minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums ) if __name__ == "__main__": print(f'{solution() = }')
182
1
"""simple docstring""" from math import ceil, sqrt def __lowerCamelCase ( a_ : int = 1_00_00_00 ) -> int: __SCREAMING_SNAKE_CASE :Any = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: __SCREAMING_SNAKE_CASE :int = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE :Tuple = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f'{solution() = }')
191
"""simple docstring""" def __lowerCamelCase ( a_ : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE :List[str] = 1 __SCREAMING_SNAKE_CASE :Dict = 2 while i * i <= n: __SCREAMING_SNAKE_CASE :Tuple = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def __lowerCamelCase ( ) -> int: __SCREAMING_SNAKE_CASE :Dict = 1 __SCREAMING_SNAKE_CASE :Dict = 1 while True: i += 1 t_num += i if count_divisors(a_ ) > 5_00: break return t_num if __name__ == "__main__": print(solution())
191
1
def __snake_case ( __UpperCamelCase : int = 6008_5147_5143 ): """simple docstring""" try: A_ = int(__UpperCamelCase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) A_ = 1 A_ = 2 while i * i <= n: while n % i == 0: A_ = i n //= i i += 1 if n > 1: A_ = n return int(__UpperCamelCase ) if __name__ == "__main__": print(F"{solution() = }")
329
import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor __a :Optional[Any] = logging.get_logger(__name__) class _a ( snake_case_ ): """simple docstring""" def __init__( self : List[str] , *UpperCAmelCase : int , **UpperCAmelCase : Optional[int] ): warnings.warn( "The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use VideoMAEImageProcessor instead." , UpperCAmelCase , ) super().__init__(*UpperCAmelCase , **UpperCAmelCase )
329
1
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS lowerCAmelCase: str = logging.get_logger(__name__) lowerCAmelCase: Tuple = { 'linear': get_linear_schedule_with_warmup, 'cosine': get_cosine_schedule_with_warmup, 'cosine_w_restarts': get_cosine_with_hard_restarts_schedule_with_warmup, 'polynomial': get_polynomial_decay_schedule_with_warmup, 'constant': get_constant_schedule, 'constant_w_warmup': get_constant_schedule_with_warmup, } class a__( lowerCamelCase__ ): def __init__( self : Optional[Any] , __snake_case : List[str]=None , __snake_case : Dict=None , *__snake_case : Any , **__snake_case : Union[str, Any] ): super().__init__(*__snake_case , **__snake_case ) if config is None: assert isinstance(self.model , __snake_case ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) a : int = self.model.config else: a : Optional[Any] = config a : Any = data_args a : int = self.config.tgt_vocab_size if isinstance(self.config , __snake_case ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ' padding..' ) if self.args.label_smoothing == 0: a : Any = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss a : Tuple = label_smoothed_nll_loss def lowercase_ ( self : Union[str, Any] , __snake_case : int ): if self.optimizer is None: a : Dict = ['bias', 'LayerNorm.weight'] a : int = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] a : int = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: a : Dict = Adafactor a : List[str] = {'scale_parameter': False, 'relative_step': False} else: a : int = AdamW a : List[str] = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } a : int = self.args.learning_rate if self.sharded_ddp: a : Tuple = OSS( params=__snake_case , optim=__snake_case , **__snake_case , ) else: a : Tuple = optimizer_cls(__snake_case , **__snake_case ) if self.lr_scheduler is None: a : Tuple = self._get_lr_scheduler(__snake_case ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def lowercase_ ( self : List[Any] , __snake_case : List[str] ): a : List[Any] = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": a : Dict = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": a : Optional[Any] = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: a : Dict = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=__snake_case ) return scheduler def lowercase_ ( self : Tuple ): if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def lowercase_ ( self : Optional[Any] , __snake_case : Dict , __snake_case : Dict , __snake_case : int ): if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token a : int = model(**__snake_case , use_cache=__snake_case )[0] a : Union[str, Any] = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models a , a : Optional[Any] = model(**__snake_case , labels=__snake_case , use_cache=__snake_case )[:2] else: # compute label smoothed loss a : List[str] = model(**__snake_case , use_cache=__snake_case )[0] a : Any = torch.nn.functional.log_softmax(__snake_case , dim=-1 ) a , a : Optional[Any] = self.loss_fn(__snake_case , __snake_case , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def lowercase_ ( self : List[str] , __snake_case : Tuple , __snake_case : str ): a : int = inputs.pop('labels' ) a , a : Dict = self._compute_loss(__snake_case , __snake_case , __snake_case ) return loss def lowercase_ ( self : Tuple , __snake_case : nn.Module , __snake_case : Dict[str, Union[torch.Tensor, Any]] , __snake_case : bool , __snake_case : Optional[List[str]] = None , ): a : str = self._prepare_inputs(__snake_case ) a : Optional[Any] = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: a : int = self.model.generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , **__snake_case , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: a : Union[str, Any] = self._pad_tensors_to_max_len(__snake_case , gen_kwargs['max_length'] ) a : Tuple = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data a , a : int = self._compute_loss(__snake_case , __snake_case , __snake_case ) a : List[str] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) a : Tuple = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: a : Optional[Any] = self._pad_tensors_to_max_len(__snake_case , gen_kwargs['max_length'] ) return (loss, logits, labels) def lowercase_ ( self : Any , __snake_case : Dict , __snake_case : List[Any] ): # If PAD token is not defined at least EOS token has to be defined a : Any = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F""" padded to `max_length`={max_length}""" ) a : str = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) a : Union[str, Any] = tensor return padded_tensor
297
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase: Union[str, Any] = { 'configuration_speecht5': [ 'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP', 'SpeechT5Config', 'SpeechT5HifiGanConfig', ], 'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'], 'processing_speecht5': ['SpeechT5Processor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[Any] = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Any = [ 'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'SpeechT5ForSpeechToText', 'SpeechT5ForSpeechToSpeech', 'SpeechT5ForTextToSpeech', 'SpeechT5Model', 'SpeechT5PreTrainedModel', 'SpeechT5HifiGan', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase: Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
1
"""simple docstring""" from collections.abc import Generator def __lowercase ( ): snake_case_, snake_case_ : List[str] = 0, 1 while True: snake_case_, snake_case_ : List[str] = b, a + b yield b def __lowercase ( _a = 1_000 ): snake_case_ : Tuple = 1 snake_case_ : List[str] = fibonacci_generator() while len(str(next(_a ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
155
"""simple docstring""" def __lowercase ( _a , _a ): return base * power(_a , (exponent - 1) ) if exponent else 1 if __name__ == "__main__": print('''Raise base to the power of exponent using recursion...''') lowercase__ : Optional[Any] = int(input('''Enter the base: ''').strip()) lowercase__ : int = int(input('''Enter the exponent: ''').strip()) lowercase__ : int = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents lowercase__ : Any = 1 / result print(f'{base} to the power of {exponent} is {result}')
155
1
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs __snake_case : List[Any] =imread(R'digital_image_processing/image_data/lena_small.jpg') __snake_case : List[str] =cvtColor(img, COLOR_BGR2GRAY) def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = cn.convert_to_negative(lowerCamelCase_) # assert negative_img array for at least one True assert negative_img.any() def lowerCAmelCase__ ( ): '''simple docstring''' with Image.open('''digital_image_processing/image_data/lena_small.jpg''') as img: # Work around assertion for response assert str(cc.change_contrast(lowerCamelCase_ ,110)).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''') def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = canny.gen_gaussian_kernel(9 ,sigma=1.4) # Assert ambiguous array assert resp.all() def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = imread('''digital_image_processing/image_data/lena_small.jpg''' ,0) # assert ambiguous array for all == True assert canny_img.all() lowerCAmelCase__ : Dict = canny.canny(lowerCamelCase_) # assert canny array for at least one True assert canny_array.any() def lowerCAmelCase__ ( ): '''simple docstring''' assert gg.gaussian_filter(lowerCamelCase_ ,5 ,sigma=0.9).all() def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : List[Any] = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]) lowerCAmelCase__ : str = conv.img_convolve(lowerCamelCase_ ,lowerCamelCase_).astype(lowerCamelCase_) assert res.any() def lowerCAmelCase__ ( ): '''simple docstring''' assert med.median_filter(lowerCamelCase_ ,3).any() def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ , lowerCAmelCase__ : Any = sob.sobel_filter(lowerCamelCase_) assert grad.any() and theta.any() def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : List[Any] = sp.make_sepia(lowerCamelCase_ ,20) assert sepia.all() def lowerCAmelCase__ ( lowerCamelCase_ : str = "digital_image_processing/image_data/lena_small.jpg"): '''simple docstring''' lowerCAmelCase__ : Optional[int] = bs.Burkes(imread(lowerCamelCase_ ,1) ,120) burkes.process() assert burkes.output_img.any() def lowerCAmelCase__ ( lowerCamelCase_ : str = "digital_image_processing/image_data/lena_small.jpg" ,): '''simple docstring''' lowerCAmelCase__ : List[Any] = rs.NearestNeighbour(imread(lowerCamelCase_ ,1) ,400 ,200) nn.process() assert nn.output.any() def lowerCAmelCase__ ( ): '''simple docstring''' lowerCAmelCase__ : int = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. lowerCAmelCase__ : List[str] = imread(lowerCamelCase_ ,0) # Test for get_neighbors_pixel function() return not None lowerCAmelCase__ : List[Any] = 0 lowerCAmelCase__ : Union[str, Any] = 0 lowerCAmelCase__ : Dict = image[x_coordinate][y_coordinate] lowerCAmelCase__ : Tuple = lbp.get_neighbors_pixel( lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image lowerCAmelCase__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1])) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 ,image.shape[0]): for j in range(0 ,image.shape[1]): lowerCAmelCase__ : int = lbp.local_binary_value(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_) assert lbp_image.any()
129
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCamelCase__ ( lowerCamelCase__): '''simple docstring''' snake_case_ =(DPMSolverSDEScheduler,) snake_case_ =10 def lowerCAmelCase__ (self ,**__lowerCamelCase ) -> List[str]: """simple docstring""" lowerCAmelCase__ : List[str] = { '''num_train_timesteps''': 11_00, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''noise_sampler_seed''': 0, } config.update(**__lowerCamelCase ) return config def lowerCAmelCase__ (self ) -> int: """simple docstring""" for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=__lowerCamelCase ) def lowerCAmelCase__ (self ) -> Optional[Any]: """simple docstring""" for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] ,[0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=__lowerCamelCase ,beta_end=__lowerCamelCase ) def lowerCAmelCase__ (self ) -> Union[str, Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__lowerCamelCase ) def lowerCAmelCase__ (self ) -> Optional[Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__lowerCamelCase ) def lowerCAmelCase__ (self ) -> int: """simple docstring""" lowerCAmelCase__ : List[str] = self.scheduler_classes[0] lowerCAmelCase__ : str = self.get_scheduler_config() lowerCAmelCase__ : Optional[Any] = scheduler_class(**__lowerCamelCase ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ : Union[str, Any] = self.dummy_model() lowerCAmelCase__ : Tuple = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ : Union[str, Any] = sample.to(__lowerCamelCase ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ : Dict = scheduler.scale_model_input(__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : Any = model(__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : List[Any] = scheduler.step(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : Optional[int] = output.prev_sample lowerCAmelCase__ : List[Any] = torch.sum(torch.abs(__lowerCamelCase ) ) lowerCAmelCase__ : Dict = torch.mean(torch.abs(__lowerCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_8210_4492_1875 ) < 1e-2 assert abs(result_mean.item() - 0.2178_7059_6456_5277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3521_1181_6406 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9068_9229_9652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def lowerCAmelCase__ (self ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ : Dict = self.scheduler_classes[0] lowerCAmelCase__ : Any = self.get_scheduler_config(prediction_type='''v_prediction''' ) lowerCAmelCase__ : List[Any] = scheduler_class(**__lowerCamelCase ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase__ : Optional[int] = self.dummy_model() lowerCAmelCase__ : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase__ : Tuple = sample.to(__lowerCamelCase ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase__ : Optional[Any] = scheduler.scale_model_input(__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : Optional[Any] = model(__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : Optional[int] = scheduler.step(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : Union[str, Any] = output.prev_sample lowerCAmelCase__ : Any = torch.sum(torch.abs(__lowerCamelCase ) ) lowerCAmelCase__ : Union[str, Any] = torch.mean(torch.abs(__lowerCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_1492_0043_9453 ) < 1e-2 assert abs(result_mean.item() - 0.1_6226_2890_1481_6284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_6633_6059_5703 ) < 1e-2 assert abs(result_mean.item() - 0.1_6688_3260_0116_7297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8_4875_4882_8125 ) < 1e-2 assert abs(result_mean.item() - 0.1560_5306_6253_6621 ) < 1e-3 def lowerCAmelCase__ (self ) -> List[Any]: """simple docstring""" lowerCAmelCase__ : Any = self.scheduler_classes[0] lowerCAmelCase__ : Tuple = self.get_scheduler_config() lowerCAmelCase__ : str = scheduler_class(**__lowerCamelCase ) scheduler.set_timesteps(self.num_inference_steps ,device=__lowerCamelCase ) lowerCAmelCase__ : Optional[Any] = self.dummy_model() lowerCAmelCase__ : List[Any] = self.dummy_sample_deter.to(__lowerCamelCase ) * scheduler.init_noise_sigma for t in scheduler.timesteps: lowerCAmelCase__ : List[Any] = scheduler.scale_model_input(__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : Any = model(__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : List[Any] = scheduler.step(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : List[Any] = output.prev_sample lowerCAmelCase__ : List[str] = torch.sum(torch.abs(__lowerCamelCase ) ) lowerCAmelCase__ : Dict = torch.mean(torch.abs(__lowerCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_9573_9746_0938 ) < 1e-2 assert abs(result_mean.item() - 0.2_1805_9346_0798_2635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3536_3769_5312 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9083_8241_5771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def lowerCAmelCase__ (self ) -> int: """simple docstring""" lowerCAmelCase__ : str = self.scheduler_classes[0] lowerCAmelCase__ : List[Any] = self.get_scheduler_config() lowerCAmelCase__ : Union[str, Any] = scheduler_class(**__lowerCamelCase ,use_karras_sigmas=__lowerCamelCase ) scheduler.set_timesteps(self.num_inference_steps ,device=__lowerCamelCase ) lowerCAmelCase__ : str = self.dummy_model() lowerCAmelCase__ : Union[str, Any] = self.dummy_sample_deter.to(__lowerCamelCase ) * scheduler.init_noise_sigma lowerCAmelCase__ : Union[str, Any] = sample.to(__lowerCamelCase ) for t in scheduler.timesteps: lowerCAmelCase__ : List[Any] = scheduler.scale_model_input(__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : str = model(__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : Tuple = scheduler.step(__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : str = output.prev_sample lowerCAmelCase__ : Tuple = torch.sum(torch.abs(__lowerCamelCase ) ) lowerCAmelCase__ : List[Any] = torch.mean(torch.abs(__lowerCamelCase ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_9741_3574_2188 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_6535_6445_3125 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3_1352_2338_8672 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2
129
1
"""simple docstring""" import argparse import collections import os import re import tempfile import pandas as pd from datasets import Dataset from huggingface_hub import hf_hub_download, upload_folder 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/update_metadata.py A_ : Any ='src/transformers' # This is to make sure the transformers module imported is the one in the repo. A_ : Any =direct_transformers_import(TRANSFORMERS_PATH) # Regexes that match TF/Flax/PT model names. A_ : List[str] =re.compile(R"""TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") A_ : List[Any] =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. A_ : Dict =re.compile(R"""(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)""") # Fill this with tuples (pipeline_tag, model_mapping, auto_model) A_ : Optional[Any] =[ ('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'), ('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'), ('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'), ('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'), ('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'), ('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'), ('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'), ('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'), ('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'), ( 'zero-shot-object-detection', 'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForZeroShotObjectDetection', ), ('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'), ('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'), ('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'), ('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'), ( 'table-question-answering', 'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForTableQuestionAnswering', ), ('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'), ('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'), ( 'next-sentence-prediction', 'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES', 'AutoModelForNextSentencePrediction', ), ( 'audio-frame-classification', 'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioFrameClassification', ), ('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'), ( 'document-question-answering', 'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForDocumentQuestionAnswering', ), ( 'visual-question-answering', 'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForVisualQuestionAnswering', ), ('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'), ( 'zero-shot-image-classification', 'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForZeroShotImageClassification', ), ('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'), ('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'), ('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'), ] def SCREAMING_SNAKE_CASE_ ( snake_case : Optional[Any] )-> List[Any]: _lowerCamelCase = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)' , UpperCAmelCase_ ) return [m.group(0 ) for m in matches] def SCREAMING_SNAKE_CASE_ ( )-> Any: _lowerCamelCase = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES _lowerCamelCase = { config.replace('Config' , '' ): model_type for model_type, config in config_maping_names.items() } # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. _lowerCamelCase = collections.defaultdict(UpperCAmelCase_ ) _lowerCamelCase = collections.defaultdict(UpperCAmelCase_ ) _lowerCamelCase = collections.defaultdict(UpperCAmelCase_ ) # Let's lookup through all transformers object (once) and find if models are supported by a given backend. for attr_name in dir(UpperCAmelCase_ ): _lowerCamelCase = None if _re_tf_models.match(UpperCAmelCase_ ) is not None: _lowerCamelCase = tf_models _lowerCamelCase = _re_tf_models.match(UpperCAmelCase_ ).groups()[0] elif _re_flax_models.match(UpperCAmelCase_ ) is not None: _lowerCamelCase = flax_models _lowerCamelCase = _re_flax_models.match(UpperCAmelCase_ ).groups()[0] elif _re_pt_models.match(UpperCAmelCase_ ) is not None: _lowerCamelCase = pt_models _lowerCamelCase = _re_pt_models.match(UpperCAmelCase_ ).groups()[0] if lookup_dict is not None: while len(UpperCAmelCase_ ) > 0: if attr_name in model_prefix_to_model_type: _lowerCamelCase = True break # Try again after removing the last word in the name _lowerCamelCase = ''.join(camel_case_split(UpperCAmelCase_ )[:-1] ) _lowerCamelCase = set(list(pt_models.keys() ) + list(tf_models.keys() ) + list(flax_models.keys() ) ) _lowerCamelCase = list(UpperCAmelCase_ ) all_models.sort() _lowerCamelCase = {'model_type': all_models} _lowerCamelCase = [pt_models[t] for t in all_models] _lowerCamelCase = [tf_models[t] for t in all_models] _lowerCamelCase = [flax_models[t] for t in all_models] # Now let's use the auto-mapping names to make sure _lowerCamelCase = {} for t in all_models: if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: _lowerCamelCase = 'AutoProcessor' elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: _lowerCamelCase = 'AutoTokenizer' elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: _lowerCamelCase = 'AutoFeatureExtractor' else: # Default to AutoTokenizer if a model has nothing, for backward compatibility. _lowerCamelCase = 'AutoTokenizer' _lowerCamelCase = [processors[t] for t in all_models] return pd.DataFrame(UpperCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( snake_case : Optional[int] )-> Dict: _lowerCamelCase = [ transformers_module.models.auto.modeling_auto, transformers_module.models.auto.modeling_tf_auto, transformers_module.models.auto.modeling_flax_auto, ] for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: _lowerCamelCase = [model_mapping, f'TF_{model_mapping}', f'FLAX_{model_mapping}'] _lowerCamelCase = [auto_class, f'TF_{auto_class}', f'Flax_{auto_class}'] # Loop through all three frameworks for module, cls, mapping in zip(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): # The type of pipeline may not exist in this framework if not hasattr(UpperCAmelCase_ , UpperCAmelCase_ ): continue # First extract all model_names _lowerCamelCase = [] for name in getattr(UpperCAmelCase_ , UpperCAmelCase_ ).values(): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): model_names.append(UpperCAmelCase_ ) else: model_names.extend(list(UpperCAmelCase_ ) ) # Add pipeline tag and auto model class for those models table.update({model_name: (pipeline_tag, cls) for model_name in model_names} ) return table def SCREAMING_SNAKE_CASE_ ( snake_case : str , snake_case : str )-> List[Any]: _lowerCamelCase = get_frameworks_table() _lowerCamelCase = Dataset.from_pandas(UpperCAmelCase_ ) _lowerCamelCase = hf_hub_download( 'huggingface/transformers-metadata' , 'pipeline_tags.json' , repo_type='dataset' , token=UpperCAmelCase_ ) _lowerCamelCase = Dataset.from_json(UpperCAmelCase_ ) _lowerCamelCase = { tags_dataset[i]['model_class']: (tags_dataset[i]['pipeline_tag'], tags_dataset[i]['auto_class']) for i in range(len(UpperCAmelCase_ ) ) } _lowerCamelCase = update_pipeline_and_auto_class_table(UpperCAmelCase_ ) # Sort the model classes to avoid some nondeterministic updates to create false update commits. _lowerCamelCase = sorted(table.keys() ) _lowerCamelCase = pd.DataFrame( { 'model_class': model_classes, 'pipeline_tag': [table[m][0] for m in model_classes], 'auto_class': [table[m][1] for m in model_classes], } ) _lowerCamelCase = Dataset.from_pandas(UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: frameworks_dataset.to_json(os.path.join(UpperCAmelCase_ , 'frameworks.json' ) ) tags_dataset.to_json(os.path.join(UpperCAmelCase_ , 'pipeline_tags.json' ) ) if commit_sha is not None: _lowerCamelCase = ( f'Update with commit {commit_sha}\n\nSee: ' f'https://github.com/huggingface/transformers/commit/{commit_sha}' ) else: _lowerCamelCase = 'Update' upload_folder( repo_id='huggingface/transformers-metadata' , folder_path=UpperCAmelCase_ , repo_type='dataset' , token=UpperCAmelCase_ , commit_message=UpperCAmelCase_ , ) def SCREAMING_SNAKE_CASE_ ( )-> Tuple: _lowerCamelCase = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} _lowerCamelCase = transformers_module.pipelines.SUPPORTED_TASKS _lowerCamelCase = [] for key in pipeline_tasks: if key not in in_table: _lowerCamelCase = pipeline_tasks[key]['pt'] if isinstance(UpperCAmelCase_ , (list, tuple) ): _lowerCamelCase = model[0] _lowerCamelCase = model.__name__ if model not in in_table.values(): missing.append(UpperCAmelCase_ ) if len(UpperCAmelCase_ ) > 0: _lowerCamelCase = ', '.join(UpperCAmelCase_ ) raise ValueError( 'The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside ' f'`utils/update_metadata.py`: {msg}. Please add them!' ) if __name__ == "__main__": A_ : Union[str, Any] =argparse.ArgumentParser() parser.add_argument("""--token""", type=str, help="""The token to use to push to the transformers-metadata dataset.""") parser.add_argument("""--commit_sha""", type=str, help="""The sha of the commit going with this update.""") parser.add_argument("""--check-only""", action="""store_true""", help="""Activate to just check all pipelines are present.""") A_ : Optional[int] =parser.parse_args() if args.check_only: check_pipeline_tags() else: update_metadata(args.token, args.commit_sha)
353
"""simple docstring""" import mpmath # for roots of unity import numpy as np class __a : def __init__( self , a__=None , a__=None ): # Input as list _lowerCamelCase = list(poly_a or [0] )[:] _lowerCamelCase = list(poly_b or [0] )[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _lowerCamelCase = len(self.polyA ) while self.polyB[-1] == 0: self.polyB.pop() _lowerCamelCase = len(self.polyB ) # Add 0 to make lengths equal a power of 2 _lowerCamelCase = int( 2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) ) while len(self.polyA ) < self.c_max_length: self.polyA.append(0 ) while len(self.polyB ) < self.c_max_length: self.polyB.append(0 ) # A complex root used for the fourier transform _lowerCamelCase = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) ) # The product _lowerCamelCase = self.__multiply() def snake_case_ ( self , a__ ): _lowerCamelCase = [[x] for x in self.polyA] if which == 'A' else [[x] for x in self.polyB] # Corner case if len(a__ ) <= 1: return dft[0] # _lowerCamelCase = self.c_max_length // 2 while next_ncol > 0: _lowerCamelCase = [[] for i in range(a__ )] _lowerCamelCase = self.root**next_ncol # First half of next step _lowerCamelCase = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(a__ ): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] ) current_root *= root # Second half of next step _lowerCamelCase = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(a__ ): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] ) current_root *= root # Update _lowerCamelCase = new_dft _lowerCamelCase = next_ncol // 2 return dft[0] def snake_case_ ( self ): _lowerCamelCase = self.__dft('A' ) _lowerCamelCase = self.__dft('B' ) _lowerCamelCase = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]] del dft_a del dft_b # Corner Case if len(inverce_c[0] ) <= 1: return inverce_c[0] # Inverse DFT _lowerCamelCase = 2 while next_ncol <= self.c_max_length: _lowerCamelCase = [[] for i in range(a__ )] _lowerCamelCase = self.root ** (next_ncol // 2) _lowerCamelCase = 1 # First half of next step for j in range(self.c_max_length // next_ncol ): for i in range(next_ncol // 2 ): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update _lowerCamelCase = new_inverse_c next_ncol *= 2 # Unpack _lowerCamelCase = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1J for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self ): _lowerCamelCase = 'A = ' + ' + '.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A] ) ) _lowerCamelCase = 'B = ' + ' + '.join( F'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B] ) ) _lowerCamelCase = 'A*B = ' + ' + '.join( F'{coef}*x^{i}' for coef, i in enumerate(self.product ) ) return F'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
80
0
"""simple docstring""" import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __UpperCAmelCase = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class _SCREAMING_SNAKE_CASE ( datasets.BuilderConfig ): UpperCAmelCase_ :Optional[datasets.Features] = None def _snake_case ( lowercase__ : "pyspark.sql.DataFrame" , lowercase__ : List[int] , ) -> Any: '''simple docstring''' import pyspark def generate_fn(): lowerCAmelCase_ :List[Any] = df.select("""*""" , pyspark.sql.functions.spark_partition_id().alias("""part_id""" ) ) for partition_id in partition_order: lowerCAmelCase_ :Optional[int] = df_with_partition_id.select("""*""" ).where(f"""part_id = {partition_id}""" ).drop("""part_id""" ) lowerCAmelCase_ :Optional[Any] = partition_df.collect() lowerCAmelCase_ :Dict = 0 for row in rows: yield f"""{partition_id}_{row_id}""", row.asDict() row_id += 1 return generate_fn class _SCREAMING_SNAKE_CASE ( _BaseExamplesIterable ): def __init__( self , __A , __A=None , ) -> Optional[Any]: lowerCAmelCase_ :List[str] = df lowerCAmelCase_ :str = partition_order or range(self.df.rdd.getNumPartitions() ) lowerCAmelCase_ :int = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Tuple: yield from self.generate_examples_fn() def __lowerCAmelCase ( self , __A ) -> "SparkExamplesIterable": lowerCAmelCase_ :List[Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(__A ) return SparkExamplesIterable(self.df , partition_order=__A ) def __lowerCAmelCase ( self , __A , __A ) -> "SparkExamplesIterable": lowerCAmelCase_ :Optional[Any] = self.split_shard_indices_by_worker(__A , __A ) return SparkExamplesIterable(self.df , partition_order=__A ) @property def __lowerCAmelCase ( self ) -> int: return len(self.partition_order ) class _SCREAMING_SNAKE_CASE ( datasets.DatasetBuilder ): UpperCAmelCase_ :Optional[Any] = SparkConfig def __init__( self , __A , __A = None , __A = None , **__A , ) -> int: import pyspark lowerCAmelCase_ :Tuple = pyspark.sql.SparkSession.builder.getOrCreate() lowerCAmelCase_ :Union[str, Any] = df lowerCAmelCase_ :Optional[Any] = working_dir super().__init__( cache_dir=__A , config_name=str(self.df.semanticHash() ) , **__A , ) def __lowerCAmelCase ( self ) -> int: # Returns the path of the created file. def create_cache_and_write_probe(__A ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=__A ) lowerCAmelCase_ :Union[str, Any] = os.path.join(self._cache_dir , """fs_test""" + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(__A , """a""" ) return [probe_file] if self._spark.conf.get("""spark.master""" , """""" ).startswith("""local""" ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: lowerCAmelCase_ :int = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(__A ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( """When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir""" ) def __lowerCAmelCase ( self ) -> Optional[Any]: return datasets.DatasetInfo(features=self.config.features ) def __lowerCAmelCase ( self , __A ) -> Any: return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __lowerCAmelCase ( self , __A ) -> Union[str, Any]: import pyspark def get_arrow_batch_size(__A ): for batch in it: yield pa.RecordBatch.from_pydict({"""batch_bytes""": [batch.nbytes]} ) lowerCAmelCase_ :Tuple = self.df.count() lowerCAmelCase_ :Union[str, Any] = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. lowerCAmelCase_ :Tuple = ( self.df.limit(__A ) .repartition(1 ) .mapInArrow(__A , """batch_bytes: long""" ) .agg(pyspark.sql.functions.sum("""batch_bytes""" ).alias("""sample_bytes""" ) ) .collect()[0] .sample_bytes / sample_num_rows ) lowerCAmelCase_ :List[Any] = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. lowerCAmelCase_ :str = min(__A , int(approx_total_size / max_shard_size ) ) lowerCAmelCase_ :Optional[int] = self.df.repartition(__A ) def __lowerCAmelCase ( self , __A , __A , __A , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: import pyspark lowerCAmelCase_ :Optional[int] = ParquetWriter if file_format == """parquet""" else ArrowWriter lowerCAmelCase_ :Dict = os.path.join(self._working_dir , os.path.basename(__A ) ) if self._working_dir else fpath lowerCAmelCase_ :Optional[Any] = file_format == """parquet""" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. lowerCAmelCase_ :List[str] = self.config.features lowerCAmelCase_ :List[Any] = self._writer_batch_size lowerCAmelCase_ :str = self._fs.storage_options def write_arrow(__A ): # Within the same SparkContext, no two task attempts will share the same attempt ID. lowerCAmelCase_ :Dict = pyspark.TaskContext().taskAttemptId() lowerCAmelCase_ :int = next(__A , __A ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) lowerCAmelCase_ :Tuple = 0 lowerCAmelCase_ :List[str] = writer_class( features=__A , path=working_fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , writer_batch_size=__A , storage_options=__A , embed_local_files=__A , ) lowerCAmelCase_ :int = pa.Table.from_batches([first_batch] ) writer.write_table(__A ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: lowerCAmelCase_ , lowerCAmelCase_ :int = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) shard_id += 1 lowerCAmelCase_ :int = writer_class( features=writer._features , path=working_fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , writer_batch_size=__A , storage_options=__A , embed_local_files=__A , ) lowerCAmelCase_ :Any = pa.Table.from_batches([batch] ) writer.write_table(__A ) if writer._num_bytes > 0: lowerCAmelCase_ , lowerCAmelCase_ :Any = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(__A ) ): lowerCAmelCase_ :Optional[int] = os.path.join(os.path.dirname(__A ) , os.path.basename(__A ) ) shutil.move(__A , __A ) lowerCAmelCase_ :Optional[int] = ( self.df.mapInArrow(__A , """task_id: long, num_examples: long, num_bytes: long""" ) .groupBy("""task_id""" ) .agg( pyspark.sql.functions.sum("""num_examples""" ).alias("""total_num_examples""" ) , pyspark.sql.functions.sum("""num_bytes""" ).alias("""total_num_bytes""" ) , pyspark.sql.functions.count("""num_bytes""" ).alias("""num_shards""" ) , pyspark.sql.functions.collect_list("""num_examples""" ).alias("""shard_lengths""" ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __lowerCAmelCase ( self , __A , __A = "arrow" , __A = None , __A = None , **__A , ) -> Any: self._validate_cache_dir() lowerCAmelCase_ :Tuple = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(__A ) lowerCAmelCase_ :Optional[Any] = not is_remote_filesystem(self._fs ) lowerCAmelCase_ :Tuple = os.path.join if is_local else posixpath.join lowerCAmelCase_ :List[Any] = """-TTTTT-SSSSS-of-NNNNN""" lowerCAmelCase_ :int = f"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}""" lowerCAmelCase_ :Optional[Any] = path_join(self._output_dir , __A ) lowerCAmelCase_ :Dict = 0 lowerCAmelCase_ :Any = 0 lowerCAmelCase_ :str = 0 lowerCAmelCase_ :Union[str, Any] = [] lowerCAmelCase_ :List[str] = [] for task_id, content in self._prepare_split_single(__A , __A , __A ): ( ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ) :List[Any] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(__A ) lowerCAmelCase_ :Optional[int] = total_num_examples lowerCAmelCase_ :Tuple = total_num_bytes # should rename everything at the end logger.debug(f"""Renaming {total_shards} shards.""" ) if total_shards > 1: lowerCAmelCase_ :Any = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. lowerCAmelCase_ :List[str] = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( __A , __A , __A , ): rename( __A , fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , fpath.replace("""TTTTT-SSSSS""" , f"""{global_shard_id:05d}""" ).replace("""NNNNN""" , f"""{total_shards:05d}""" ) , ) lowerCAmelCase_ :Tuple = [] lowerCAmelCase_ :Tuple = 0 for i in range(len(__A ) ): lowerCAmelCase_ , lowerCAmelCase_ :Dict = task_id_and_num_shards[i] for shard_id in range(__A ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(__A , len(__A ) ).map(lambda __A : _rename_shard(*__A ) ).collect() else: # don't use any pattern lowerCAmelCase_ :Optional[int] = 0 lowerCAmelCase_ :Optional[Any] = task_id_and_num_shards[0][0] self._rename( fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , fpath.replace(__A , """""" ) , ) def __lowerCAmelCase ( self , __A , ) -> SparkExamplesIterable: return SparkExamplesIterable(self.df )
84
"""simple docstring""" from __future__ import annotations __a = 10 def A_ ( _lowercase ): '''simple docstring''' snake_case_ :Union[str, Any] = 1 snake_case_ :List[str] = max(_lowercase ) while placement <= max_digit: # declare and initialize empty buckets snake_case_ :list[list] = [[] for _ in range(_lowercase )] # split list_of_ints between the buckets for i in list_of_ints: snake_case_ :Any = int((i / placement) % RADIX ) buckets[tmp].append(_lowercase ) # put each buckets' contents into list_of_ints snake_case_ :Optional[Any] = 0 for b in range(_lowercase ): for i in buckets[b]: snake_case_ :Union[str, Any] = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
66
0
'''simple docstring''' import logging import os from .state import PartialState class UpperCamelCase_ (logging.LoggerAdapter ): """simple docstring""" @staticmethod def _a ( _lowerCamelCase : Union[str, Any] ): """simple docstring""" A_ : str = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def _a ( self : List[Any] , _lowerCamelCase : Dict , _lowerCamelCase : str , *_lowerCamelCase : Tuple , **_lowerCamelCase : str ): """simple docstring""" if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) A_ : Dict = kwargs.pop('''main_process_only''' , _lowerCamelCase ) A_ : List[str] = kwargs.pop('''in_order''' , _lowerCamelCase ) if self.isEnabledFor(_lowerCamelCase ): if self._should_log(_lowerCamelCase ): A_ ,A_ : Union[str, Any] = self.process(_lowerCamelCase , _lowerCamelCase ) self.logger.log(_lowerCamelCase , _lowerCamelCase , *_lowerCamelCase , **_lowerCamelCase ) elif in_order: A_ : Any = PartialState() for i in range(state.num_processes ): if i == state.process_index: A_ ,A_ : str = self.process(_lowerCamelCase , _lowerCamelCase ) self.logger.log(_lowerCamelCase , _lowerCamelCase , *_lowerCamelCase , **_lowerCamelCase ) state.wait_for_everyone() def snake_case__ ( lowerCamelCase__ : str , lowerCamelCase__ : str = None ) -> str: if log_level is None: A_ : int = os.environ.get('''ACCELERATE_LOG_LEVEL''' , lowerCamelCase__ ) A_ : int = logging.getLogger(lowerCamelCase__ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(lowerCamelCase__ , {} )
4
'''simple docstring''' from __future__ import annotations def snake_case__ ( lowerCamelCase__ : list[int] , lowerCamelCase__ : int ) -> list[int]: A_ : int = 0 A_ : str = len(lowerCamelCase__ ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: A_ : Tuple = i + 1 else: A_ : List[str] = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(F'{two_pointer([2, 7, 11, 15], 9) = }')
4
1
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging __lowerCamelCase = logging.get_logger(__name__) def UpperCAmelCase ( ): """simple docstring""" A__ = os.getenv('SM_HP_MP_PARAMETERS' , '{}' ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. A__ = json.loads(__lowerCamelCase ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. A__ = os.getenv('SM_FRAMEWORK_PARAMS' , '{}' ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". A__ = json.loads(__lowerCamelCase ) if not mpi_options.get('sagemaker_mpi_enabled' , __lowerCamelCase ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec('smdistributed' ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase__( lowercase__ ): lowerCAmelCase__ : str = field( default='' , metadata={'help': 'Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'} , ) def snake_case__ ( self ) -> List[str]: super().__post_init__() warnings.warn( '`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use ' '`TrainingArguments` instead.' ,__lowercase ,) @cached_property def snake_case__ ( self ) -> "torch.device": logger.info('PyTorch: setting up devices' ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( 'torch.distributed process group is initialized, but local_rank == -1. ' 'In order to use Torch DDP, launch your script with `python -m torch.distributed.launch' ) if self.no_cuda: A__ = torch.device('cpu' ) A__ = 0 elif is_sagemaker_model_parallel_available(): A__ = smp.local_rank() A__ = torch.device('cuda' ,__lowercase ) A__ = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend='smddp' ,timeout=self.ddp_timeout_delta ) A__ = int(os.getenv('SMDATAPARALLEL_LOCAL_RANK' ) ) A__ = torch.device('cuda' ,self.local_rank ) A__ = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 A__ = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu' ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. A__ = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend='nccl' ,timeout=self.ddp_timeout_delta ) A__ = torch.device('cuda' ,self.local_rank ) A__ = 1 if device.type == "cuda": torch.cuda.set_device(__lowercase ) return device @property def snake_case__ ( self ) -> List[str]: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def snake_case__ ( self ) -> int: return not is_sagemaker_model_parallel_available() @property def snake_case__ ( self ) -> List[Any]: return False
221
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a : Union[str, Any] = {"configuration_timm_backbone": ["TimmBackboneConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Tuple = ["TimmBackbone"] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys a : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
114
0
"""simple docstring""" import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def __A (_SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=1026 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="data/tokenized_stories_train_wikitext103.jbl" , _SCREAMING_SNAKE_CASE="igf_context_pairs.jbl" , ) ->Optional[int]: """simple docstring""" set_seed(3 ) # generate train_data and objective_set lowerCAmelCase__ , lowerCAmelCase__ :int = generate_datasets( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , number=_SCREAMING_SNAKE_CASE , min_len=1026 , trim=_SCREAMING_SNAKE_CASE ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? lowerCAmelCase__ :List[str] = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu' ) # load pretrained model lowerCAmelCase__ :Union[str, Any] = load_gpta('gpt2' ).to(_SCREAMING_SNAKE_CASE ) print('computing perplexity on objective set' ) lowerCAmelCase__ :Tuple = compute_perplexity(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).item() print('perplexity on objective set:' , _SCREAMING_SNAKE_CASE ) # collect igf pairs and save to file demo.jbl collect_objective_set(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=15 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE="igf_model.pt" , ) ->int: """simple docstring""" set_seed(42 ) # Load pre-trained model lowerCAmelCase__ :List[Any] = GPTaLMHeadModel.from_pretrained('gpt2' ) # Initialize secondary learner to use embedding weights of model lowerCAmelCase__ :List[str] = SecondaryLearner(_SCREAMING_SNAKE_CASE ) # Train secondary learner lowerCAmelCase__ :Union[str, Any] = train_secondary_learner( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_epochs=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , eval_freq=100 , igf_model_path=_SCREAMING_SNAKE_CASE , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=1000 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=recopy_gpta , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE="gpt2_finetuned.pt" , ) ->Union[str, Any]: """simple docstring""" lowerCAmelCase__ :Union[str, Any] = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu' ) lowerCAmelCase__ :Optional[int] = RandomSampler(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = DataLoader(_SCREAMING_SNAKE_CASE , sampler=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = max_steps // (len(_SCREAMING_SNAKE_CASE )) + 1 lowerCAmelCase__ :str = 0 lowerCAmelCase__ :int = torch.zeros((1, context_len) , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = recopy_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) model.train() if secondary_learner is not None: secondary_learner.to(_SCREAMING_SNAKE_CASE ) secondary_learner.eval() lowerCAmelCase__ :Union[str, Any] = [] lowerCAmelCase__ :List[str] = 0 lowerCAmelCase__ :Optional[int] = [] lowerCAmelCase__ :Any = [] # Compute the performance of the transformer model at the beginning lowerCAmelCase__ :Any = compute_perplexity(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) test_perps.append(_SCREAMING_SNAKE_CASE ) print('Test perplexity, step' , _SCREAMING_SNAKE_CASE , ':' , _SCREAMING_SNAKE_CASE ) for epoch in range(int(_SCREAMING_SNAKE_CASE ) ): for step, example in enumerate(_SCREAMING_SNAKE_CASE ): torch.cuda.empty_cache() lowerCAmelCase__ :Tuple = random.randint(0 , example.size(2 ) - context_len - 1 ) lowerCAmelCase__ :str = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() lowerCAmelCase__ :Any = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Union[str, Any] = True if secondary_learner is not None: lowerCAmelCase__ :Union[str, Any] = secondary_learner.forward( torch.tensor(_SCREAMING_SNAKE_CASE , dtype=torch.long , device=_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) )[0].item() observed_qs.append(float(_SCREAMING_SNAKE_CASE ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: lowerCAmelCase__ :int = -1 if predicted_q < threshold: lowerCAmelCase__ :str = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) lowerCAmelCase__ :Optional[int] = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() lowerCAmelCase__ :List[str] = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: lowerCAmelCase__ :Dict = compute_perplexity(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) test_perps.append(_SCREAMING_SNAKE_CASE ) print('Test perplexity, step' , _SCREAMING_SNAKE_CASE , ':' , _SCREAMING_SNAKE_CASE ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def __A () ->Any: """simple docstring""" lowerCAmelCase__ :Any = argparse.ArgumentParser(description='Fine-tune a transformer model with IGF on a language modeling task' ) # Required parameters parser.add_argument( '--data_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The input data dir. Should contain data files for WikiText.' , ) parser.add_argument( '--model_name_or_path' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--data_file' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help=( 'A jbl file containing tokenized data which can be split as objective dataset, ' 'train_dataset and test_dataset.' ) , ) parser.add_argument( '--igf_data_file' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help='A jbl file containing the context and information gain pairs to train secondary learner.' , ) parser.add_argument( '--output_dir' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help='The output directory where the final fine-tuned model is stored.' , ) parser.add_argument( '--tokenizer_name' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Pretrained tokenizer name or path if not the same as model_name' , ) parser.add_argument('--seed' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help='A seed for reproducible training.' ) parser.add_argument( '--context_len' , default=32 , type=_SCREAMING_SNAKE_CASE , help=( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) , ) parser.add_argument( '--size_objective_set' , default=100 , type=_SCREAMING_SNAKE_CASE , help='number of articles that are long enough to be used as our objective set' , ) parser.add_argument( '--eval_freq' , default=100 , type=_SCREAMING_SNAKE_CASE , help='secondary model evaluation is triggered at eval_freq' ) parser.add_argument('--max_steps' , default=1000 , type=_SCREAMING_SNAKE_CASE , help='To calculate training epochs' ) parser.add_argument( '--secondary_learner_batch_size' , default=128 , type=_SCREAMING_SNAKE_CASE , help='batch size of training data for secondary learner' , ) parser.add_argument( '--batch_size' , default=16 , type=_SCREAMING_SNAKE_CASE , help='batch size of training data of language model(gpt2) ' ) parser.add_argument( '--eval_interval' , default=10 , type=_SCREAMING_SNAKE_CASE , help=( 'decay the selectivity of our secondary learner filter from' '1 standard deviation above average to 1 below average after 10 batches' ) , ) parser.add_argument( '--number' , default=100 , type=_SCREAMING_SNAKE_CASE , help='The number of examples split to be used as objective_set/test_data' ) parser.add_argument( '--min_len' , default=1026 , type=_SCREAMING_SNAKE_CASE , help='The minimum length of the article to be used as objective set' ) parser.add_argument( '--secondary_learner_max_epochs' , default=15 , type=_SCREAMING_SNAKE_CASE , help='number of epochs to train secondary learner' ) parser.add_argument('--trim' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='truncate the example if it exceeds context length' ) parser.add_argument( '--threshold' , default=1.0 , type=_SCREAMING_SNAKE_CASE , help=( 'The threshold value used by secondary learner to filter the train_data and allow only' ' informative data as input to the model' ) , ) parser.add_argument('--finetuned_model_name' , default='gpt2_finetuned.pt' , type=_SCREAMING_SNAKE_CASE , help='finetuned_model_name' ) parser.add_argument( '--recopy_model' , default=_SCREAMING_SNAKE_CASE , type=_SCREAMING_SNAKE_CASE , help='Reset the model to the original pretrained GPT-2 weights after each iteration' , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1026 , trim=_SCREAMING_SNAKE_CASE , data_file='data/tokenized_stories_train_wikitext103.jbl' , igf_data_file='igf_context_pairs.jbl' , ) # Load train data for secondary learner lowerCAmelCase__ :Dict = joblib.load('data/IGF_values.jbl' ) # Train secondary learner lowerCAmelCase__ :Optional[int] = training_secondary_learner( _SCREAMING_SNAKE_CASE , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path='igf_model.pt' , ) # load pretrained gpt2 model lowerCAmelCase__ :List[str] = GPTaLMHeadModel.from_pretrained('gpt2' ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = generate_datasets( context_len=32 , file='data/tokenized_stories_train_wikitext103.jbl' , number=100 , min_len=1026 , trim=_SCREAMING_SNAKE_CASE ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , context_len=32 , max_steps=1000 , batch_size=16 , threshold=1.0 , recopy_model=_SCREAMING_SNAKE_CASE , secondary_learner=_SCREAMING_SNAKE_CASE , eval_interval=10 , finetuned_model_name='gpt2_finetuned.pt' , ) if __name__ == "__main__": main()
254
"""simple docstring""" from pathlib import Path import fire def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = Path(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = Path(_SCREAMING_SNAKE_CASE ) dest_dir.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) for path in src_dir.iterdir(): lowerCAmelCase__ :Union[str, Any] = [x.rstrip() for x in list(path.open().readlines() )][:n] lowerCAmelCase__ :Tuple = dest_dir.joinpath(path.name ) print(_SCREAMING_SNAKE_CASE ) dest_path.open('w' ).write('\n'.join(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": fire.Fire(minify)
254
1
"""simple docstring""" import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A ( __lowerCamelCase , unittest.TestCase ): _UpperCamelCase : Union[str, Any] = CodeGenTokenizer _UpperCamelCase : Optional[Any] = CodeGenTokenizerFast _UpperCamelCase : Union[str, Any] = True _UpperCamelCase : Union[str, Any] = {"""add_prefix_space""": True} _UpperCamelCase : Any = False def __A ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _lowerCAmelCase : List[str] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', '''<|endoftext|>''', ] _lowerCAmelCase : str = dict(zip(__lowercase , range(len(__lowercase ) ) ) ) _lowerCAmelCase : Tuple = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] _lowerCAmelCase : Any = {'''unk_token''': '''<unk>'''} _lowerCAmelCase : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) _lowerCAmelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__lowercase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__lowercase ) ) def __A ( self , **a__ ): kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname , **__lowercase ) def __A ( self , **a__ ): kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **__lowercase ) def __A ( self , a__ ): _lowerCAmelCase : Union[str, Any] = '''lower newer''' _lowerCAmelCase : Tuple = '''lower newer''' return input_text, output_text def __A ( self ): _lowerCAmelCase : str = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) _lowerCAmelCase : str = '''lower newer''' _lowerCAmelCase : Dict = ['''\u0120low''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] _lowerCAmelCase : Union[str, Any] = tokenizer.tokenize(__lowercase , add_prefix_space=__lowercase ) self.assertListEqual(__lowercase , __lowercase ) _lowerCAmelCase : List[str] = tokens + [tokenizer.unk_token] _lowerCAmelCase : int = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowercase ) , __lowercase ) def __A ( self ): if not self.test_rust_tokenizer: return _lowerCAmelCase : List[Any] = self.get_tokenizer() _lowerCAmelCase : List[Any] = self.get_rust_tokenizer(add_prefix_space=__lowercase ) _lowerCAmelCase : Tuple = '''lower newer''' # Testing tokenization _lowerCAmelCase : int = tokenizer.tokenize(__lowercase , add_prefix_space=__lowercase ) _lowerCAmelCase : str = rust_tokenizer.tokenize(__lowercase ) self.assertListEqual(__lowercase , __lowercase ) # Testing conversion to ids without special tokens _lowerCAmelCase : Tuple = tokenizer.encode(__lowercase , add_special_tokens=__lowercase , add_prefix_space=__lowercase ) _lowerCAmelCase : Optional[int] = rust_tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) self.assertListEqual(__lowercase , __lowercase ) # Testing conversion to ids with special tokens _lowerCAmelCase : Any = self.get_rust_tokenizer(add_prefix_space=__lowercase ) _lowerCAmelCase : Tuple = tokenizer.encode(__lowercase , add_prefix_space=__lowercase ) _lowerCAmelCase : List[Any] = rust_tokenizer.encode(__lowercase ) self.assertListEqual(__lowercase , __lowercase ) # Testing the unknown token _lowerCAmelCase : Tuple = tokens + [rust_tokenizer.unk_token] _lowerCAmelCase : List[str] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(__lowercase ) , __lowercase ) def __A ( self , *a__ , **a__ ): # It's very difficult to mix/test pretokenization with byte-level # And get both CodeGen and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def __A ( self , a__=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): _lowerCAmelCase : List[str] = self.rust_tokenizer_class.from_pretrained(__lowercase , **__lowercase ) # Simple input _lowerCAmelCase : str = '''This is a simple input''' _lowerCAmelCase : Any = ['''This is a simple input 1''', '''This is a simple input 2'''] _lowerCAmelCase : Any = ('''This is a simple input''', '''This is a pair''') _lowerCAmelCase : List[str] = [ ('''This is a simple input 1''', '''This is a simple input 2'''), ('''This is a simple pair 1''', '''This is a simple pair 2'''), ] # Simple input tests self.assertRaises(__lowercase , tokenizer_r.encode , __lowercase , max_length=__lowercase , padding="""max_length""" ) # Simple input self.assertRaises(__lowercase , tokenizer_r.encode_plus , __lowercase , max_length=__lowercase , padding="""max_length""" ) # Simple input self.assertRaises( __lowercase , tokenizer_r.batch_encode_plus , __lowercase , max_length=__lowercase , padding="""max_length""" , ) # Pair input self.assertRaises(__lowercase , tokenizer_r.encode , __lowercase , max_length=__lowercase , padding="""max_length""" ) # Pair input self.assertRaises(__lowercase , tokenizer_r.encode_plus , __lowercase , max_length=__lowercase , padding="""max_length""" ) # Pair input self.assertRaises( __lowercase , tokenizer_r.batch_encode_plus , __lowercase , max_length=__lowercase , padding="""max_length""" , ) def __A ( self ): _lowerCAmelCase : Union[str, Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token="""<pad>""" ) # Simple input _lowerCAmelCase : List[Any] = '''This is a simple input''' _lowerCAmelCase : Union[str, Any] = ['''This is a simple input looooooooong''', '''This is a simple input'''] _lowerCAmelCase : Dict = ('''This is a simple input''', '''This is a pair''') _lowerCAmelCase : int = [ ('''This is a simple input loooooong''', '''This is a simple input'''), ('''This is a simple pair loooooong''', '''This is a simple pair'''), ] _lowerCAmelCase : Optional[int] = tokenizer.pad_token_id _lowerCAmelCase : Optional[int] = tokenizer(__lowercase , padding="""max_length""" , max_length=30 , return_tensors="""np""" ) _lowerCAmelCase : Any = tokenizer(__lowercase , padding=__lowercase , truncate=__lowercase , return_tensors="""np""" ) _lowerCAmelCase : Any = tokenizer(*__lowercase , padding="""max_length""" , max_length=60 , return_tensors="""np""" ) _lowerCAmelCase : str = tokenizer(__lowercase , padding=__lowercase , truncate=__lowercase , return_tensors="""np""" ) # s # test single string max_length padding self.assertEqual(out_s["""input_ids"""].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s["""input_ids"""] ) self.assertTrue(0 in out_s["""attention_mask"""] ) # s2 # test automatic padding self.assertEqual(out_sa["""input_ids"""].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] ) self.assertFalse(0 in out_sa["""attention_mask"""][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] ) self.assertTrue(0 in out_sa["""attention_mask"""][1] ) # p # test single pair max_length padding self.assertEqual(out_p["""input_ids"""].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p["""input_ids"""] ) self.assertTrue(0 in out_p["""attention_mask"""] ) # p2 # test automatic padding pair self.assertEqual(out_pa["""input_ids"""].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] ) self.assertFalse(0 in out_pa["""attention_mask"""][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] ) self.assertTrue(0 in out_pa["""attention_mask"""][1] ) def __A ( self ): _lowerCAmelCase : List[Any] = '''$$$''' _lowerCAmelCase : List[str] = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=__lowercase , add_bos_token=__lowercase ) _lowerCAmelCase : str = '''This is a simple input''' _lowerCAmelCase : List[str] = ['''This is a simple input 1''', '''This is a simple input 2'''] _lowerCAmelCase : List[str] = tokenizer.bos_token_id _lowerCAmelCase : Optional[int] = tokenizer(__lowercase ) _lowerCAmelCase : Union[str, Any] = tokenizer(__lowercase ) self.assertEqual(out_s.input_ids[0] , __lowercase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) _lowerCAmelCase : Union[str, Any] = tokenizer.decode(out_s.input_ids ) _lowerCAmelCase : List[str] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , __lowercase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def __A ( self ): _lowerCAmelCase : str = CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono""" ) _lowerCAmelCase : Dict = '''\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#''' _lowerCAmelCase : Dict = '''\nif len_a > len_b: result = a\nelse: result = b''' _lowerCAmelCase : Any = tokenizer.encode(__lowercase ) _lowerCAmelCase : Dict = ['''^#''', re.escape("""<|endoftext|>""" ), '''^\'\'\'''', '''^"""''', '''\n\n\n'''] _lowerCAmelCase : Optional[Any] = tokenizer.decode(__lowercase , truncate_before_pattern=__lowercase ) self.assertEqual(__lowercase , __lowercase ) def __A ( self ): pass
44
A__ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__ = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str: """simple docstring""" assert len(str(__lowerCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: snake_case__ : Optional[int] = year // 100 snake_case__ : List[str] = (5 * (century % 4) + 2) % 7 snake_case__ : Dict = year % 100 snake_case__ : Union[str, Any] = centurian % 12 snake_case__ : List[Any] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 snake_case__ : List[str] = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) snake_case__ : List[str] = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
230
0
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES _lowercase : List[Any] = logging.get_logger(__name__) _lowercase : str = OrderedDict( [ # Base model mapping ("albert", "FlaxAlbertModel"), ("bart", "FlaxBartModel"), ("beit", "FlaxBeitModel"), ("bert", "FlaxBertModel"), ("big_bird", "FlaxBigBirdModel"), ("blenderbot", "FlaxBlenderbotModel"), ("blenderbot-small", "FlaxBlenderbotSmallModel"), ("clip", "FlaxCLIPModel"), ("distilbert", "FlaxDistilBertModel"), ("electra", "FlaxElectraModel"), ("gpt-sw3", "FlaxGPT2Model"), ("gpt2", "FlaxGPT2Model"), ("gpt_neo", "FlaxGPTNeoModel"), ("gptj", "FlaxGPTJModel"), ("longt5", "FlaxLongT5Model"), ("marian", "FlaxMarianModel"), ("mbart", "FlaxMBartModel"), ("mt5", "FlaxMT5Model"), ("opt", "FlaxOPTModel"), ("pegasus", "FlaxPegasusModel"), ("regnet", "FlaxRegNetModel"), ("resnet", "FlaxResNetModel"), ("roberta", "FlaxRobertaModel"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"), ("roformer", "FlaxRoFormerModel"), ("t5", "FlaxT5Model"), ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"), ("vit", "FlaxViTModel"), ("wav2vec2", "FlaxWav2Vec2Model"), ("whisper", "FlaxWhisperModel"), ("xglm", "FlaxXGLMModel"), ("xlm-roberta", "FlaxXLMRobertaModel"), ] ) _lowercase : List[str] = OrderedDict( [ # Model for pre-training mapping ("albert", "FlaxAlbertForPreTraining"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForPreTraining"), ("big_bird", "FlaxBigBirdForPreTraining"), ("electra", "FlaxElectraForPreTraining"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("t5", "FlaxT5ForConditionalGeneration"), ("wav2vec2", "FlaxWav2Vec2ForPreTraining"), ("whisper", "FlaxWhisperForConditionalGeneration"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) _lowercase : int = OrderedDict( [ # Model for Masked LM mapping ("albert", "FlaxAlbertForMaskedLM"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForMaskedLM"), ("big_bird", "FlaxBigBirdForMaskedLM"), ("distilbert", "FlaxDistilBertForMaskedLM"), ("electra", "FlaxElectraForMaskedLM"), ("mbart", "FlaxMBartForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) _lowercase : str = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("bart", "FlaxBartForConditionalGeneration"), ("blenderbot", "FlaxBlenderbotForConditionalGeneration"), ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"), ("encoder-decoder", "FlaxEncoderDecoderModel"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("marian", "FlaxMarianMTModel"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("pegasus", "FlaxPegasusForConditionalGeneration"), ("t5", "FlaxT5ForConditionalGeneration"), ] ) _lowercase : Optional[Any] = OrderedDict( [ # Model for Image-classsification ("beit", "FlaxBeitForImageClassification"), ("regnet", "FlaxRegNetForImageClassification"), ("resnet", "FlaxResNetForImageClassification"), ("vit", "FlaxViTForImageClassification"), ] ) _lowercase : str = OrderedDict( [ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"), ] ) _lowercase : Tuple = OrderedDict( [ # Model for Causal LM mapping ("bart", "FlaxBartForCausalLM"), ("bert", "FlaxBertForCausalLM"), ("big_bird", "FlaxBigBirdForCausalLM"), ("electra", "FlaxElectraForCausalLM"), ("gpt-sw3", "FlaxGPT2LMHeadModel"), ("gpt2", "FlaxGPT2LMHeadModel"), ("gpt_neo", "FlaxGPTNeoForCausalLM"), ("gptj", "FlaxGPTJForCausalLM"), ("opt", "FlaxOPTForCausalLM"), ("roberta", "FlaxRobertaForCausalLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"), ("xglm", "FlaxXGLMForCausalLM"), ("xlm-roberta", "FlaxXLMRobertaForCausalLM"), ] ) _lowercase : Any = OrderedDict( [ # Model for Sequence Classification mapping ("albert", "FlaxAlbertForSequenceClassification"), ("bart", "FlaxBartForSequenceClassification"), ("bert", "FlaxBertForSequenceClassification"), ("big_bird", "FlaxBigBirdForSequenceClassification"), ("distilbert", "FlaxDistilBertForSequenceClassification"), ("electra", "FlaxElectraForSequenceClassification"), ("mbart", "FlaxMBartForSequenceClassification"), ("roberta", "FlaxRobertaForSequenceClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"), ("roformer", "FlaxRoFormerForSequenceClassification"), ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"), ] ) _lowercase : Dict = OrderedDict( [ # Model for Question Answering mapping ("albert", "FlaxAlbertForQuestionAnswering"), ("bart", "FlaxBartForQuestionAnswering"), ("bert", "FlaxBertForQuestionAnswering"), ("big_bird", "FlaxBigBirdForQuestionAnswering"), ("distilbert", "FlaxDistilBertForQuestionAnswering"), ("electra", "FlaxElectraForQuestionAnswering"), ("mbart", "FlaxMBartForQuestionAnswering"), ("roberta", "FlaxRobertaForQuestionAnswering"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"), ("roformer", "FlaxRoFormerForQuestionAnswering"), ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"), ] ) _lowercase : List[Any] = OrderedDict( [ # Model for Token Classification mapping ("albert", "FlaxAlbertForTokenClassification"), ("bert", "FlaxBertForTokenClassification"), ("big_bird", "FlaxBigBirdForTokenClassification"), ("distilbert", "FlaxDistilBertForTokenClassification"), ("electra", "FlaxElectraForTokenClassification"), ("roberta", "FlaxRobertaForTokenClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"), ("roformer", "FlaxRoFormerForTokenClassification"), ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"), ] ) _lowercase : List[Any] = OrderedDict( [ # Model for Multiple Choice mapping ("albert", "FlaxAlbertForMultipleChoice"), ("bert", "FlaxBertForMultipleChoice"), ("big_bird", "FlaxBigBirdForMultipleChoice"), ("distilbert", "FlaxDistilBertForMultipleChoice"), ("electra", "FlaxElectraForMultipleChoice"), ("roberta", "FlaxRobertaForMultipleChoice"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"), ("roformer", "FlaxRoFormerForMultipleChoice"), ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"), ] ) _lowercase : Any = OrderedDict( [ ("bert", "FlaxBertForNextSentencePrediction"), ] ) _lowercase : List[str] = OrderedDict( [ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"), ("whisper", "FlaxWhisperForConditionalGeneration"), ] ) _lowercase : str = OrderedDict( [ ("whisper", "FlaxWhisperForAudioClassification"), ] ) _lowercase : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) _lowercase : List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) _lowercase : Tuple = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) _lowercase : str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) _lowercase : List[str] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) _lowercase : Tuple = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) _lowercase : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) _lowercase : str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) _lowercase : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) _lowercase : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) _lowercase : Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) _lowercase : str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) _lowercase : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) _lowercase : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_MAPPING _lowercase : Tuple = auto_class_update(FlaxAutoModel) class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_PRETRAINING_MAPPING _lowercase : List[Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING _lowercase : int = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_MASKED_LM_MAPPING _lowercase : Tuple = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : Tuple = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _lowercase : Any = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING _lowercase : Tuple = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING _lowercase : Tuple = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING _lowercase : str = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING _lowercase : str = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING _lowercase : Union[str, Any] = auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING _lowercase : Union[str, Any] = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling") class lowerCAmelCase__ ( _BaseAutoModelClass ): lowerCAmelCase_ = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING _lowercase : List[str] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling" )
355
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase : Tuple = {"configuration_vit_msn": ["VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMSNConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str = [ "VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMSNModel", "ViTMSNForImageClassification", "ViTMSNPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys _lowercase : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
264
0
"""simple docstring""" import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () lowerCAmelCase__ : Optional[Any] = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). lowerCAmelCase__ : List[str] = [0, 25, 50] lowerCAmelCase__ : List[Any] = [25, 50, 75] lowerCAmelCase__ : Any = fuzz.membership.trimf(X, abca) lowerCAmelCase__ : Tuple = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. lowerCAmelCase__ : Optional[Any] = np.ones(75) lowerCAmelCase__ : List[Any] = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) lowerCAmelCase__ : List[Any] = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) lowerCAmelCase__ : Optional[Any] = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) lowerCAmelCase__ : Tuple = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) lowerCAmelCase__ : Tuple = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] lowerCAmelCase__ : List[str] = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) lowerCAmelCase__ : int = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] lowerCAmelCase__ : Dict = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] lowerCAmelCase__ : Union[str, Any] = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
98
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ : int = logging.get_logger(__name__) lowerCAmelCase__ : str = { 'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/config.json', # See all XGLM models at https://huggingface.co/models?filter=xglm } class snake_case ( __UpperCAmelCase ): """simple docstring""" snake_case__ = "xglm" snake_case__ = ["past_key_values"] snake_case__ = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : Any ,lowerCamelCase__ : Any=256_008 ,lowerCamelCase__ : Optional[Any]=2_048 ,lowerCamelCase__ : List[str]=1_024 ,lowerCamelCase__ : List[str]=4_096 ,lowerCamelCase__ : Tuple=24 ,lowerCamelCase__ : Optional[int]=16 ,lowerCamelCase__ : int="gelu" ,lowerCamelCase__ : Dict=0.1 ,lowerCamelCase__ : int=0.1 ,lowerCamelCase__ : List[Any]=0.0 ,lowerCamelCase__ : List[str]=0.0 ,lowerCamelCase__ : Optional[Any]=0.0_2 ,lowerCamelCase__ : List[str]=True ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : str=2 ,lowerCamelCase__ : Dict=1 ,lowerCamelCase__ : Optional[int]=0 ,lowerCamelCase__ : Tuple=2 ,**lowerCamelCase__ : List[Any] ,): UpperCAmelCase__ = vocab_size UpperCAmelCase__ = max_position_embeddings UpperCAmelCase__ = d_model UpperCAmelCase__ = ffn_dim UpperCAmelCase__ = num_layers UpperCAmelCase__ = attention_heads UpperCAmelCase__ = activation_function UpperCAmelCase__ = dropout UpperCAmelCase__ = attention_dropout UpperCAmelCase__ = activation_dropout UpperCAmelCase__ = layerdrop UpperCAmelCase__ = init_std UpperCAmelCase__ = scale_embedding # scale factor will be sqrt(d_model) if True UpperCAmelCase__ = use_cache super().__init__( pad_token_id=lowerCamelCase__ ,bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,decoder_start_token_id=lowerCamelCase__ ,**lowerCamelCase__ ,)
98
1
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class __magic_name__ ( unittest.TestCase): @slow def UpperCAmelCase__ ( self : str ) -> str: '''simple docstring''' UpperCamelCase__ : str = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) UpperCamelCase__ : Any = AutoTokenizer.from_pretrained('''google/mt5-small''' ) UpperCamelCase__ : List[Any] = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids UpperCamelCase__ : Union[str, Any] = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids UpperCamelCase__ : str = shift_tokens_right(lowerCamelCase__ , model.config.pad_token_id , model.config.decoder_start_token_id ) UpperCamelCase__ : Any = model(lowerCamelCase__ , decoder_input_ids=lowerCamelCase__ ).logits UpperCamelCase__ : Optional[int] = optax.softmax_cross_entropy(lowerCamelCase__ , onehot(lowerCamelCase__ , logits.shape[-1] ) ).mean() UpperCamelCase__ : Optional[Any] = -(labels.shape[-1] * loss.item()) UpperCamelCase__ : Any = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
366
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __magic_name__ ( __lowerCAmelCase , unittest.TestCase): A: int = CTRLTokenizer A: List[Any] = False A: Dict = False def UpperCAmelCase__ ( self : Optional[Any] ) -> str: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ : Dict = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] UpperCamelCase__ : List[str] = dict(zip(lowerCamelCase__ , range(len(lowerCamelCase__ ) ) ) ) UpperCamelCase__ : Tuple = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</w>''', ''''''] UpperCamelCase__ : int = {'''unk_token''': '''<unk>'''} UpperCamelCase__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCamelCase__ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(lowerCamelCase__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(lowerCamelCase__ ) ) def UpperCAmelCase__ ( self : Tuple , **lowerCamelCase__ : str ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase__ ) def UpperCAmelCase__ ( self : List[Any] , lowerCamelCase__ : Any ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ : Tuple = '''adapt react readapt apt''' UpperCamelCase__ : Optional[Any] = '''adapt react readapt apt''' return input_text, output_text def UpperCAmelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' UpperCamelCase__ : int = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ : Optional[Any] = '''adapt react readapt apt''' UpperCamelCase__ : List[Any] = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() UpperCamelCase__ : Tuple = tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase__ : Dict = tokens + [tokenizer.unk_token] UpperCamelCase__ : List[str] = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) , lowerCamelCase__ )
51
0
def __lowerCamelCase ( lowerCamelCase__ = 50_000_000 ): """simple docstring""" lowercase__ : Any = set() lowercase__ : Optional[Any] = int((limit - 24) ** (1 / 2) ) lowercase__ : str = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , lowerCamelCase__ ) ) ) for primea in primes: lowercase__ : List[str] = primea * primea for primea in primes: lowercase__ : int = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowercase__ : Any = primea * primea * primea * primea lowercase__ : List[Any] = square + cube + tetr if total >= limit: break ret.add(lowerCamelCase__ ) return len(lowerCamelCase__ ) if __name__ == "__main__": print(f'''{solution() = }''')
130
import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, is_tf_available, is_torch_available, ) lowerCAmelCase__ = logging.getLogger(__name__) @dataclass(frozen=_UpperCamelCase ) class snake_case__: """simple docstring""" lowercase_ = 42 lowercase_ = 42 lowercase_ = None lowercase_ = None lowercase_ = None @dataclass(frozen=_UpperCamelCase ) class snake_case__: """simple docstring""" lowercase_ = 42 lowercase_ = None lowercase_ = None lowercase_ = None lowercase_ = None if is_torch_available(): import torch from torch.utils.data import Dataset class snake_case__(_UpperCamelCase ): """simple docstring""" lowercase_ = 42 def __init__( self : Any , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : PreTrainedTokenizer , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] = None , SCREAMING_SNAKE_CASE : Tuple=False , SCREAMING_SNAKE_CASE : bool = False , ): lowercase__ : List[str] = hans_processors[task]() lowercase__ : Dict = os.path.join( SCREAMING_SNAKE_CASE , "cached_{}_{}_{}_{}".format( "dev" if evaluate else "train" , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , ) , ) lowercase__ : List[str] = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) lowercase__ , lowercase__ : Union[str, Any] = label_list[2], label_list[1] lowercase__ : Any = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. lowercase__ : int = cached_features_file + ".lock" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"""Loading features from cached file {cached_features_file}""" ) lowercase__ : Any = torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"""Creating features from dataset file at {data_dir}""" ) lowercase__ : List[str] = ( processor.get_dev_examples(SCREAMING_SNAKE_CASE ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE ) ) logger.info("Training examples: %s" , len(SCREAMING_SNAKE_CASE ) ) lowercase__ : Tuple = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) logger.info("Saving features into cached file %s" , SCREAMING_SNAKE_CASE ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self : List[Any] ): return len(self.features ) def __getitem__( self : str , SCREAMING_SNAKE_CASE : List[str] ): return self.features[i] def snake_case ( self : Any ): return self.label_list if is_tf_available(): import tensorflow as tf class snake_case__: """simple docstring""" lowercase_ = 42 def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : PreTrainedTokenizer , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] = 128 , SCREAMING_SNAKE_CASE : int=False , SCREAMING_SNAKE_CASE : bool = False , ): lowercase__ : str = hans_processors[task]() lowercase__ : Union[str, Any] = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) lowercase__ , lowercase__ : str = label_list[2], label_list[1] lowercase__ : Optional[int] = label_list lowercase__ : Any = processor.get_dev_examples(SCREAMING_SNAKE_CASE ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE ) lowercase__ : Optional[int] = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc="convert examples to features" ): if ex_index % 10_000 == 0: logger.info("Writing example %d of %d" % (ex_index, len(SCREAMING_SNAKE_CASE )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) lowercase__ : Optional[int] = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ( { "example_id": tf.intaa, "input_ids": tf.intaa, "attention_mask": tf.intaa, "token_type_ids": tf.intaa, }, tf.intaa, ) , ( { "example_id": tf.TensorShape([] ), "input_ids": tf.TensorShape([None, None] ), "attention_mask": tf.TensorShape([None, None] ), "token_type_ids": tf.TensorShape([None, None] ), }, tf.TensorShape([] ), ) , ) def snake_case ( self : int ): return self.dataset def __len__( self : List[str] ): return len(self.features ) def __getitem__( self : Union[str, Any] , SCREAMING_SNAKE_CASE : Any ): return self.features[i] def snake_case ( self : Any ): return self.label_list class snake_case__(_UpperCamelCase ): """simple docstring""" def snake_case ( self : Dict , SCREAMING_SNAKE_CASE : int ): return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE , "heuristics_train_set.txt" ) ) , "train" ) def snake_case ( self : Any , SCREAMING_SNAKE_CASE : Any ): return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE , "heuristics_evaluation_set.txt" ) ) , "dev" ) def snake_case ( self : Union[str, Any] ): return ["contradiction", "entailment", "neutral"] def snake_case ( self : Optional[int] , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Dict ): lowercase__ : Dict = [] for i, line in enumerate(SCREAMING_SNAKE_CASE ): if i == 0: continue lowercase__ : str = "%s-%s" % (set_type, line[0]) lowercase__ : str = line[5] lowercase__ : List[str] = line[6] lowercase__ : Dict = line[7][2:] if line[7].startswith("ex" ) else line[7] lowercase__ : Union[str, Any] = line[0] examples.append(InputExample(guid=SCREAMING_SNAKE_CASE , text_a=SCREAMING_SNAKE_CASE , text_b=SCREAMING_SNAKE_CASE , label=SCREAMING_SNAKE_CASE , pairID=SCREAMING_SNAKE_CASE ) ) return examples def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ): """simple docstring""" lowercase__ : str = {label: i for i, label in enumerate(lowerCamelCase__ )} lowercase__ : str = [] for ex_index, example in tqdm.tqdm(enumerate(lowerCamelCase__ ) , desc="convert examples to features" ): if ex_index % 10_000 == 0: logger.info("Writing example %d" % (ex_index) ) lowercase__ : Any = tokenizer( example.text_a , example.text_b , add_special_tokens=lowerCamelCase__ , max_length=lowerCamelCase__ , padding="max_length" , truncation=lowerCamelCase__ , return_overflowing_tokens=lowerCamelCase__ , ) lowercase__ : Optional[int] = label_map[example.label] if example.label in label_map else 0 lowercase__ : Any = int(example.pairID ) features.append(InputFeatures(**lowerCamelCase__ , label=lowerCamelCase__ , pairID=lowerCamelCase__ ) ) for i, example in enumerate(examples[:5] ): logger.info("*** Example ***" ) logger.info(F"""guid: {example}""" ) logger.info(F"""features: {features[i]}""" ) return features lowerCAmelCase__ = { '''hans''': 3, } lowerCAmelCase__ = { '''hans''': HansProcessor, }
130
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ = { '''configuration_luke''': ['''LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LukeConfig'''], '''tokenization_luke''': ['''LukeTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ = [ '''LUKE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LukeForEntityClassification''', '''LukeForEntityPairClassification''', '''LukeForEntitySpanClassification''', '''LukeForMultipleChoice''', '''LukeForQuestionAnswering''', '''LukeForSequenceClassification''', '''LukeForTokenClassification''', '''LukeForMaskedLM''', '''LukeModel''', '''LukePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys A__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
44
import argparse from collections import defaultdict def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: """simple docstring""" snake_case__ : Dict = f"""{file}_{class_name}_{test_name}""" done_test[_id] += 1 with open(__lowerCAmelCase , '''r''' ) as f: snake_case__ : str = f.readlines() snake_case__ : List[str] = f"""class {class_name}(""" snake_case__ : Any = f"""{4 * ' '}def {test_name}(""" snake_case__ : Optional[int] = f"""{8 * ' '}{correct_line.split()[0]}""" snake_case__ : List[str] = f"""{16 * ' '}{correct_line.split()[0]}""" snake_case__ : Any = False snake_case__ : Optional[int] = False snake_case__ : Optional[Any] = False snake_case__ : int = False snake_case__ : Union[str, Any] = 0 snake_case__ : str = 0 snake_case__ : Union[str, Any] = [] for line in lines: if line.startswith(__lowerCAmelCase ): snake_case__ : Optional[Any] = True elif in_class and line.startswith(__lowerCAmelCase ): snake_case__ : Optional[int] = True elif in_class and in_func and (line.startswith(__lowerCAmelCase ) or line.startswith(__lowerCAmelCase )): snake_case__ : int = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: snake_case__ : Tuple = True if in_class and in_func and in_line: if ")" not in line: continue else: snake_case__ : List[Any] = True if in_class and in_func and in_line and insert_line: new_lines.append(f"""{spaces * ' '}{correct_line}""" ) snake_case__ : Optional[int] = False else: new_lines.append(__lowerCAmelCase ) with open(__lowerCAmelCase , '''w''' ) as f: for line in new_lines: f.write(__lowerCAmelCase ) def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase=None ) -> Dict: """simple docstring""" if fail is not None: with open(__lowerCAmelCase , '''r''' ) as f: snake_case__ : Optional[int] = {l.strip() for l in f.readlines()} else: snake_case__ : Tuple = None with open(__lowerCAmelCase , '''r''' ) as f: snake_case__ : Optional[int] = f.readlines() snake_case__ : Tuple = defaultdict(__lowerCAmelCase ) for line in correct_lines: snake_case__ , snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = line.split(''';''' ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": A__ = argparse.ArgumentParser() parser.add_argument('''--correct_filename''', help='''filename of tests with expected result''') parser.add_argument('''--fail_filename''', help='''filename of test failures''', type=str, default=None) A__ = parser.parse_args() main(args.correct_filename, args.fail_filename)
44
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A__: List[str] = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[Any] = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: str = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys A__: Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
1
import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCamelCase : int = logging.get_logger(__name__) __UpperCamelCase : Union[str, Any] = { "nvidia/segformer-b0-finetuned-ade-512-512": ( "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = '''segformer''' def __init__( self :Dict , __magic_name__ :List[str]=3 , __magic_name__ :int=4 , __magic_name__ :Union[str, Any]=[2, 2, 2, 2] , __magic_name__ :List[Any]=[8, 4, 2, 1] , __magic_name__ :str=[32, 64, 160, 256] , __magic_name__ :int=[7, 3, 3, 3] , __magic_name__ :Dict=[4, 2, 2, 2] , __magic_name__ :List[Any]=[1, 2, 5, 8] , __magic_name__ :int=[4, 4, 4, 4] , __magic_name__ :Union[str, Any]="gelu" , __magic_name__ :Any=0.0 , __magic_name__ :Optional[int]=0.0 , __magic_name__ :List[Any]=0.1 , __magic_name__ :str=0.02 , __magic_name__ :List[str]=0.1 , __magic_name__ :Any=1E-6 , __magic_name__ :Optional[int]=256 , __magic_name__ :Tuple=255 , **__magic_name__ :Tuple , ): '''simple docstring''' super().__init__(**__magic_name__ ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be""" """ removed, as the behaviour will default to that of reshape_last_stage = True.""" , __magic_name__ , ) a = num_channels a = num_encoder_blocks a = depths a = sr_ratios a = hidden_sizes a = patch_sizes a = strides a = mlp_ratios a = num_attention_heads a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = classifier_dropout_prob a = initializer_range a = drop_path_rate a = layer_norm_eps a = decoder_hidden_size a = kwargs.get("""reshape_last_stage""" , __magic_name__ ) a = semantic_loss_ignore_index class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = version.parse('''1.11''' ) @property def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowerCamelCase__ ( self :List[str] ): '''simple docstring''' return 1E-4 @property def lowerCamelCase__ ( self :str ): '''simple docstring''' return 12
347
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize("""dataset_size""" , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize("""input_in_memory_max_size""" , ["""default""", 0, 100 * 2**20, 900 * 2**20] ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , """IN_MEMORY_MAX_SIZE""" , __lowerCamelCase ) a = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: a = dataset_size < in_memory_max_size else: a = False a = is_small_dataset(__lowerCamelCase ) assert result == expected
347
1
'''simple docstring''' 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 __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer __lowerCamelCase = flax_key_tuple[:-1] + ('''weight''',) __lowerCamelCase = torch.permute(UpperCamelCase__ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(UpperCamelCase__ ): # linear layer __lowerCamelCase = flax_key_tuple[:-1] + ('''weight''',) __lowerCamelCase = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: __lowerCamelCase = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: if "metadata" in layer: __lowerCamelCase = layer.split('''metadata''' ) __lowerCamelCase = ''''''.join(split_layer[0] )[:-1] __lowerCamelCase = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )] elif "kvstore" in layer: __lowerCamelCase = layer.split('''kvstore''' ) __lowerCamelCase = ''''''.join(split_layer[0] )[:-1] __lowerCamelCase = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )] else: __lowerCamelCase = layer.split('''/''' ) __lowerCamelCase = '''/'''.join(split_layer[:-1] ) __lowerCamelCase = (split_layer[-1],) if "kvstore/path" in layer: __lowerCamelCase = f"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: __lowerCamelCase = '''file''' else: __lowerCamelCase = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Dict: __lowerCamelCase = rename_keys(UpperCamelCase__ ) __lowerCamelCase = {} for k, v in current_block.items(): __lowerCamelCase = v __lowerCamelCase = new_current_block torch.save(UpperCamelCase__ , UpperCamelCase__ ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = WEIGHTS_NAME ) -> Tuple: __lowerCamelCase = convert_file_size_to_int(UpperCamelCase__ ) __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 __lowerCamelCase = 0 os.makedirs(UpperCamelCase__ , exist_ok=UpperCamelCase__ ) with gfile.GFile(switch_checkpoint_path + '''/checkpoint''' , '''rb''' ) as fp: __lowerCamelCase = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] __lowerCamelCase = flatten_dict(UpperCamelCase__ , sep='''/''' ) __lowerCamelCase = {} for layer in checkpoint_info.keys(): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = get_key_and_tensorstore_dict( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if curr_real_layer_name in all_layers: __lowerCamelCase = content else: __lowerCamelCase = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file __lowerCamelCase = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() __lowerCamelCase = torch.tensor(UpperCamelCase__ ) __lowerCamelCase = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts __lowerCamelCase , __lowerCamelCase = rename_base_flax_keys(tuple(key.split('''/''' ) ) , UpperCamelCase__ ) __lowerCamelCase = '''/'''.join(UpperCamelCase__ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: __lowerCamelCase = os.path.join( UpperCamelCase__ , weights_name.replace('''.bin''' , f"""-{len(UpperCamelCase__ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(UpperCamelCase__ , UpperCamelCase__ ) sharded_state_dicts.append(current_block.keys() ) del current_block __lowerCamelCase = {} __lowerCamelCase = 0 __lowerCamelCase = raw_weights.to(getattr(UpperCamelCase__ , UpperCamelCase__ ) ) current_block_size += weight_size total_size += weight_size # Add the last block __lowerCamelCase = os.path.join(UpperCamelCase__ , weights_name.replace('''.bin''' , f"""-{len(UpperCamelCase__ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(UpperCamelCase__ , UpperCamelCase__ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(UpperCamelCase__ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index __lowerCamelCase = {} __lowerCamelCase = {} for idx, shard in enumerate(UpperCamelCase__ ): __lowerCamelCase = weights_name.replace( '''.bin''' , f"""-{idx+1:05d}-of-{len(UpperCamelCase__ ):05d}.bin""" ) # len(sharded_state_dicts):05d} __lowerCamelCase = os.path.join(UpperCamelCase__ , weights_name.replace('''.bin''' , f"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(UpperCamelCase__ , os.path.join(UpperCamelCase__ , UpperCamelCase__ ) ) __lowerCamelCase = shard for key in shard: __lowerCamelCase = shard_file # Add the metadata __lowerCamelCase = {'''total_size''': total_size} __lowerCamelCase = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) , '''w''' , encoding='''utf-8''' ) as f: __lowerCamelCase = json.dumps(UpperCamelCase__ , indent=2 , sort_keys=UpperCamelCase__ ) + '''\n''' f.write(UpperCamelCase__ ) return metadata, index if __name__ == "__main__": __UpperCAmelCase =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.", ) __UpperCAmelCase =parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __lowerCAmelCase ( ) -> List[Any]: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer __lowerCamelCase = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' ) config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' ) __lowerCamelCase = SwitchTransformersForConditionalGeneration.from_pretrained( '''/home/arthur_huggingface_co/transformers/switch_converted''' , device_map='''auto''' ) __lowerCamelCase = TaTokenizer.from_pretrained('''t5-small''' ) __lowerCamelCase = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' __lowerCamelCase = tokenizer(UpperCamelCase__ , return_tensors='''pt''' ).input_ids __lowerCamelCase = model.generate(UpperCamelCase__ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
67
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu a__ : Any = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def _UpperCamelCase ( __A , __A=None , __A=None , __A=None ) -> int: '''simple docstring''' UpperCamelCase__ = True while ask_again: UpperCamelCase__ = input(__A ) try: if default is not None and len(__A ) == 0: return default return convert_value(__A ) if convert_value is not None else result except Exception: if error_message is not None: print(__A ) def _UpperCamelCase ( __A , __A=[] , __A=None , __A=0 ) -> Any: '''simple docstring''' UpperCamelCase__ = BulletMenu(__A , __A ) UpperCamelCase__ = menu.run(default_choice=__A ) return convert_value(__A ) if convert_value is not None else result def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] ) def _UpperCamelCase ( __A ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = int(__A ) return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' UpperCamelCase__ = int(__A ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def _UpperCamelCase ( __A ) -> str: '''simple docstring''' UpperCamelCase__ = int(__A ) return PrecisionType(["no", "fp16", "bf16", "fp8"][value] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = int(__A ) return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] ) def _UpperCamelCase ( __A ) -> Dict: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class lowercase_ ( argparse.RawDescriptionHelpFormatter ): def __a ( self , a , a , a , a ): UpperCamelCase__ = super()._format_usage(a , a , a , a ) UpperCamelCase__ = usage.replace("<command> [<args>] " , "" ) return usage
80
0
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup __a = '''https://www.indeed.co.in/jobs?q=mobile+app+development&l=''' def __lowercase ( _UpperCamelCase = "mumbai" ) ->Generator[tuple[str, str], None, None]: """simple docstring""" lowercase : Optional[int] = BeautifulSoup(requests.get(url + location ).content, '''html.parser''' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('''div''', attrs={'''data-tn-component''': '''organicJob'''} ): lowercase : Union[str, Any] = job.find('''a''', attrs={'''data-tn-element''': '''jobTitle'''} ).text.strip() lowercase : int = job.find('''span''', {'''class''': '''company'''} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('''Bangalore'''), 1): print(F'''Job {i:>2} is {job[0]} at {job[1]}''')
350
import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __lowerCamelCase ( self ): lowercase : int = 0 @slow def __lowerCamelCase ( self ): for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): lowercase : Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(SCREAMING_SNAKE_CASE__ ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): lowercase : str = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(SCREAMING_SNAKE_CASE__ ) , 0 ) def __lowerCamelCase ( self ): lowercase : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def __lowerCamelCase ( self ): lowercase : Any = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 20 ) def __lowerCamelCase ( self ): lowercase : Union[str, Any] = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Check that tokenizer_type ≠ model_type lowercase : Optional[int] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def __lowerCamelCase ( self ): with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.txt''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab.txt''' ) ) lowercase : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , tokenizer_type='''bert''' , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.json''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab.json''' ) ) shutil.copy('''./tests/fixtures/merges.txt''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''merges.txt''' ) ) lowercase : Any = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , tokenizer_type='''gpt2''' , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @require_tokenizers def __lowerCamelCase ( self ): with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.txt''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab.txt''' ) ) lowercase : Dict = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , tokenizer_type='''bert''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.json''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab.json''' ) ) shutil.copy('''./tests/fixtures/merges.txt''' , os.path.join(SCREAMING_SNAKE_CASE__ , '''merges.txt''' ) ) lowercase : int = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , tokenizer_type='''gpt2''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self ): with pytest.raises(SCREAMING_SNAKE_CASE__ ): AutoTokenizer.from_pretrained('''./''' , tokenizer_type='''xxx''' ) @require_tokenizers def __lowerCamelCase ( self ): for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: lowercase : Union[str, Any] = tokenizer_class.from_pretrained('''wietsedv/bert-base-dutch-cased''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (BertTokenizer, BertTokenizerFast) ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(tokenizer.do_lower_case , SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.model_max_length , 512 ) @require_tokenizers def __lowerCamelCase ( self ): for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , '''julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier''' , ): lowercase : str = tokenizer_class.from_pretrained('''julien-c/herlolip-not-exists''' ) def __lowerCamelCase ( self ): # tests: https://github.com/huggingface/transformers/pull/13251 # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai lowercase : Any = TOKENIZER_MAPPING.values() lowercase : Tuple = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(SCREAMING_SNAKE_CASE__ ) @require_tokenizers def __lowerCamelCase ( self ): self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' , use_fast=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' ) , SCREAMING_SNAKE_CASE__ ) @require_tokenizers def __lowerCamelCase ( self ): lowercase : Optional[Any] = AutoTokenizer.from_pretrained('''distilbert-base-uncased''' , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowercase : List[Any] = '''Hello, world. How are you?''' lowercase : Any = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertEqual('''[UNK]''' , tokens[0] ) lowercase : Optional[Any] = AutoTokenizer.from_pretrained('''microsoft/mpnet-base''' , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertEqual('''[UNK]''' , tokens[0] ) @require_tokenizers def __lowerCamelCase ( self ): lowercase : int = AutoTokenizer.from_pretrained('''robot-test/dummy-tokenizer-fast-with-model-config''' ) self.assertEqual(type(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.model_max_length , 512 ) self.assertEqual(tokenizer.vocab_size , 30000 ) self.assertEqual(tokenizer.unk_token , '''[UNK]''' ) self.assertEqual(tokenizer.padding_side , '''right''' ) self.assertEqual(tokenizer.truncation_side , '''right''' ) def __lowerCamelCase ( self ): lowercase : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : Any = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 12 ) def __lowerCamelCase ( self ): lowercase : Union[str, Any] = AutoTokenizer.from_pretrained('''ctrl''' ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self ): # Check we can load the tokenizer config of an online model. lowercase : Optional[Any] = get_tokenizer_config('''bert-base-cased''' ) lowercase : str = config.pop('''_commit_hash''' , SCREAMING_SNAKE_CASE__ ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(SCREAMING_SNAKE_CASE__ , {'''do_lower_case''': False} ) # This model does not have a tokenizer_config so we get back an empty dict. lowercase : Union[str, Any] = get_tokenizer_config(SCREAMING_SNAKE_CASE__ ) self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. lowercase : str = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = get_tokenizer_config(SCREAMING_SNAKE_CASE__ ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config['''tokenizer_class'''] , '''BertTokenizer''' ) def __lowerCamelCase ( self ): try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE__ ) AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , slow_tokenizer_class=SCREAMING_SNAKE_CASE__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE__ ): AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , slow_tokenizer_class=SCREAMING_SNAKE_CASE__ ) lowercase : int = CustomTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : str = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def __lowerCamelCase ( self ): try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE__ ) # Can register in two steps AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , slow_tokenizer_class=SCREAMING_SNAKE_CASE__ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , fast_tokenizer_class=SCREAMING_SNAKE_CASE__ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( SCREAMING_SNAKE_CASE__ , slow_tokenizer_class=SCREAMING_SNAKE_CASE__ , fast_tokenizer_class=SCREAMING_SNAKE_CASE__ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE__ ): AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , fast_tokenizer_class=SCREAMING_SNAKE_CASE__ ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: lowercase : Union[str, Any] = BertTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE__ ) bert_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : List[Any] = CustomTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : Optional[int] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def __lowerCamelCase ( self ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(SCREAMING_SNAKE_CASE__ ): lowercase : List[Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(SCREAMING_SNAKE_CASE__ ): lowercase : str = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) lowercase : Dict = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , trust_remote_code=SCREAMING_SNAKE_CASE__ ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) # Test we can also load the slow version lowercase : int = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , trust_remote_code=SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizer''' ) @require_tokenizers def __lowerCamelCase ( self ): class __SCREAMING_SNAKE_CASE ( A__ ): A : str = False class __SCREAMING_SNAKE_CASE ( A__ ): A : Dict = NewTokenizer A : Optional[int] = False try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE__ ) AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , slow_tokenizer_class=SCREAMING_SNAKE_CASE__ ) AutoTokenizer.register(SCREAMING_SNAKE_CASE__ , fast_tokenizer_class=SCREAMING_SNAKE_CASE__ ) # If remote code is not set, the default is to use local lowercase : Union[str, Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertFalse(tokenizer.special_attribute_present ) lowercase : Union[str, Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. lowercase : Tuple = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertFalse(tokenizer.special_attribute_present ) lowercase : List[str] = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub lowercase : Any = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertTrue(tokenizer.special_attribute_present ) lowercase : List[Any] = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def __lowerCamelCase ( self ): lowercase : Dict = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer_legacy''' , trust_remote_code=SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) # Test we can also load the slow version lowercase : int = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer_legacy''' , trust_remote_code=SCREAMING_SNAKE_CASE__ , use_fast=SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) def __lowerCamelCase ( self ): with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , '''bert-base is not a local folder and is not a valid model identifier''' ): lowercase : List[Any] = AutoTokenizer.from_pretrained('''bert-base''' ) def __lowerCamelCase ( self ): with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): lowercase : Optional[int] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , revision='''aaaaaa''' ) def __lowerCamelCase ( self ): # Make sure we have cached the tokenizer. lowercase : Optional[Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) with RequestCounter() as counter: lowercase : List[Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
173
0
'''simple docstring''' import logging import os from .state import PartialState class UpperCAmelCase_ ( logging.LoggerAdapter ): @staticmethod def __UpperCAmelCase ( UpperCAmelCase__ : List[Any] ) -> Optional[int]: lowerCAmelCase = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def __UpperCAmelCase ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : Optional[Any] ) -> List[str]: if PartialState._shared_state == {}: raise RuntimeError( 'You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.' ) lowerCAmelCase = kwargs.pop('main_process_only' , UpperCAmelCase__ ) lowerCAmelCase = kwargs.pop('in_order' , UpperCAmelCase__ ) if self.isEnabledFor(UpperCAmelCase__ ): if self._should_log(UpperCAmelCase__ ): lowerCAmelCase , lowerCAmelCase = self.process(UpperCAmelCase__ , UpperCAmelCase__ ) self.logger.log(UpperCAmelCase__ , UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) elif in_order: lowerCAmelCase = PartialState() for i in range(state.num_processes ): if i == state.process_index: lowerCAmelCase , lowerCAmelCase = self.process(UpperCAmelCase__ , UpperCAmelCase__ ) self.logger.log(UpperCAmelCase__ , UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) state.wait_for_everyone() def a_ ( lowerCamelCase : str , lowerCamelCase : str = None ): if log_level is None: lowerCAmelCase = os.environ.get('ACCELERATE_LOG_LEVEL' , lowerCamelCase ) lowerCAmelCase = logging.getLogger(lowerCamelCase ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(lowerCamelCase , {} )
4
'''simple docstring''' print((lambda quine: quine % quine)("""print((lambda quine: quine %% quine)(%r))"""))
4
1
def __lowercase ( ): UpperCamelCase_ : str = [] UpperCamelCase_ : Union[str, Any] = 1 while len(lowerCamelCase ) < 1e6: constant.append(str(lowerCamelCase ) ) i += 1 UpperCamelCase_ : Union[str, Any] = ''.join(lowerCamelCase ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[999] ) * int(constant[9999] ) * int(constant[99999] ) * int(constant[999999] ) ) if __name__ == "__main__": print(solution())
50
from __future__ import annotations import numpy as np def __lowercase ( lowerCamelCase : list[float] ): return np.maximum(0 , lowerCamelCase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
50
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { '''microsoft/swin-tiny-patch4-window7-224''': ( '''https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json''' ), # See all Swin models at https://huggingface.co/models?filter=swin } class _A ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[Any] = "swin" _SCREAMING_SNAKE_CASE : Optional[int] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , __UpperCAmelCase=224 , __UpperCAmelCase=4 , __UpperCAmelCase=3 , __UpperCAmelCase=96 , __UpperCAmelCase=[2, 2, 6, 2] , __UpperCAmelCase=[3, 6, 12, 24] , __UpperCAmelCase=7 , __UpperCAmelCase=4.0 , __UpperCAmelCase=True , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase="gelu" , __UpperCAmelCase=False , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-5 , __UpperCAmelCase=32 , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase , ) -> Optional[int]: '''simple docstring''' super().__init__(**__UpperCAmelCase ) __UpperCAmelCase : Dict = image_size __UpperCAmelCase : Tuple = patch_size __UpperCAmelCase : Dict = num_channels __UpperCAmelCase : List[Any] = embed_dim __UpperCAmelCase : List[str] = depths __UpperCAmelCase : int = len(__UpperCAmelCase ) __UpperCAmelCase : Optional[int] = num_heads __UpperCAmelCase : Any = window_size __UpperCAmelCase : Union[str, Any] = mlp_ratio __UpperCAmelCase : List[str] = qkv_bias __UpperCAmelCase : List[str] = hidden_dropout_prob __UpperCAmelCase : Optional[int] = attention_probs_dropout_prob __UpperCAmelCase : Any = drop_path_rate __UpperCAmelCase : Tuple = hidden_act __UpperCAmelCase : Any = use_absolute_embeddings __UpperCAmelCase : Optional[Any] = layer_norm_eps __UpperCAmelCase : List[Any] = initializer_range __UpperCAmelCase : Tuple = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __UpperCAmelCase : Union[str, Any] = int(embed_dim * 2 ** (len(__UpperCAmelCase ) - 1) ) __UpperCAmelCase : int = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(__UpperCAmelCase ) + 1 )] __UpperCAmelCase , __UpperCAmelCase : List[str] = get_aligned_output_features_output_indices( out_features=__UpperCAmelCase , out_indices=__UpperCAmelCase , stage_names=self.stage_names ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : int = version.parse("1.11" ) @property def __A ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __A ( self ) -> float: '''simple docstring''' return 1E-4
254
'''simple docstring''' import math import os import sys def lowercase_ ( lowerCAmelCase__ : str ): """simple docstring""" __UpperCAmelCase : Any = """""" try: with open(lowerCAmelCase__ , """rb""" ) as binary_file: __UpperCAmelCase : int = binary_file.read() for dat in data: __UpperCAmelCase : Tuple = f'{dat:08b}' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def lowercase_ ( lowerCAmelCase__ : dict[str, str] , lowerCAmelCase__ : str , lowerCAmelCase__ : int , lowerCAmelCase__ : str ): """simple docstring""" lexicon.pop(lowerCAmelCase__ ) __UpperCAmelCase : List[str] = last_match_id if math.loga(lowerCAmelCase__ ).is_integer(): for curr_key in lexicon: __UpperCAmelCase : List[str] = """0""" + lexicon[curr_key] __UpperCAmelCase : Any = bin(lowerCAmelCase__ )[2:] def lowercase_ ( lowerCAmelCase__ : str ): """simple docstring""" __UpperCAmelCase : str = {"""0""": """0""", """1""": """1"""} __UpperCAmelCase , __UpperCAmelCase : Dict = """""", """""" __UpperCAmelCase : str = len(lowerCAmelCase__ ) for i in range(len(lowerCAmelCase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __UpperCAmelCase : str = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) index += 1 __UpperCAmelCase : Any = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": __UpperCAmelCase : Union[str, Any] = lexicon[curr_string] result += last_match_id return result def lowercase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ): """simple docstring""" __UpperCAmelCase : int = os.path.getsize(lowerCAmelCase__ ) __UpperCAmelCase : int = bin(lowerCAmelCase__ )[2:] __UpperCAmelCase : List[Any] = len(lowerCAmelCase__ ) return "0" * (length_length - 1) + file_length_binary + compressed def lowercase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ): """simple docstring""" __UpperCAmelCase : List[str] = 8 try: with open(lowerCAmelCase__ , """wb""" ) as opened_file: __UpperCAmelCase : Any = [ to_write[i : i + byte_length] for i in range(0 , len(lowerCAmelCase__ ) , lowerCAmelCase__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("""10000000""" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(lowerCAmelCase__ , 2 ).to_bytes(1 , byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def lowercase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ): """simple docstring""" __UpperCAmelCase : Dict = read_file_binary(lowerCAmelCase__ ) __UpperCAmelCase : str = compress_data(lowerCAmelCase__ ) __UpperCAmelCase : List[str] = add_file_length(lowerCAmelCase__ , lowerCAmelCase__ ) write_file_binary(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
254
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer import diffusers from diffusers import ( AutoencoderKL, EulerDiscreteScheduler, StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.schedulers import KarrasDiffusionSchedulers 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 ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() def _snake_case ( _snake_case : Optional[int] ) -> List[Any]: '''simple docstring''' _A = [tensor.shape for tensor in tensor_list] return all(shape == shapes[0] for shape in shapes[1:] ) class lowercase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCAmelCase : Tuple = StableDiffusionLatentUpscalePipeline UpperCAmelCase : Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''height''', '''width''', '''cross_attention_kwargs''', '''negative_prompt_embeds''', '''prompt_embeds''', } UpperCAmelCase : Optional[int] = PipelineTesterMixin.required_optional_params - {'''num_images_per_prompt'''} UpperCAmelCase : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCAmelCase : Any = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess UpperCAmelCase : Tuple = frozenset([] ) UpperCAmelCase : Tuple = True @property def lowerCAmelCase_ ( self : str ): _A = 1 _A = 4 _A = (16, 16) _A = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(_UpperCAmelCase ) return image def lowerCAmelCase_ ( self : List[str] ): torch.manual_seed(0 ) _A = UNetaDConditionModel( act_fn='gelu' , attention_head_dim=8 , norm_num_groups=_UpperCAmelCase , block_out_channels=[32, 32, 64, 64] , time_cond_proj_dim=160 , conv_in_kernel=1 , conv_out_kernel=1 , cross_attention_dim=32 , down_block_types=( 'KDownBlock2D', 'KCrossAttnDownBlock2D', 'KCrossAttnDownBlock2D', 'KCrossAttnDownBlock2D', ) , in_channels=8 , mid_block_type=_UpperCAmelCase , only_cross_attention=_UpperCAmelCase , out_channels=5 , resnet_time_scale_shift='scale_shift' , time_embedding_type='fourier' , timestep_post_act='gelu' , up_block_types=('KCrossAttnUpBlock2D', 'KCrossAttnUpBlock2D', 'KCrossAttnUpBlock2D', 'KUpBlock2D') , ) _A = AutoencoderKL( block_out_channels=[32, 32, 64, 64] , in_channels=3 , out_channels=3 , down_block_types=[ 'DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D', ] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) _A = EulerDiscreteScheduler(prediction_type='sample' ) _A = 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=1_000 , hidden_act='quick_gelu' , projection_dim=512 , ) _A = CLIPTextModel(_UpperCAmelCase ) _A = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _A = { 'unet': model.eval(), 'vae': vae.eval(), 'scheduler': scheduler, 'text_encoder': text_encoder, 'tokenizer': tokenizer, } return components def lowerCAmelCase_ ( self : Tuple , _UpperCAmelCase : Any , _UpperCAmelCase : Optional[Any]=0 ): if str(_UpperCAmelCase ).startswith('mps' ): _A = torch.manual_seed(_UpperCAmelCase ) else: _A = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) _A = { 'prompt': 'A painting of a squirrel eating a burger', 'image': self.dummy_image.cpu(), 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def lowerCAmelCase_ ( self : Union[str, Any] ): _A = 'cpu' _A = self.get_dummy_components() _A = self.pipeline_class(**_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) _A = self.get_dummy_inputs(_UpperCAmelCase ) _A = pipe(**_UpperCAmelCase ).images _A = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 256, 256, 3) ) _A = np.array( [0.4722_2412, 0.4192_1633, 0.4471_7434, 0.4687_4192, 0.4258_8258, 0.4615_0726, 0.467_7534, 0.4558_3832, 0.4857_9055] ) _A = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_UpperCAmelCase , 1E-3 ) def lowerCAmelCase_ ( self : str ): super().test_attention_slicing_forward_pass(expected_max_diff=7E-3 ) def lowerCAmelCase_ ( self : int ): super().test_cpu_offload_forward_pass(expected_max_diff=3E-3 ) def lowerCAmelCase_ ( self : List[Any] ): super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def lowerCAmelCase_ ( self : Optional[int] ): super().test_inference_batch_single_identical(expected_max_diff=7E-3 ) def lowerCAmelCase_ ( self : List[Any] ): super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3E-3 ) def lowerCAmelCase_ ( self : Optional[Any] ): super().test_save_load_local(expected_max_difference=3E-3 ) def lowerCAmelCase_ ( self : List[Any] ): super().test_save_load_optional_components(expected_max_difference=3E-3 ) def lowerCAmelCase_ ( self : int ): _A = [ 'DDIMScheduler', 'DDPMScheduler', 'PNDMScheduler', 'HeunDiscreteScheduler', 'EulerAncestralDiscreteScheduler', 'KDPM2DiscreteScheduler', 'KDPM2AncestralDiscreteScheduler', 'DPMSolverSDEScheduler', ] _A = self.get_dummy_components() _A = self.pipeline_class(**_UpperCAmelCase ) # make sure that PNDM does not need warm-up pipe.scheduler.register_to_config(skip_prk_steps=_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) _A = self.get_dummy_inputs(_UpperCAmelCase ) _A = 2 _A = [] for scheduler_enum in KarrasDiffusionSchedulers: if scheduler_enum.name in skip_schedulers: # no sigma schedulers are not supported # no schedulers continue _A = getattr(_UpperCAmelCase , scheduler_enum.name ) _A = scheduler_cls.from_config(pipe.scheduler.config ) _A = pipe(**_UpperCAmelCase )[0] outputs.append(_UpperCAmelCase ) assert check_same_shape(_UpperCAmelCase ) @require_torch_gpu @slow class lowercase_ ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase_ ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase_ ( self : Optional[int] ): _A = torch.manual_seed(33 ) _A = StableDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' , torch_dtype=torch.floataa ) pipe.to('cuda' ) _A = StableDiffusionLatentUpscalePipeline.from_pretrained( 'stabilityai/sd-x2-latent-upscaler' , torch_dtype=torch.floataa ) upscaler.to('cuda' ) _A = 'a photo of an astronaut high resolution, unreal engine, ultra realistic' _A = pipe(_UpperCAmelCase , generator=_UpperCAmelCase , output_type='latent' ).images _A = upscaler( prompt=_UpperCAmelCase , image=_UpperCAmelCase , num_inference_steps=20 , guidance_scale=0 , generator=_UpperCAmelCase , output_type='np' , ).images[0] _A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy' ) assert np.abs((expected_image - image).mean() ) < 5E-2 def lowerCAmelCase_ ( self : str ): _A = torch.manual_seed(33 ) _A = StableDiffusionLatentUpscalePipeline.from_pretrained( 'stabilityai/sd-x2-latent-upscaler' , torch_dtype=torch.floataa ) upscaler.to('cuda' ) _A = 'the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas' _A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png' ) _A = upscaler( prompt=_UpperCAmelCase , image=_UpperCAmelCase , num_inference_steps=20 , guidance_scale=0 , generator=_UpperCAmelCase , output_type='np' , ).images[0] _A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy' ) assert np.abs((expected_image - image).max() ) < 5E-2
271
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel a = logging.getLogger(__name__) def _snake_case ( _snake_case : str , _snake_case : Tuple ) -> Any: '''simple docstring''' if os.path.exists(_snake_case ): if os.path.exists(os.path.join(_snake_case , 'config.json' ) ) and os.path.isfile( os.path.join(_snake_case , 'config.json' ) ): os.remove(os.path.join(_snake_case , 'config.json' ) ) if os.path.exists(os.path.join(_snake_case , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(_snake_case , 'pytorch_model.bin' ) ): os.remove(os.path.join(_snake_case , 'pytorch_model.bin' ) ) else: os.makedirs(_snake_case ) model.save_pretrained(_snake_case ) def _snake_case ( _snake_case : Union[str, Any] , _snake_case : Optional[int]=False ) -> Tuple: '''simple docstring''' _A = 2 if unlogit: _A = torch.pow(_snake_case , _snake_case ) _A = p * torch.log(_snake_case ) _A = 0 return -plogp.sum(dim=-1 ) def _snake_case ( _snake_case : Optional[Any] ) -> int: '''simple docstring''' logger.info('lv, h >\t' + '\t'.join(F'''{x + 1}''' for x in range(len(_snake_case ) ) ) ) for row in range(len(_snake_case ) ): if tensor.dtype != torch.long: logger.info(F'''layer {row + 1}:\t''' + '\t'.join(F'''{x:.5f}''' for x in tensor[row].cpu().data ) ) else: logger.info(F'''layer {row + 1}:\t''' + '\t'.join(F'''{x:d}''' for x in tensor[row].cpu().data ) ) def _snake_case ( _snake_case : List[str] , _snake_case : Dict , _snake_case : List[str] , _snake_case : Union[str, Any]=True , _snake_case : Any=True , _snake_case : List[str]=None , _snake_case : List[Any]=False ) -> int: '''simple docstring''' _A , _A = model.config.num_hidden_layers, model.config.num_attention_heads _A = torch.zeros(_snake_case , _snake_case ).to(args.device ) _A = torch.zeros(_snake_case , _snake_case ).to(args.device ) if head_mask is None: _A = torch.ones(_snake_case , _snake_case ).to(args.device ) head_mask.requires_grad_(requires_grad=_snake_case ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: _A = None _A = 0.0 _A = 0.0 for step, inputs in enumerate(tqdm(_snake_case , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): _A = tuple(t.to(args.device ) for t in inputs ) ((_A) , ) = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) _A = model(_snake_case , labels=_snake_case , head_mask=_snake_case ) # (loss), lm_logits, presents, (all hidden_states), (attentions) _A , _A , _A = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(_snake_case ): _A = entropy(attn.detach() , _snake_case ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(_snake_case ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: _A = 2 _A = torch.pow(torch.pow(_snake_case , _snake_case ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1E-20 if not args.dont_normalize_global_importance: _A = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(_snake_case ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(_snake_case ) logger.info('Head ranked by importance scores' ) _A = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) _A = torch.arange( head_importance.numel() , device=args.device ) _A = head_ranks.view_as(_snake_case ) print_ad_tensor(_snake_case ) return attn_entropy, head_importance, total_loss def _snake_case ( _snake_case : Any , _snake_case : Tuple , _snake_case : List[Any] ) -> List[str]: '''simple docstring''' _A , _A , _A = compute_heads_importance(_snake_case , _snake_case , _snake_case , compute_entropy=_snake_case ) _A = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _snake_case , original_score * args.masking_threshold ) _A = torch.ones_like(_snake_case ) _A = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) _A = original_score while current_score >= original_score * args.masking_threshold: _A = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads _A = float('Inf' ) _A = head_importance.view(-1 ).sort()[1] if len(_snake_case ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads _A = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) _A = new_head_mask.view(-1 ) _A = 0.0 _A = new_head_mask.view_as(_snake_case ) _A = new_head_mask.clone().detach() print_ad_tensor(_snake_case ) # Compute metric and head importance again _A , _A , _A = compute_heads_importance( _snake_case , _snake_case , _snake_case , compute_entropy=_snake_case , head_mask=_snake_case ) _A = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , _snake_case , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_00 , ) logger.info('Final head mask' ) print_ad_tensor(_snake_case ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def _snake_case ( _snake_case : Union[str, Any] , _snake_case : Any , _snake_case : Dict , _snake_case : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' _A = datetime.now() _A , _A , _A = compute_heads_importance( _snake_case , _snake_case , _snake_case , compute_entropy=_snake_case , compute_importance=_snake_case , head_mask=_snake_case ) _A = 1 / loss _A = datetime.now() - before_time _A = sum(p.numel() for p in model.parameters() ) _A = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_snake_case ) ) } for k, v in heads_to_prune.items(): if isinstance(_snake_case , _snake_case ): _A = [ v, ] assert sum(len(_snake_case ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_snake_case ) _A = sum(p.numel() for p in model.parameters() ) _A = datetime.now() _A , _A , _A = compute_heads_importance( _snake_case , _snake_case , _snake_case , compute_entropy=_snake_case , compute_importance=_snake_case , head_mask=_snake_case , actually_pruned=_snake_case , ) _A = 1 / loss _A = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , _snake_case , _snake_case , pruned_num_params / original_num_params * 1_00 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , _snake_case , _snake_case ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 1_00 ) save_model(_snake_case , args.output_dir ) def _snake_case ( ) -> Dict: '''simple docstring''' _A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=_snake_case , type=_snake_case , required=_snake_case , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=_snake_case , type=_snake_case , required=_snake_case , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=_snake_case , type=_snake_case , required=_snake_case , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=_snake_case , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=_snake_case , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=_snake_case , type=_snake_case , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=_snake_case , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=_snake_case , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=_snake_case , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=_snake_case , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=1_28 , type=_snake_case , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=_snake_case , help='Batch size.' ) parser.add_argument('--seed' , type=_snake_case , default=42 ) parser.add_argument('--local_rank' , type=_snake_case , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=_snake_case , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=_snake_case , default='' , help='Can be used for distant debugging.' ) _A = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_snake_case ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: _A = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) _A = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) _A = torch.device('cuda' , args.local_rank ) _A = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) _A = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: _A = nn.parallel.DistributedDataParallel( _snake_case , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_snake_case ) elif args.n_gpu > 1: _A = nn.DataParallel(_snake_case ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=_snake_case ) torch.save(_snake_case , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , _snake_case ) # Prepare dataset _A = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) _A = (torch.from_numpy(_snake_case ),) _A = TensorDataset(*_snake_case ) _A = RandomSampler(_snake_case ) _A = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(_snake_case , _snake_case , _snake_case ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: _A = mask_heads(_snake_case , _snake_case , _snake_case ) prune_heads(_snake_case , _snake_case , _snake_case , _snake_case ) if __name__ == "__main__": main()
271
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case_( a__ , a__ , unittest.TestCase ): __UpperCamelCase = StableDiffusionXLImgaImgPipeline __UpperCamelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} __UpperCamelCase = PipelineTesterMixin.required_optional_params - {'''latents'''} __UpperCamelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __UpperCamelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS __UpperCamelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowerCamelCase__ ( self : int ): torch.manual_seed(0 ) lowerCAmelCase : str = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , attention_head_dim=(2, 4) , use_linear_projection=UpperCamelCase_ , addition_embed_type='''text_time''' , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=8_0 , cross_attention_dim=6_4 , ) lowerCAmelCase : Optional[Any] = EulerDiscreteScheduler( beta_start=0.00_085 , beta_end=0.012 , steps_offset=1 , beta_schedule='''scaled_linear''' , timestep_spacing='''leading''' , ) torch.manual_seed(0 ) lowerCAmelCase : Dict = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) lowerCAmelCase : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act='''gelu''' , projection_dim=3_2 , ) lowerCAmelCase : int = CLIPTextModel(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=UpperCamelCase_ ) lowerCAmelCase : str = CLIPTextModelWithProjection(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' , local_files_only=UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''text_encoder_2''': text_encoder_a, '''tokenizer_2''': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : int=0 ): lowerCAmelCase : Union[str, Any] = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(UpperCamelCase_ ) ).to(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = image / 2 + 0.5 if str(UpperCamelCase_ ).startswith('''mps''' ): lowerCAmelCase : Any = torch.manual_seed(UpperCamelCase_ ) else: lowerCAmelCase : str = torch.Generator(device=UpperCamelCase_ ).manual_seed(UpperCamelCase_ ) lowerCAmelCase : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 5.0, '''output_type''': '''numpy''', '''strength''': 0.75, } return inputs def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : Union[str, Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowerCAmelCase : Optional[Any] = self.get_dummy_components() lowerCAmelCase : Optional[int] = StableDiffusionXLImgaImgPipeline(**UpperCamelCase_ ) lowerCAmelCase : Tuple = sd_pipe.to(UpperCamelCase_ ) sd_pipe.set_progress_bar_config(disable=UpperCamelCase_ ) lowerCAmelCase : List[str] = self.get_dummy_inputs(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = sd_pipe(**UpperCamelCase_ ).images lowerCAmelCase : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) lowerCAmelCase : Optional[Any] = np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase__ ( self : int ): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def lowerCamelCase__ ( self : int ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def lowerCamelCase__ ( self : str ): pass def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : List[Any] = self.get_dummy_components() lowerCAmelCase : int = StableDiffusionXLImgaImgPipeline(**UpperCamelCase_ ) lowerCAmelCase : int = sd_pipe.to(UpperCamelCase_ ) lowerCAmelCase : Any = sd_pipe.to(UpperCamelCase_ ) sd_pipe.set_progress_bar_config(disable=UpperCamelCase_ ) # forward without prompt embeds lowerCAmelCase : Tuple = self.get_dummy_inputs(UpperCamelCase_ ) lowerCAmelCase : Tuple = 3 * ['''this is a negative prompt'''] lowerCAmelCase : Dict = negative_prompt lowerCAmelCase : Tuple = 3 * [inputs['''prompt''']] lowerCAmelCase : Union[str, Any] = sd_pipe(**UpperCamelCase_ ) lowerCAmelCase : str = output.images[0, -3:, -3:, -1] # forward with prompt embeds lowerCAmelCase : Union[str, Any] = self.get_dummy_inputs(UpperCamelCase_ ) lowerCAmelCase : int = 3 * ['''this is a negative prompt'''] lowerCAmelCase : Optional[int] = 3 * [inputs.pop('''prompt''' )] ( ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ) : Tuple = sd_pipe.encode_prompt(UpperCamelCase_ , negative_prompt=UpperCamelCase_ ) lowerCAmelCase : Any = sd_pipe( **UpperCamelCase_ , prompt_embeds=UpperCamelCase_ , negative_prompt_embeds=UpperCamelCase_ , pooled_prompt_embeds=UpperCamelCase_ , negative_pooled_prompt_embeds=UpperCamelCase_ , ) lowerCAmelCase : str = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : int , UpperCamelCase_ : Union[str, Any]="cpu" , UpperCamelCase_ : Optional[int]=torch.floataa , UpperCamelCase_ : int=0 ): lowerCAmelCase : Union[str, Any] = torch.Generator(device=UpperCamelCase_ ).manual_seed(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = np.random.RandomState(UpperCamelCase_ ).standard_normal((1, 4, 6_4, 6_4) ) lowerCAmelCase : Dict = torch.from_numpy(UpperCamelCase_ ).to(device=UpperCamelCase_ , dtype=UpperCamelCase_ ) lowerCAmelCase : str = { '''prompt''': '''a photograph of an astronaut riding a horse''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : Union[str, Any] = DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''' ) pipe.to(UpperCamelCase_ ) pipe.set_progress_bar_config(disable=UpperCamelCase_ ) lowerCAmelCase : List[str] = self.get_inputs(UpperCamelCase_ ) lowerCAmelCase : Any = pipe(**UpperCamelCase_ ).images lowerCAmelCase : List[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase : Dict = np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
60
import random def __lowerCamelCase ( snake_case__ ) -> bool: """simple docstring""" _SCREAMING_SNAKE_CASE = num - 1 _SCREAMING_SNAKE_CASE = 0 while s % 2 == 0: _SCREAMING_SNAKE_CASE = s // 2 t += 1 for _ in range(5 ): _SCREAMING_SNAKE_CASE = random.randrange(2 ,num - 1 ) _SCREAMING_SNAKE_CASE = pow(snake_case__ ,snake_case__ ,snake_case__ ) if v != 1: _SCREAMING_SNAKE_CASE = 0 while v != (num - 1): if i == t - 1: return False else: _SCREAMING_SNAKE_CASE = i + 1 _SCREAMING_SNAKE_CASE = (v**2) % num return True def __lowerCamelCase ( snake_case__ ) -> bool: """simple docstring""" if num < 2: return False _SCREAMING_SNAKE_CASE = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 1_01, 1_03, 1_07, 1_09, 1_13, 1_27, 1_31, 1_37, 1_39, 1_49, 1_51, 1_57, 1_63, 1_67, 1_73, 1_79, 1_81, 1_91, 1_93, 1_97, 1_99, 2_11, 2_23, 2_27, 2_29, 2_33, 2_39, 2_41, 2_51, 2_57, 2_63, 2_69, 2_71, 2_77, 2_81, 2_83, 2_93, 3_07, 3_11, 3_13, 3_17, 3_31, 3_37, 3_47, 3_49, 3_53, 3_59, 3_67, 3_73, 3_79, 3_83, 3_89, 3_97, 4_01, 4_09, 4_19, 4_21, 4_31, 4_33, 4_39, 4_43, 4_49, 4_57, 4_61, 4_63, 4_67, 4_79, 4_87, 4_91, 4_99, 5_03, 5_09, 5_21, 5_23, 5_41, 5_47, 5_57, 5_63, 5_69, 5_71, 5_77, 5_87, 5_93, 5_99, 6_01, 6_07, 6_13, 6_17, 6_19, 6_31, 6_41, 6_43, 6_47, 6_53, 6_59, 6_61, 6_73, 6_77, 6_83, 6_91, 7_01, 7_09, 7_19, 7_27, 7_33, 7_39, 7_43, 7_51, 7_57, 7_61, 7_69, 7_73, 7_87, 7_97, 8_09, 8_11, 8_21, 8_23, 8_27, 8_29, 8_39, 8_53, 8_57, 8_59, 8_63, 8_77, 8_81, 8_83, 8_87, 9_07, 9_11, 9_19, 9_29, 9_37, 9_41, 9_47, 9_53, 9_67, 9_71, 9_77, 9_83, 9_91, 9_97, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(snake_case__ ) def __lowerCamelCase ( snake_case__ = 10_24 ) -> int: """simple docstring""" while True: _SCREAMING_SNAKE_CASE = random.randrange(2 ** (keysize - 1) ,2 ** (keysize) ) if is_prime_low_num(snake_case__ ): return num if __name__ == "__main__": UpperCamelCase = generate_large_prime() print(('''Prime number:''', num)) print(('''is_prime_low_num:''', is_prime_low_num(num)))
306
0
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 = logging.get_logger(__name__) UpperCamelCase = '▁' UpperCamelCase = {'vocab_file': 'sentencepiece.bpe.model'} UpperCamelCase = { 'vocab_file': { 'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model', } } UpperCamelCase = { 'facebook/xglm-564M': 2048, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int="<s>" , SCREAMING_SNAKE_CASE__ : List[Any]="</s>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[Any]="<pad>" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> None: lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer lowerCAmelCase__ = 7 lowerCAmelCase__ = [f'<madeupword{i}>' for i in range(self.num_madeup_words )] lowerCAmelCase__ = 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=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) 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' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowerCAmelCase__ = 1 # Mimic fairseq token-to-id alignment for the first 4 token lowerCAmelCase__ = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} lowerCAmelCase__ = len(self.sp_model ) lowerCAmelCase__ = {f'<madeupword{i}>': sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Any ) -> int: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None lowerCAmelCase__ = self.sp_model.serialized_model_proto() return state def __setstate__( self : List[str] , SCREAMING_SNAKE_CASE__ : Any ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.sep_token_id] + token_ids_a lowerCAmelCase__ = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [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 a ( self : int ) -> Any: return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def a ( self : str ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int ) -> Union[str, Any]: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowerCAmelCase__ = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: 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 a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Dict: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , " " ).strip() return out_string def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
221
from __future__ import annotations UpperCamelCase = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def _A ( lowerCAmelCase_ : list[list[int]] , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : list[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : list[list[int]] , ): """simple docstring""" lowerCAmelCase__ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(lowerCAmelCase_ ) ) ] # the reference grid lowerCAmelCase__ = 1 lowerCAmelCase__ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(lowerCAmelCase_ ) ) ] # the action grid lowerCAmelCase__ = init[0] lowerCAmelCase__ = init[1] lowerCAmelCase__ = 0 lowerCAmelCase__ = g + heuristic[x][y] # cost from starting cell to destination cell lowerCAmelCase__ = [[f, g, x, y]] lowerCAmelCase__ = False # flag that is set when search is complete lowerCAmelCase__ = False # flag set if we can't find expand while not found and not resign: if len(lowerCAmelCase_ ) == 0: raise ValueError("Algorithm is unable to find solution" ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() lowerCAmelCase__ = cell.pop() lowerCAmelCase__ = next_cell[2] lowerCAmelCase__ = next_cell[3] lowerCAmelCase__ = next_cell[1] if x == goal[0] and y == goal[1]: lowerCAmelCase__ = True else: for i in range(len(lowerCAmelCase_ ) ): # to try out different valid actions lowerCAmelCase__ = x + DIRECTIONS[i][0] lowerCAmelCase__ = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(lowerCAmelCase_ ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: lowerCAmelCase__ = g + cost lowerCAmelCase__ = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) lowerCAmelCase__ = 1 lowerCAmelCase__ = i lowerCAmelCase__ = [] lowerCAmelCase__ = goal[0] lowerCAmelCase__ = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: lowerCAmelCase__ = x - DIRECTIONS[action[x][y]][0] lowerCAmelCase__ = y - DIRECTIONS[action[x][y]][1] lowerCAmelCase__ = xa lowerCAmelCase__ = ya invpath.append([x, y] ) lowerCAmelCase__ = [] for i in range(len(lowerCAmelCase_ ) ): path.append(invpath[len(lowerCAmelCase_ ) - 1 - i] ) return path, action if __name__ == "__main__": UpperCamelCase = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] UpperCamelCase = [0, 0] # all coordinates are given in format [y,x] UpperCamelCase = [len(grid) - 1, len(grid[0]) - 1] UpperCamelCase = 1 # the cost map which pushes the path closer to the goal UpperCamelCase = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): UpperCamelCase = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map UpperCamelCase = 99 UpperCamelCase , UpperCamelCase = search(grid, init, goal, cost, heuristic) print('ACTION MAP') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
221
1
from __future__ import annotations class snake_case__ : """simple docstring""" def __init__( self , __lowercase=None ) -> str: """simple docstring""" a__ : int = data a__ : List[str] = None def __repr__( self ) -> Optional[Any]: """simple docstring""" a__ : Tuple = [] a__ : Tuple = self while temp: string_rep.append(F'''{temp.data}''' ) a__ : List[Any] = temp.next return "->".join(_snake_case ) def lowerCAmelCase_ ( _lowercase : list) -> List[str]: """simple docstring""" if not elements_list: raise Exception("""The Elements List is empty""") a__ : Dict = Node(elements_list[0]) for i in range(1 , len(__A)): a__ : Optional[int] = Node(elements_list[i]) a__ : Union[str, Any] = current.next return head def lowerCAmelCase_ ( _lowercase : Node) -> None: """simple docstring""" if head_node is not None and isinstance(__A , __A): print_reverse(head_node.next) print(head_node.data) def lowerCAmelCase_ ( ) -> List[str]: """simple docstring""" from doctest import testmod testmod() a__ : Optional[Any] = make_linked_list([14, 52, 14, 12, 43]) print("""Linked List:""") print(__A) print("""Elements in Reverse:""") print_reverse(__A) if __name__ == "__main__": main()
170
import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class __snake_case : @staticmethod def lowerCamelCase ( *_snake_case : Optional[int] , **_snake_case : int): """simple docstring""" pass def A (__A : Image ) -> str: """simple docstring""" UpperCAmelCase_ = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class __snake_case ( unittest.TestCase ): UpperCAmelCase__ : Tuple = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def lowerCamelCase ( self : Tuple , _snake_case : Optional[Any] , _snake_case : Optional[Any] , _snake_case : List[str]): """simple docstring""" UpperCAmelCase_ = DepthEstimationPipeline(model=_snake_case , image_processor=_snake_case) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def lowerCamelCase ( self : str , _snake_case : Optional[int] , _snake_case : List[str]): """simple docstring""" UpperCAmelCase_ = depth_estimator('''./tests/fixtures/tests_samples/COCO/000000039769.png''') self.assertEqual({'''predicted_depth''': ANY(torch.Tensor), '''depth''': ANY(Image.Image)} , _snake_case) import datasets UpperCAmelCase_ = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''') UpperCAmelCase_ = depth_estimator( [ Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ]) self.assertEqual( [ {'''predicted_depth''': ANY(torch.Tensor), '''depth''': ANY(Image.Image)}, {'''predicted_depth''': ANY(torch.Tensor), '''depth''': ANY(Image.Image)}, {'''predicted_depth''': ANY(torch.Tensor), '''depth''': ANY(Image.Image)}, {'''predicted_depth''': ANY(torch.Tensor), '''depth''': ANY(Image.Image)}, {'''predicted_depth''': ANY(torch.Tensor), '''depth''': ANY(Image.Image)}, ] , _snake_case , ) @require_tf @unittest.skip('''Depth estimation is not implemented in TF''') def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" pass @slow @require_torch def lowerCamelCase ( self : List[str]): """simple docstring""" UpperCAmelCase_ = '''Intel/dpt-large''' UpperCAmelCase_ = pipeline('''depth-estimation''' , model=_snake_case) UpperCAmelCase_ = depth_estimator('''http://images.cocodataset.org/val2017/000000039769.jpg''') UpperCAmelCase_ = hashimage(outputs['''depth''']) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['''predicted_depth'''].max().item()) , 2_9.3_0_4) self.assertEqual(nested_simplify(outputs['''predicted_depth'''].min().item()) , 2.6_6_2) @require_torch def lowerCamelCase ( self : Optional[Any]): """simple docstring""" self.skipTest('''There is not hf-internal-testing tiny model for either GLPN nor DPT''')
51
0
from __future__ import annotations def __SCREAMING_SNAKE_CASE ( A_ ): return [ord(A_ ) - 96 for elem in plain] def __SCREAMING_SNAKE_CASE ( A_ ): return "".join(chr(elem + 96 ) for elem in encoded ) def __SCREAMING_SNAKE_CASE ( ): lowerCAmelCase__ : Dict = encode(input('''-> ''' ).strip().lower() ) print('''Encoded: ''' , A_ ) print('''Decoded:''' , decode(A_ ) ) if __name__ == "__main__": main()
371
"""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 : Optional[int] = logging.get_logger(__name__) __UpperCamelCase : List[Any] = '''▁''' __UpperCamelCase : Union[str, Any] = {'''vocab_file''': '''spiece.model'''} __UpperCamelCase : Tuple = { '''vocab_file''': { '''google/reformer-crime-and-punishment''': ( '''https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model''' ) } } __UpperCamelCase : Optional[Any] = { '''google/reformer-crime-and-punishment''': 5_2_4_2_8_8, } class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["input_ids", "attention_mask"] def __init__( self : List[Any] ,lowercase_ : List[str] ,lowercase_ : Optional[int]="</s>" ,lowercase_ : List[Any]="<unk>" ,lowercase_ : Optional[Any]=[] ,lowercase_ : Optional[Dict[str, Any]] = None ,**lowercase_ : int ,): lowerCAmelCase__ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=lowercase_ ,unk_token=lowercase_ ,additional_special_tokens=lowercase_ ,sp_model_kwargs=self.sp_model_kwargs ,**lowercase_ ,) lowerCAmelCase__ : List[str] = vocab_file lowerCAmelCase__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase_ ) @property def __lowerCAmelCase ( self : List[str] ): return self.sp_model.get_piece_size() def __lowerCAmelCase ( self : Any ): lowerCAmelCase__ : Optional[Any] = {self.convert_ids_to_tokens(lowercase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : List[str] ): lowerCAmelCase__ : str = self.__dict__.copy() lowerCAmelCase__ : Any = None return state def __setstate__( self : List[str] ,lowercase_ : Any ): lowerCAmelCase__ : Union[str, Any] = d # for backward compatibility if not hasattr(self ,'''sp_model_kwargs''' ): lowerCAmelCase__ : Tuple = {} lowerCAmelCase__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : Dict ,lowercase_ : str ): return self.sp_model.encode(lowercase_ ,out_type=lowercase_ ) def __lowerCAmelCase ( self : List[Any] ,lowercase_ : int ): return self.sp_model.piece_to_id(lowercase_ ) def __lowerCAmelCase ( self : Optional[Any] ,lowercase_ : Dict ): if index < self.sp_model.get_piece_size(): lowerCAmelCase__ : List[Any] = self.sp_model.IdToPiece(lowercase_ ) return token def __lowerCAmelCase ( self : Optional[Any] ,lowercase_ : List[Any] ): lowerCAmelCase__ : int = [] lowerCAmelCase__ : Optional[Any] = '''''' 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 lowerCAmelCase__ : Dict = [] else: current_sub_tokens.append(lowercase_ ) out_string += self.sp_model.decode(lowercase_ ) return out_string.strip() def __lowerCAmelCase ( self : Optional[Any] ,lowercase_ : str ,lowercase_ : Optional[str] = None ): if not os.path.isdir(lowercase_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ : 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: lowerCAmelCase__ : Any = self.sp_model.serialized_model_proto() fi.write(lowercase_ ) return (out_vocab_file,)
74
0
"""simple docstring""" import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging _a : List[Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[Any]=None ,_lowerCamelCase : Union[str, Any]=None ) -> Dict: return field(default_factory=lambda: default ,metadata=_lowerCamelCase ) @dataclass class __A : _UpperCamelCase : List[str] = 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" ) } , ) _UpperCamelCase : List[int] = list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) _UpperCamelCase : List[int] = list_field( default=[8, 32, 128, 512] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) _UpperCamelCase : bool = field( default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) _UpperCamelCase : bool = field( default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) _UpperCamelCase : bool = field( default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) _UpperCamelCase : bool = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Use FP16 to accelerate inference."} ) _UpperCamelCase : bool = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Benchmark training of model"} ) _UpperCamelCase : bool = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Verbose memory tracing"} ) _UpperCamelCase : bool = field( default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) _UpperCamelCase : bool = field( default=SCREAMING_SNAKE_CASE_ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) _UpperCamelCase : bool = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Trace memory line by line"} ) _UpperCamelCase : bool = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Save result to a CSV file"} ) _UpperCamelCase : bool = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Save all print statements in a log file"} ) _UpperCamelCase : bool = field(default=SCREAMING_SNAKE_CASE_ , metadata={"help": "Whether to print environment information"} ) _UpperCamelCase : bool = field( default=SCREAMING_SNAKE_CASE_ , 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." ) } , ) _UpperCamelCase : str = field( default=f"""inference_time_{round(time() )}.csv""" , metadata={"help": "CSV filename used if saving time results to csv."} , ) _UpperCamelCase : str = field( default=f"""inference_memory_{round(time() )}.csv""" , metadata={"help": "CSV filename used if saving memory results to csv."} , ) _UpperCamelCase : str = field( default=f"""train_time_{round(time() )}.csv""" , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) _UpperCamelCase : str = field( default=f"""train_memory_{round(time() )}.csv""" , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) _UpperCamelCase : str = field( default=f"""env_info_{round(time() )}.csv""" , metadata={"help": "CSV filename used if saving environment information."} , ) _UpperCamelCase : str = field( default=f"""log_{round(time() )}.csv""" , metadata={"help": "Log filename used if print statements are saved in log."} , ) _UpperCamelCase : int = field(default=3 , metadata={"help": "Times an experiment will be run."} ) _UpperCamelCase : bool = field( default=SCREAMING_SNAKE_CASE_ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def __A ( 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.""" , a__ , ) def __A ( self ): return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def __A ( 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 __A ( 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
44
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer _a : List[Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Union[str, Any] = { 'vocab_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt' ), 'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt', 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'google/electra-small-generator': ( 'https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json' ), 'google/electra-base-generator': ( 'https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json' ), 'google/electra-large-generator': ( 'https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json' ), 'google/electra-small-discriminator': ( 'https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json' ), 'google/electra-base-discriminator': ( 'https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json' ), 'google/electra-large-discriminator': ( 'https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json' ), }, } _a : Optional[Any] = { 'google/electra-small-generator': 512, 'google/electra-base-generator': 512, 'google/electra-large-generator': 512, 'google/electra-small-discriminator': 512, 'google/electra-base-discriminator': 512, 'google/electra-large-discriminator': 512, } _a : Any = { 'google/electra-small-generator': {'do_lower_case': True}, 'google/electra-base-generator': {'do_lower_case': True}, 'google/electra-large-generator': {'do_lower_case': True}, 'google/electra-small-discriminator': {'do_lower_case': True}, 'google/electra-base-discriminator': {'do_lower_case': True}, 'google/electra-large-discriminator': {'do_lower_case': True}, } class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = VOCAB_FILES_NAMES _UpperCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_INIT_CONFIGURATION _UpperCamelCase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : Optional[Any] = ElectraTokenizer def __init__( self , a__=None , a__=None , a__=True , a__="[UNK]" , a__="[SEP]" , a__="[PAD]" , a__="[CLS]" , a__="[MASK]" , a__=True , a__=None , **a__ , ): super().__init__( a__ , tokenizer_file=a__ , do_lower_case=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , tokenize_chinese_chars=a__ , strip_accents=a__ , **a__ , ) _lowerCAmelCase : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , a__ ) != do_lower_case or normalizer_state.get("""strip_accents""" , a__ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , a__ ) != tokenize_chinese_chars ): _lowerCAmelCase : Dict = getattr(a__ , normalizer_state.pop("""type""" ) ) _lowerCAmelCase : int = do_lower_case _lowerCAmelCase : str = strip_accents _lowerCAmelCase : Dict = tokenize_chinese_chars _lowerCAmelCase : str = normalizer_class(**a__ ) _lowerCAmelCase : List[str] = do_lower_case def __A ( self , a__ , a__=None ): _lowerCAmelCase : int = [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 __A ( self , a__ , a__ = None ): _lowerCAmelCase : List[str] = [self.sep_token_id] _lowerCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , a__ , a__ = None ): _lowerCAmelCase : Optional[Any] = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ )
44
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class _A ( unittest.TestCase ): """simple docstring""" def __snake_case ( self : Tuple): a : Tuple = tempfile.mkdtemp() # fmt: off a : Any = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on a : List[Any] = dict(zip(a_ , range(len(a_)))) a : Dict = ["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""] a : Union[str, Any] = {"unk_token": "<unk>"} a : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"]) a : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"]) with open(self.vocab_file , "w" , encoding="utf-8") as fp: fp.write(json.dumps(a_) + "\n") with open(self.merges_file , "w" , encoding="utf-8") as fp: fp.write("\n".join(a_)) a : str = { "do_resize": True, "size": 20, "do_center_crop": True, "crop_size": 18, "do_normalize": True, "image_mean": [0.48_145_466, 0.4_578_275, 0.40_821_073], "image_std": [0.26_862_954, 0.26_130_258, 0.27_577_711], } a : Union[str, Any] = os.path.join(self.tmpdirname , a_) with open(self.image_processor_file , "w" , encoding="utf-8") as fp: json.dump(a_ , a_) def __snake_case ( self : Union[str, Any] , **__UpperCAmelCase : List[Any]): return CLIPTokenizer.from_pretrained(self.tmpdirname , **a_) def __snake_case ( self : Tuple , **__UpperCAmelCase : Dict): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a_) def __snake_case ( self : Optional[int] , **__UpperCAmelCase : List[Any]): return CLIPImageProcessor.from_pretrained(self.tmpdirname , **a_) def __snake_case ( self : Optional[int]): shutil.rmtree(self.tmpdirname) def __snake_case ( self : Optional[int]): a : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta)] a : str = [Image.fromarray(np.moveaxis(a_ , 0 , -1)) for x in image_inputs] return image_inputs def __snake_case ( self : Dict): a : Any = self.get_tokenizer() a : Any = self.get_rust_tokenizer() a : Optional[Any] = self.get_image_processor() a : List[Any] = CLIPProcessor(tokenizer=a_ , image_processor=a_) processor_slow.save_pretrained(self.tmpdirname) a : Tuple = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=a_) a : int = CLIPProcessor(tokenizer=a_ , image_processor=a_) processor_fast.save_pretrained(self.tmpdirname) a : List[Any] = CLIPProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab()) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab()) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab()) self.assertIsInstance(processor_slow.tokenizer , a_) self.assertIsInstance(processor_fast.tokenizer , a_) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string()) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string()) self.assertIsInstance(processor_slow.image_processor , a_) self.assertIsInstance(processor_fast.image_processor , a_) def __snake_case ( self : List[Any]): a : str = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor()) processor.save_pretrained(self.tmpdirname) a : Optional[Any] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") a : Any = self.get_image_processor(do_normalize=a_ , padding_value=1.0) a : Any = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=a_ , padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer , a_) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string()) self.assertIsInstance(processor.image_processor , a_) def __snake_case ( self : List[str]): a : Optional[Any] = self.get_image_processor() a : Dict = self.get_tokenizer() a : str = CLIPProcessor(tokenizer=a_ , image_processor=a_) a : Any = self.prepare_image_inputs() a : List[str] = image_processor(a_ , return_tensors="np") a : Optional[Any] = processor(images=a_ , return_tensors="np") for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2) def __snake_case ( self : Optional[int]): a : List[str] = self.get_image_processor() a : Any = self.get_tokenizer() a : Optional[Any] = CLIPProcessor(tokenizer=a_ , image_processor=a_) a : Union[str, Any] = "lower newer" a : str = processor(text=a_) a : int = tokenizer(a_) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def __snake_case ( self : List[str]): a : Any = self.get_image_processor() a : Tuple = self.get_tokenizer() a : List[str] = CLIPProcessor(tokenizer=a_ , image_processor=a_) a : Dict = "lower newer" a : Tuple = self.prepare_image_inputs() a : Optional[Any] = processor(text=a_ , images=a_) self.assertListEqual(list(inputs.keys()) , ["input_ids", "attention_mask", "pixel_values"]) # test if it raises when no input is passed with pytest.raises(a_): processor() def __snake_case ( self : Any): a : Any = self.get_image_processor() a : Optional[int] = self.get_tokenizer() a : int = CLIPProcessor(tokenizer=a_ , image_processor=a_) a : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a : Union[str, Any] = processor.batch_decode(a_) a : Optional[int] = tokenizer.batch_decode(a_) self.assertListEqual(a_ , a_) def __snake_case ( self : Union[str, Any]): a : List[Any] = self.get_image_processor() a : Union[str, Any] = self.get_tokenizer() a : Union[str, Any] = CLIPProcessor(tokenizer=a_ , image_processor=a_) a : List[Any] = "lower newer" a : Optional[Any] = self.prepare_image_inputs() a : Optional[Any] = processor(text=a_ , images=a_) self.assertListEqual(list(inputs.keys()) , processor.model_input_names)
359
"""simple docstring""" import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch __lowercase = True except ImportError: __lowercase = False try: from torch.hub import _get_torch_home __lowercase = _get_torch_home() except ImportError: __lowercase = os.path.expanduser( os.getenv("""TORCH_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """torch""")) ) __lowercase = os.path.join(torch_cache_home, """transformers""") __lowercase = """https://cdn.huggingface.co""" __lowercase = """https://s3.amazonaws.com/models.huggingface.co/bert""" __lowercase = """/""".join(str(Path(__file__).resolve()).split("""/""")[:-1]) __lowercase = os.path.join(PATH, """config.yaml""") __lowercase = os.path.join(PATH, """attributes.txt""") __lowercase = os.path.join(PATH, """objects.txt""") __lowercase = os.getenv("""PYTORCH_PRETRAINED_BERT_CACHE""", default_cache_path) __lowercase = os.getenv("""PYTORCH_TRANSFORMERS_CACHE""", PYTORCH_PRETRAINED_BERT_CACHE) __lowercase = os.getenv("""TRANSFORMERS_CACHE""", PYTORCH_TRANSFORMERS_CACHE) __lowercase = """pytorch_model.bin""" __lowercase = """config.yaml""" def lowercase ( A_=OBJECTS , A_=ATTRIBUTES )-> Union[str, Any]: '''simple docstring''' a : Optional[Any] = [] with open(A_ ) as f: for object in f.readlines(): vg_classes.append(object.split("," )[0].lower().strip() ) a : Union[str, Any] = [] with open(A_ ) as f: for object in f.readlines(): vg_attrs.append(object.split("," )[0].lower().strip() ) return vg_classes, vg_attrs def lowercase ( A_ )-> Optional[Any]: '''simple docstring''' a : Dict = OrderedDict() with open(A_ , "rb" ) as f: a : Optional[Any] = pkl.load(A_ )["model"] for k in copy.deepcopy(list(ckp.keys() ) ): a : Dict = ckp.pop(A_ ) if isinstance(A_ , np.ndarray ): a : Optional[Any] = torch.tensor(A_ ) else: assert isinstance(A_ , torch.tensor ), type(A_ ) a : int = v return r class _A : """simple docstring""" UpperCAmelCase : int = {} def __init__( self : Any , __UpperCAmelCase : dict , __UpperCAmelCase : str = "root" , __UpperCAmelCase : Optional[int]=0): a : List[str] = name a : Tuple = level a : int = {} for k, v in dictionary.items(): if v is None: raise ValueError() a : List[Any] = copy.deepcopy(__UpperCAmelCase) a : int = copy.deepcopy(__UpperCAmelCase) if isinstance(__UpperCAmelCase , __UpperCAmelCase): a : Union[str, Any] = Config(__UpperCAmelCase , name=__UpperCAmelCase , level=level + 1) a : Dict = v setattr(self , __UpperCAmelCase , __UpperCAmelCase) a : Tuple = d def __repr__( self : List[str]): return str(list((self._pointer.keys()))) def __setattr__( self : Dict , __UpperCAmelCase : str , __UpperCAmelCase : Tuple): a : Optional[Any] = val a : Tuple = val a : Dict = key.split(".") a : Union[str, Any] = len(__UpperCAmelCase) - 1 a : Optional[int] = self._pointer if len(__UpperCAmelCase) > 1: for i, l in enumerate(__UpperCAmelCase): if hasattr(self , __UpperCAmelCase) and isinstance(getattr(self , __UpperCAmelCase) , __UpperCAmelCase): setattr(getattr(self , __UpperCAmelCase) , ".".join(levels[i:]) , __UpperCAmelCase) if l == last_level: a : int = val else: a : str = pointer[l] def __snake_case ( self : str): return self._pointer def __snake_case ( self : int , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any]): with open(f'''{file_name}''' , "w") as stream: dump(__UpperCAmelCase , __UpperCAmelCase) def __snake_case ( self : int , __UpperCAmelCase : Dict , __UpperCAmelCase : int): with open(f'''{file_name}''' , "w") as stream: json.dump(__UpperCAmelCase , __UpperCAmelCase) @staticmethod def __snake_case ( __UpperCAmelCase : Dict): with open(__UpperCAmelCase) as stream: a : List[str] = load(__UpperCAmelCase , Loader=__UpperCAmelCase) return data def __str__( self : Tuple): a : str = " " if self._name != "root": a : List[str] = f'''{t * (self._level-1)}{self._name}:\n''' else: a : Optional[Any] = "" a : List[Any] = self._level for i, (k, v) in enumerate(self._pointer.items()): if isinstance(__UpperCAmelCase , __UpperCAmelCase): r += f'''{t * (self._level)}{v}\n''' self._level += 1 else: r += f'''{t * (self._level)}{k}: {v} ({type(__UpperCAmelCase).__name__})\n''' a : Tuple = level return r[:-1] @classmethod def __snake_case ( cls : str , __UpperCAmelCase : str , **__UpperCAmelCase : List[Any]): a , a : Tuple = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase) return cls(__UpperCAmelCase) @classmethod def __snake_case ( cls : Union[str, Any] , __UpperCAmelCase : str , **__UpperCAmelCase : List[str]): a : int = kwargs.pop("cache_dir" , __UpperCAmelCase) a : List[Any] = kwargs.pop("force_download" , __UpperCAmelCase) a : Optional[int] = kwargs.pop("resume_download" , __UpperCAmelCase) a : Tuple = kwargs.pop("proxies" , __UpperCAmelCase) a : int = kwargs.pop("local_files_only" , __UpperCAmelCase) if os.path.isdir(__UpperCAmelCase): a : Union[str, Any] = os.path.join(__UpperCAmelCase , __UpperCAmelCase) elif os.path.isfile(__UpperCAmelCase) or is_remote_url(__UpperCAmelCase): a : List[Any] = pretrained_model_name_or_path else: a : int = hf_bucket_url(__UpperCAmelCase , filename=__UpperCAmelCase , use_cdn=__UpperCAmelCase) try: # Load from URL or cache if already cached a : Optional[Any] = cached_path( __UpperCAmelCase , cache_dir=__UpperCAmelCase , force_download=__UpperCAmelCase , proxies=__UpperCAmelCase , resume_download=__UpperCAmelCase , local_files_only=__UpperCAmelCase , ) # Load config dict if resolved_config_file is None: raise EnvironmentError a : Union[str, Any] = Config.load_yaml(__UpperCAmelCase) except EnvironmentError: a : str = "Can't load config for" raise EnvironmentError(__UpperCAmelCase) if resolved_config_file == config_file: print("loading configuration file from path") else: print("loading configuration file cache") return Config.load_yaml(__UpperCAmelCase), kwargs def lowercase ( A_ )-> str: '''simple docstring''' a : Tuple = torch.load("dump.pt" , map_location=in_tensor.device ) a : Any = in_tensor.numpy() a : Optional[int] = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(A_ , A_ , rtol=0.0_1 , atol=0.1 ), ( F'''{sum([1 for x in np.isclose(A_ , A_ , rtol=0.0_1 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %''' " element-wise mismatch" ) raise Exception("tensors are all good" ) # Hugging face functions below def lowercase ( A_ )-> Optional[Any]: '''simple docstring''' a : Optional[Any] = urlparse(A_ ) return parsed.scheme in ("http", "https") def lowercase ( A_ , A_ , A_=True )-> str: '''simple docstring''' a : List[Any] = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX a : str = "/" not in model_id if legacy_format: return F'''{endpoint}/{model_id}-{filename}''' else: return F'''{endpoint}/{model_id}/{filename}''' def lowercase ( A_ , A_ , A_=None , A_=0 , A_=None , )-> List[str]: '''simple docstring''' a : Optional[int] = "python/{}".format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(A_ , A_ ): ua += "; " + "; ".join("{}/{}".format(A_ , A_ ) for k, v in user_agent.items() ) elif isinstance(A_ , A_ ): ua += "; " + user_agent a : str = {"user-agent": ua} if resume_size > 0: a : List[Any] = "bytes=%d-" % (resume_size,) a : str = requests.get(A_ , stream=A_ , proxies=A_ , headers=A_ ) if response.status_code == 416: # Range not satisfiable return a : Optional[int] = response.headers.get("Content-Length" ) a : List[Any] = resume_size + int(A_ ) if content_length is not None else None a : List[Any] = tqdm( unit="B" , unit_scale=A_ , total=A_ , initial=A_ , desc="Downloading" , ) for chunk in response.iter_content(chunk_size=1_024 ): if chunk: # filter out keep-alive new chunks progress.update(len(A_ ) ) temp_file.write(A_ ) progress.close() def lowercase ( A_ , A_=None , A_=False , A_=None , A_=10 , A_=False , A_=None , A_=False , )-> str: '''simple docstring''' if cache_dir is None: a : List[Any] = TRANSFORMERS_CACHE if isinstance(A_ , A_ ): a : Tuple = str(A_ ) os.makedirs(A_ , exist_ok=A_ ) a : Optional[Any] = None if not local_files_only: try: a : Dict = requests.head(A_ , allow_redirects=A_ , proxies=A_ , timeout=A_ ) if response.status_code == 200: a : int = response.headers.get("ETag" ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass a : List[str] = url_to_filename(A_ , A_ ) # get cache path to put the file a : List[str] = os.path.join(A_ , A_ ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(A_ ): return cache_path else: a : Any = [ file for file in fnmatch.filter(os.listdir(A_ ) , filename + ".*" ) if not file.endswith(".json" ) and not file.endswith(".lock" ) ] if len(A_ ) > 0: return os.path.join(A_ , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( "Cannot find the requested files in the cached path and outgoing traffic has been" " disabled. To enable model look-ups and downloads online, set 'local_files_only'" " to False." ) return None # From now on, etag is not None. if os.path.exists(A_ ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. a : Dict = cache_path + ".lock" with FileLock(A_ ): # If the download just completed while the lock was activated. if os.path.exists(A_ ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: a : Optional[Any] = cache_path + ".incomplete" @contextmanager def _resumable_file_manager(): with open(A_ , "a+b" ) as f: yield f a : Tuple = _resumable_file_manager if os.path.exists(A_ ): a : Optional[Any] = os.stat(A_ ).st_size else: a : Optional[int] = 0 else: a : Union[str, Any] = partial(tempfile.NamedTemporaryFile , dir=A_ , delete=A_ ) a : Dict = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( "%s not found in cache or force_download set to True, downloading to %s" , A_ , temp_file.name , ) http_get( A_ , A_ , proxies=A_ , resume_size=A_ , user_agent=A_ , ) os.replace(temp_file.name , A_ ) a : List[str] = {"url": url, "etag": etag} a : Tuple = cache_path + ".json" with open(A_ , "w" ) as meta_file: json.dump(A_ , A_ ) return cache_path def lowercase ( A_ , A_=None )-> Any: '''simple docstring''' a : Dict = url.encode("utf-8" ) a : Optional[Any] = shaaaa(A_ ) a : Any = url_hash.hexdigest() if etag: a : Union[str, Any] = etag.encode("utf-8" ) a : Tuple = shaaaa(A_ ) filename += "." + etag_hash.hexdigest() if url.endswith(".h5" ): filename += ".h5" return filename def lowercase ( A_ , A_=None , A_=False , A_=None , A_=False , A_=None , A_=False , A_=False , A_=False , )-> Tuple: '''simple docstring''' if cache_dir is None: a : Union[str, Any] = TRANSFORMERS_CACHE if isinstance(A_ , A_ ): a : List[Any] = str(A_ ) if isinstance(A_ , A_ ): a : int = str(A_ ) if is_remote_url(A_ ): # URL, so get it from the cache (downloading if necessary) a : Optional[Any] = get_from_cache( A_ , cache_dir=A_ , force_download=A_ , proxies=A_ , resume_download=A_ , user_agent=A_ , local_files_only=A_ , ) elif os.path.exists(A_ ): # File, and it exists. a : Union[str, Any] = url_or_filename elif urlparse(A_ ).scheme == "": # File, but it doesn't exist. raise EnvironmentError("file {} not found".format(A_ ) ) else: # Something unknown raise ValueError("unable to parse {} as a URL or as a local path".format(A_ ) ) if extract_compressed_file: if not is_zipfile(A_ ) and not tarfile.is_tarfile(A_ ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" a , a : Dict = os.path.split(A_ ) a : List[str] = output_file.replace("." , "-" ) + "-extracted" a : Optional[Any] = os.path.join(A_ , A_ ) if os.path.isdir(A_ ) and os.listdir(A_ ) and not force_extract: return output_path_extracted # Prevent parallel extractions a : Tuple = output_path + ".lock" with FileLock(A_ ): shutil.rmtree(A_ , ignore_errors=A_ ) os.makedirs(A_ ) if is_zipfile(A_ ): with ZipFile(A_ , "r" ) as zip_file: zip_file.extractall(A_ ) zip_file.close() elif tarfile.is_tarfile(A_ ): a : List[str] = tarfile.open(A_ ) tar_file.extractall(A_ ) tar_file.close() else: raise EnvironmentError("Archive format of {} could not be identified".format(A_ ) ) return output_path_extracted return output_path def lowercase ( A_ , A_="," )-> Union[str, Any]: '''simple docstring''' assert isinstance(A_ , A_ ) if os.path.isfile(A_ ): with open(A_ ) as f: a : str = eval(f.read() ) else: a : List[Any] = requests.get(A_ ) try: a : Any = requests.json() except Exception: a : Any = req.content.decode() assert data is not None, "could not connect" try: a : Optional[Any] = eval(A_ ) except Exception: a : Any = data.split("\n" ) req.close() return data def lowercase ( A_ )-> str: '''simple docstring''' a : Optional[int] = requests.get(A_ ) a : List[str] = np.array(Image.open(BytesIO(response.content ) ) ) return img def lowercase ( A_ )-> Any: '''simple docstring''' a : List[Any] = url.split("/" )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(A_ ) with open(A_ , "rb" ) as stream: a : Any = pkl.load(A_ ) a : List[str] = weights.pop("model" ) a : Dict = {} for k, v in model.items(): a : List[str] = torch.from_numpy(A_ ) if "running_var" in k: a : Dict = torch.tensor([0] ) a : Any = k.replace("running_var" , "num_batches_tracked" ) a : List[Any] = zero return new def lowercase ( )-> Optional[int]: '''simple docstring''' print(F'''{os.path.abspath(os.path.join(A_ , os.pardir ) )}/demo.ipynb''' ) def lowercase ( A_ , A_="RGB" )-> Any: '''simple docstring''' assert isinstance(A_ , A_ ) if os.path.isfile(A_ ): a : Dict = cva.imread(A_ ) else: a : Union[str, Any] = get_image_from_url(A_ ) assert img is not None, F'''could not connect to: {im}''' a : int = cva.cvtColor(A_ , cva.COLOR_BGR2RGB ) if input_format == "RGB": a : List[str] = img[:, :, ::-1] return img def lowercase ( A_ , A_=1 )-> int: '''simple docstring''' return (images[i : i + batch] for i in range(0 , len(A_ ) , A_ ))
226
0
'''simple docstring''' import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 _SCREAMING_SNAKE_CASE : Optional[Any] = { "return_dict": False, "output_hidden_states": True, "output_attentions": True, "torchscript": True, "torch_dtype": "float16", "use_bfloat16": True, "tf_legacy_loss": True, "pruned_heads": {"a": 1}, "tie_word_embeddings": False, "is_decoder": True, "cross_attention_hidden_size": 128, "add_cross_attention": True, "tie_encoder_decoder": True, "max_length": 50, "min_length": 3, "do_sample": True, "early_stopping": True, "num_beams": 3, "num_beam_groups": 3, "diversity_penalty": 0.5, "temperature": 2.0, "top_k": 10, "top_p": 0.7, "typical_p": 0.2, "repetition_penalty": 0.8, "length_penalty": 0.8, "no_repeat_ngram_size": 5, "encoder_no_repeat_ngram_size": 5, "bad_words_ids": [1, 2, 3], "num_return_sequences": 3, "chunk_size_feed_forward": 5, "output_scores": True, "return_dict_in_generate": True, "forced_bos_token_id": 2, "forced_eos_token_id": 3, "remove_invalid_values": True, "architectures": ["BertModel"], "finetuning_task": "translation", "id2label": {0: "label"}, "label2id": {"label": "0"}, "tokenizer_class": "BertTokenizerFast", "prefix": "prefix", "bos_token_id": 6, "pad_token_id": 7, "eos_token_id": 8, "sep_token_id": 9, "decoder_start_token_id": 10, "exponential_decay_length_penalty": (5, 1.0_1), "suppress_tokens": [0, 1], "begin_suppress_tokens": 2, "task_specific_params": {"translation": "some_params"}, "problem_type": "regression", } @is_staging_test class _snake_case ( unittest.TestCase ): @classmethod def lowerCAmelCase__ ( cls ) -> Union[str, Any]: '''simple docstring''' snake_case_ = TOKEN HfFolder.save_token(a__ ) @classmethod def lowerCAmelCase__ ( cls ) -> str: '''simple docstring''' try: delete_repo(token=cls._token , repo_id="test-config" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-config-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-config" ) except HTTPError: pass def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("test-config" , use_auth_token=self._token ) snake_case_ = BertConfig.from_pretrained(F'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(a__ , getattr(a__ , a__ ) ) # Reset repo delete_repo(token=self._token , repo_id="test-config" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(a__ , repo_id="test-config" , push_to_hub=a__ , use_auth_token=self._token ) snake_case_ = BertConfig.from_pretrained(F'{USER}/test-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(a__ , getattr(a__ , a__ ) ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token ) snake_case_ = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(a__ , getattr(a__ , a__ ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-config-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( a__ , repo_id="valid_org/test-config-org" , push_to_hub=a__ , use_auth_token=self._token ) snake_case_ = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(a__ , getattr(a__ , a__ ) ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' CustomConfig.register_for_auto_class() snake_case_ = CustomConfig(attribute=42 ) config.push_to_hub("test-dynamic-config" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} ) snake_case_ = AutoConfig.from_pretrained(F'{USER}/test-dynamic-config' , trust_remote_code=a__ ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , "CustomConfig" ) self.assertEqual(new_config.attribute , 42 ) class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated snake_case_ = c.n_embd + 1 # int snake_case_ = c.resid_pdrop + 1.0 # float snake_case_ = not c.scale_attn_weights # bool snake_case_ = c.summary_type + "foo" # str c.update_from_string( F'n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}' ) self.assertEqual(a__ , c.n_embd , "mismatch for key: n_embd" ) self.assertEqual(a__ , c.resid_pdrop , "mismatch for key: resid_pdrop" ) self.assertEqual(a__ , c.scale_attn_weights , "mismatch for key: scale_attn_weights" ) self.assertEqual(a__ , c.summary_type , "mismatch for key: summary_type" ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = PretrainedConfig() snake_case_ = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( a__ , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] ) snake_case_ = [key for key, value in config_common_kwargs.items() if value == getattr(a__ , a__ )] if len(a__ ) > 0: raise ValueError( "The following keys are set with the default values in" " `test_configuration_common.config_common_kwargs` pick another value for them:" F' {", ".join(a__ )}.' ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' with self.assertRaises(a__ ): # config is in subfolder, the following should not work without specifying the subfolder snake_case_ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" ) snake_case_ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" ) self.assertIsNotNone(a__ ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = mock.Mock() snake_case_ = 500 snake_case_ = {} snake_case_ = HTTPError snake_case_ = {} # Download this model to make sure it's in the cache. snake_case_ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=a__ ) as mock_head: snake_case_ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = BertConfig.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = AutoConfig.from_pretrained("bert-base-cased" ) snake_case_ = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(a__ ) snake_case_ = 2 json.dump(configuration.to_dict() , open(os.path.join(a__ , "config.4.0.0.json" ) , "w" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 snake_case_ = AutoConfig.from_pretrained(a__ ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 snake_case_ = ["config.42.0.0.json"] snake_case_ = 768 configuration.save_pretrained(a__ ) shutil.move(os.path.join(a__ , "config.4.0.0.json" ) , os.path.join(a__ , "config.42.0.0.json" ) ) snake_case_ = AutoConfig.from_pretrained(a__ ) self.assertEqual(new_configuration.hidden_size , 768 ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = "hf-internal-testing/test-two-configs" import transformers as new_transformers snake_case_ = "v4.0.0" snake_case_ , snake_case_ = new_transformers.models.auto.AutoConfig.from_pretrained( a__ , return_unused_kwargs=a__ ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(a__ , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers snake_case_ = "v3.0.0" snake_case_ = old_transformers.models.auto.AutoConfig.from_pretrained(a__ ) self.assertEqual(old_configuration.hidden_size , 768 )
85
from __future__ import annotations import os from collections.abc import Mapping _UpperCAmelCase : Tuple = tuple[int, int] class lowercase : def __init__( self , A_ , A_ ) -> None: """simple docstring""" UpperCamelCase = vertices UpperCamelCase = { (min(A_ ), max(A_ )): weight for edge, weight in edges.items() } def __UpperCamelCase ( self , A_ , A_ ) -> None: """simple docstring""" self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) UpperCamelCase = weight def __UpperCamelCase ( self ) -> Graph: """simple docstring""" UpperCamelCase = Graph({min(self.vertices )} , {} ) UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 while len(subgraph.vertices ) < len(self.vertices ): UpperCamelCase = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: UpperCamelCase = edge UpperCamelCase = weight subgraph.add_edge(A_ , A_ ) return subgraph def A ( lowercase = "p107_network.txt" ) -> int: '''simple docstring''' UpperCamelCase = os.path.abspath(os.path.dirname(lowercase ) ) UpperCamelCase = os.path.join(lowercase , lowercase ) UpperCamelCase = {} UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 with open(lowercase ) as f: UpperCamelCase = f.read().strip().split('\n' ) UpperCamelCase = [line.split(',' ) for line in data] for edgea in range(1 , len(lowercase ) ): for edgea in range(lowercase ): if adjaceny_matrix[edgea][edgea] != "-": UpperCamelCase = int(adjaceny_matrix[edgea][edgea] ) UpperCamelCase = Graph(set(range(len(lowercase ) ) ) , lowercase ) UpperCamelCase = graph.prims_algorithm() UpperCamelCase = sum(graph.edges.values() ) UpperCamelCase = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F'''{solution() = }''')
222
0
import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): """simple docstring""" A_ = BioGptTokenizer A_ = False def __A ( self: Optional[Any] ) -> int: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _A = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] _A = dict(zip(__A , range(len(__A ) ) ) ) _A = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] _A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(__A ) ) def __A ( self: List[str] , __A: Optional[Any] ) -> Optional[Any]: _A = '''lower newer''' _A = '''lower newer''' return input_text, output_text def __A ( self: int ) -> List[str]: _A = BioGptTokenizer(self.vocab_file , self.merges_file ) _A = '''lower''' _A = ['''low''', '''er</w>'''] _A = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) _A = tokens + ['''<unk>'''] _A = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) @slow def __A ( self: List[Any] ) -> Optional[int]: _A = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) _A = tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) _A = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) _A = tokenizer.build_inputs_with_special_tokens(__A ) _A = tokenizer.build_inputs_with_special_tokens(__A , __A ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
75
import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): __A = yaml.safe_load( '\\nname: ""\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: "Dataset Card for X" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: "Table of Contents"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Dataset Description"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: "Dataset Summary"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Supported Tasks and Leaderboards"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n' ) __A = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } __A = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __A = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __A = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Extra Ignored Subsection', 'text': '', 'is_empty_text': True, 'subsections': [], } ], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } __A = '\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __A = ( 'The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.' ) __A = '\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __A = ( 'The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.' ) __A = '\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __A = 'The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.' __A = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __A = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).' __A = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n' __A = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.' __A = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n' __A = 'The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.' __A = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n' __A = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.' __A = '\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __A = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.' __A = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n' __A = 'The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.' __A = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __A = 'The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.' __A = '' __A = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.' __A = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __A = 'The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.' @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def __A ( _lowercase , _lowercase ): '''simple docstring''' assert ReadMe.from_string(_lowercase , _lowercase ).to_dict() == expected_dict @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def __A ( _lowercase , _lowercase ): '''simple docstring''' with pytest.raises(_lowercase , match=re.escape(expected_error.format(path='''root''' ) ) ): _A = ReadMe.from_string(_lowercase , _lowercase ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def __A ( _lowercase , _lowercase ): '''simple docstring''' with pytest.raises(_lowercase , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(_lowercase , _lowercase ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def __A ( _lowercase ): '''simple docstring''' ReadMe.from_string(_lowercase , _lowercase , suppress_parsing_errors=_lowercase ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def __A ( _lowercase , _lowercase ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _A = Path(_lowercase ) / '''README.md''' with open(_lowercase , '''w+''' ) as readme_file: readme_file.write(_lowercase ) _A = ReadMe.from_readme(_lowercase , _lowercase ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def __A ( _lowercase , _lowercase ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _A = Path(_lowercase ) / '''README.md''' with open(_lowercase , '''w+''' ) as readme_file: readme_file.write(_lowercase ) _A = expected_error.format(path=_lowercase ) with pytest.raises(_lowercase , match=re.escape(_lowercase ) ): _A = ReadMe.from_readme(_lowercase , _lowercase ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def __A ( _lowercase , _lowercase ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _A = Path(_lowercase ) / '''README.md''' with open(_lowercase , '''w+''' ) as readme_file: readme_file.write(_lowercase ) _A = expected_error.format(path=_lowercase ) with pytest.raises(_lowercase , match=re.escape(_lowercase ) ): ReadMe.from_readme(_lowercase , _lowercase ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def __A ( _lowercase ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _A = Path(_lowercase ) / '''README.md''' with open(_lowercase , '''w+''' ) as readme_file: readme_file.write(_lowercase ) ReadMe.from_readme(_lowercase , _lowercase , suppress_parsing_errors=_lowercase )
75
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def snake_case ( snake_case__ :Optional[int]=None) -> Optional[int]: if subparsers is not None: _A = subparsers.add_parser("""test""") else: _A = argparse.ArgumentParser("""Accelerate test command""") parser.add_argument( """--config_file""" , default=_A , help=( """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """ """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """ """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """ """with 'huggingface'.""" ) , ) if subparsers is not None: parser.set_defaults(func=_A) return parser def snake_case ( snake_case__ :List[Any]) -> Any: _A = os.path.sep.join(__file__.split(os.path.sep)[:-2] + ["""test_utils""", """scripts""", """test_script.py"""]) if args.config_file is None: _A = script_name else: _A = F'''--config_file={args.config_file} {script_name}''' _A = ["""accelerate-launch"""] + test_args.split() _A = execute_subprocess_async(_A , env=os.environ.copy()) if result.returncode == 0: print("""Test is a success! You are ready for your distributed training!""") def snake_case ( ) -> Any: _A = test_command_parser() _A = parser.parse_args() test_command(_A) if __name__ == "__main__": main()
180
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __A : Optional[Any] = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[str] = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys __A : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
154
0
"""simple docstring""" import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _snake_case ( lowerCamelCase__ : List[str] ) -> str: if is_torch_version("<" , "2.0.0" ) or not hasattr(lowerCamelCase__ , "_dynamo" ): return False return isinstance(lowerCamelCase__ , torch._dynamo.eval_frame.OptimizedModule ) def _snake_case ( lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : bool = True ) -> Optional[int]: lowerCamelCase_ : Optional[Any] =(torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) lowerCamelCase_ : Any =is_compiled_module(lowerCamelCase__ ) if is_compiled: lowerCamelCase_ : Optional[Any] =model lowerCamelCase_ : Union[str, Any] =model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ : Any =model.module if not keep_fpaa_wrapper: lowerCamelCase_ : List[Any] =getattr(lowerCamelCase__ , "forward" ) lowerCamelCase_ : Dict =model.__dict__.pop("_original_forward" , lowerCamelCase__ ) if original_forward is not None: while hasattr(lowerCamelCase__ , "__wrapped__" ): lowerCamelCase_ : List[Any] =forward.__wrapped__ if forward == original_forward: break lowerCamelCase_ : Dict =forward if getattr(lowerCamelCase__ , "_converted_to_transformer_engine" , lowerCamelCase__ ): convert_model(lowerCamelCase__ , to_transformer_engine=lowerCamelCase__ ) if is_compiled: lowerCamelCase_ : Dict =model lowerCamelCase_ : Dict =compiled_model return model def _snake_case ( ) -> Optional[int]: PartialState().wait_for_everyone() def _snake_case ( lowerCamelCase__ : int , lowerCamelCase__ : List[str] ) -> Union[str, Any]: if PartialState().distributed_type == DistributedType.TPU: xm.save(lowerCamelCase__ , lowerCamelCase__ ) elif PartialState().local_process_index == 0: torch.save(lowerCamelCase__ , lowerCamelCase__ ) @contextmanager def _snake_case ( **lowerCamelCase__ : Any ) -> str: for key, value in kwargs.items(): lowerCamelCase_ : Optional[int] =str(lowerCamelCase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _snake_case ( lowerCamelCase__ : Union[str, Any] ) -> Dict: if not hasattr(lowerCamelCase__ , "__qualname__" ) and not hasattr(lowerCamelCase__ , "__name__" ): lowerCamelCase_ : Union[str, Any] =getattr(lowerCamelCase__ , "__class__" , lowerCamelCase__ ) if hasattr(lowerCamelCase__ , "__qualname__" ): return obj.__qualname__ if hasattr(lowerCamelCase__ , "__name__" ): return obj.__name__ return str(lowerCamelCase__ ) def _snake_case ( lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[Any] ) -> Tuple: for key, value in source.items(): if isinstance(lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ : Optional[int] =destination.setdefault(lowerCamelCase__ , {} ) merge_dicts(lowerCamelCase__ , lowerCamelCase__ ) else: lowerCamelCase_ : Dict =value return destination def _snake_case ( lowerCamelCase__ : int = None ) -> bool: if port is None: lowerCamelCase_ : Tuple =29_500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(("localhost", port) ) == 0
209
"""simple docstring""" import inspect import unittest from transformers import DecisionTransformerConfig, 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, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class lowercase__ : def __init__( self : List[Any] , snake_case__ : Optional[Any] , snake_case__ : Tuple=13 , snake_case__ : str=7 , snake_case__ : Union[str, Any]=6 , snake_case__ : str=17 , snake_case__ : Any=23 , snake_case__ : int=11 , snake_case__ : Tuple=True , ): lowerCamelCase_ : str =parent lowerCamelCase_ : Union[str, Any] =batch_size lowerCamelCase_ : List[Any] =seq_length lowerCamelCase_ : Union[str, Any] =act_dim lowerCamelCase_ : Optional[Any] =state_dim lowerCamelCase_ : Optional[Any] =hidden_size lowerCamelCase_ : Tuple =max_length lowerCamelCase_ : List[Any] =is_training def UpperCAmelCase__ ( self : Dict ): lowerCamelCase_ : Optional[Any] =floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) lowerCamelCase_ : Optional[Any] =floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) lowerCamelCase_ : List[Any] =floats_tensor((self.batch_size, self.seq_length, 1) ) lowerCamelCase_ : Optional[Any] =floats_tensor((self.batch_size, self.seq_length, 1) ) lowerCamelCase_ : List[Any] =ids_tensor((self.batch_size, self.seq_length) , vocab_size=1000 ) lowerCamelCase_ : Optional[int] =random_attention_mask((self.batch_size, self.seq_length) ) lowerCamelCase_ : List[str] =self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def UpperCAmelCase__ ( self : Any ): return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def UpperCAmelCase__ ( self : Optional[Any] , snake_case__ : Tuple , snake_case__ : Dict , snake_case__ : int , snake_case__ : Dict , snake_case__ : Optional[int] , snake_case__ : List[str] , snake_case__ : List[str] , ): lowerCamelCase_ : Tuple =DecisionTransformerModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() lowerCamelCase_ : str =model(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def UpperCAmelCase__ ( self : List[str] ): lowerCamelCase_ : List[str] =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ( lowerCamelCase_ ) , ) : Optional[int] =config_and_inputs lowerCamelCase_ : Optional[int] ={ "states": states, "actions": actions, "rewards": rewards, "returns_to_go": returns_to_go, "timesteps": timesteps, "attention_mask": attention_mask, } return config, inputs_dict @require_torch class lowercase__ ( snake_case__, snake_case__, snake_case__, unittest.TestCase ): _UpperCAmelCase :Optional[Any] = (DecisionTransformerModel,) if is_torch_available() else () _UpperCAmelCase :int = () _UpperCAmelCase :int = {"feature-extraction": DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids _UpperCAmelCase :Union[str, Any] = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features _UpperCAmelCase :Optional[Any] = False _UpperCAmelCase :Tuple = False _UpperCAmelCase :Tuple = False _UpperCAmelCase :List[Any] = False _UpperCAmelCase :Dict = False _UpperCAmelCase :Any = False _UpperCAmelCase :List[Any] = False _UpperCAmelCase :int = False _UpperCAmelCase :str = False def UpperCAmelCase__ ( self : str ): lowerCamelCase_ : Dict =DecisionTransformerModelTester(self ) lowerCamelCase_ : str =ConfigTester(self , config_class=snake_case__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Union[str, Any] ): self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : int ): lowerCamelCase_ : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) @slow def UpperCAmelCase__ ( self : List[str] ): for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ : str =DecisionTransformerModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) def UpperCAmelCase__ ( self : str ): lowerCamelCase_ , lowerCamelCase_ : Dict =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase_ : List[Any] =model_class(snake_case__ ) lowerCamelCase_ : int =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase_ : List[Any] =[*signature.parameters.keys()] lowerCamelCase_ : List[str] =[ "states", "actions", "rewards", "returns_to_go", "timesteps", "attention_mask", ] self.assertListEqual(arg_names[: len(snake_case__ )] , snake_case__ ) @require_torch class lowercase__ ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self : Any ): lowerCamelCase_ : Optional[int] =2 # number of steps of autoregressive prediction we will perform lowerCamelCase_ : int =10 # defined by the RL environment, may be normalized lowerCamelCase_ : List[Any] =DecisionTransformerModel.from_pretrained("edbeeching/decision-transformer-gym-hopper-expert" ) lowerCamelCase_ : Union[str, Any] =model.to(snake_case__ ) lowerCamelCase_ : Any =model.config torch.manual_seed(0 ) lowerCamelCase_ : Optional[Any] =torch.randn(1 , 1 , config.state_dim ).to(device=snake_case__ , dtype=torch.floataa ) # env.reset() lowerCamelCase_ : Optional[Any] =torch.tensor( [[0.242_793, -0.28_693_074, 0.8_742_613], [0.67_815_274, -0.08_101_085, -0.12_952_147]] , device=snake_case__ ) lowerCamelCase_ : int =torch.tensor(snake_case__ , device=snake_case__ , dtype=torch.floataa ).reshape(1 , 1 , 1 ) lowerCamelCase_ : str =state lowerCamelCase_ : Optional[int] =torch.zeros(1 , 0 , config.act_dim , device=snake_case__ , dtype=torch.floataa ) lowerCamelCase_ : int =torch.zeros(1 , 0 , device=snake_case__ , dtype=torch.floataa ) lowerCamelCase_ : Tuple =torch.tensor(0 , device=snake_case__ , dtype=torch.long ).reshape(1 , 1 ) for step in range(snake_case__ ): lowerCamelCase_ : str =torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=snake_case__ )] , dim=1 ) lowerCamelCase_ : Union[str, Any] =torch.cat([rewards, torch.zeros(1 , 1 , device=snake_case__ )] , dim=1 ) lowerCamelCase_ : Optional[int] =torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ : Dict =model( states=snake_case__ , actions=snake_case__ , rewards=snake_case__ , returns_to_go=snake_case__ , timesteps=snake_case__ , attention_mask=snake_case__ , return_dict=snake_case__ , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1E-4 ) ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ : Optional[Any] =( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=snake_case__ , dtype=torch.floataa ), 1.0, False, {}, ) lowerCamelCase_ : str =action_pred[0, -1] lowerCamelCase_ : Optional[int] =torch.cat([states, state] , dim=1 ) lowerCamelCase_ : Optional[Any] =returns_to_go[0, -1] - reward lowerCamelCase_ : str =torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) lowerCamelCase_ : int =torch.cat( [timesteps, torch.ones((1, 1) , device=snake_case__ , dtype=torch.long ) * (step + 1)] , dim=1 )
209
1
from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) -> list[float]: lowerCamelCase__ , lowerCamelCase__ : List[str] = coefficient_matrix.shape lowerCamelCase__ , lowerCamelCase__ : Tuple = constant_matrix.shape if rowsa != colsa: lowerCamelCase__ : List[Any] = F"""Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}""" raise ValueError(_UpperCAmelCase ) if colsa != 1: lowerCamelCase__ : Tuple = F"""Constant matrix must be nx1 but received {rowsa}x{colsa}""" raise ValueError(_UpperCAmelCase ) if rowsa != rowsa: lowerCamelCase__ : Optional[Any] = ( 'Coefficient and constant matrices dimensions must be nxn and nx1 but ' F"""received {rowsa}x{colsa} and {rowsa}x{colsa}""" ) raise ValueError(_UpperCAmelCase ) if len(_UpperCAmelCase ) != rowsa: lowerCamelCase__ : Tuple = ( 'Number of initial values must be equal to number of rows in coefficient ' F"""matrix but received {len(_UpperCAmelCase )} and {rowsa}""" ) raise ValueError(_UpperCAmelCase ) if iterations <= 0: raise ValueError('Iterations must be at least 1' ) lowerCamelCase__ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) lowerCamelCase__ , lowerCamelCase__ : List[str] = table.shape strictly_diagonally_dominant(_UpperCAmelCase ) # Iterates the whole matrix for given number of times for _ in range(_UpperCAmelCase ): lowerCamelCase__ : str = [] for row in range(_UpperCAmelCase ): lowerCamelCase__ : Dict = 0 for col in range(_UpperCAmelCase ): if col == row: lowerCamelCase__ : int = table[row][col] elif col == cols - 1: lowerCamelCase__ : Optional[int] = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] lowerCamelCase__ : Optional[Any] = (temp + val) / denom new_val.append(_UpperCAmelCase ) lowerCamelCase__ : List[str] = new_val return [float(_UpperCAmelCase ) for i in new_val] def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> bool: lowerCamelCase__ , lowerCamelCase__ : List[Any] = table.shape lowerCamelCase__ : Optional[int] = True for i in range(0 , _UpperCAmelCase ): lowerCamelCase__ : Optional[Any] = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('Coefficient matrix is not strictly diagonally dominant' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
50
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss _UpperCAmelCase : str = pytest.mark.integration @require_faiss class lowerCAmelCase ( __UpperCamelCase ): def A_ ( self : List[Any] ) -> Union[str, Any]: lowerCamelCase__ : List[Any] = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(UpperCAmelCase ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Optional[Any] ) -> Optional[int]: import faiss lowerCamelCase__ : Dataset = self._create_dummy_dataset() lowerCamelCase__ : List[Any] = dset.map( lambda UpperCAmelCase , UpperCAmelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=UpperCAmelCase , keep_in_memory=UpperCAmelCase ) lowerCamelCase__ : Tuple = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) lowerCamelCase__ , lowerCamelCase__ : str = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Union[str, Any] ) -> int: import faiss lowerCamelCase__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[str] ) -> Tuple: import faiss lowerCamelCase__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=UpperCAmelCase ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) lowerCamelCase__ , lowerCamelCase__ : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Any ) -> Optional[Any]: lowerCamelCase__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(UpperCAmelCase , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : Dict ) -> Dict: from elasticsearch import Elasticsearch lowerCamelCase__ : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: lowerCamelCase__ : List[Any] = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) lowerCamelCase__ : int = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} lowerCamelCase__ : List[str] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=UpperCAmelCase ) lowerCamelCase__ , lowerCamelCase__ : Dict = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class lowerCAmelCase ( __UpperCamelCase ): def A_ ( self : Any ) -> Dict: import faiss lowerCamelCase__ : Tuple = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query lowerCamelCase__ : int = np.zeros(5 , dtype=np.floataa ) lowerCamelCase__ : Any = 1 lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = index.search(UpperCAmelCase ) self.assertRaises(UpperCAmelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries lowerCamelCase__ : str = np.eye(5 , dtype=np.floataa )[::-1] lowerCamelCase__ , lowerCamelCase__ : Dict = index.search_batch(UpperCAmelCase ) self.assertRaises(UpperCAmelCase , index.search_batch , queries[0] ) lowerCamelCase__ : str = [scores[0] for scores in total_scores] lowerCamelCase__ : List[str] = [indices[0] for indices in total_indices] self.assertGreater(np.min(UpperCAmelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , UpperCAmelCase ) def A_ ( self : List[Any] ) -> List[Any]: import faiss lowerCamelCase__ : Any = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) lowerCamelCase__ : Tuple = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(UpperCAmelCase ): lowerCamelCase__ : List[str] = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : List[str] ) -> Optional[int]: import faiss lowerCamelCase__ : Optional[Any] = faiss.IndexFlat(5 ) lowerCamelCase__ : int = FaissIndex(custom_index=UpperCAmelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : Any ) -> Optional[int]: import faiss lowerCamelCase__ : Any = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=UpperCAmelCase ) as tmp_file: index.save(tmp_file.name ) lowerCamelCase__ : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) lowerCamelCase__ : List[str] = np.zeros(5 , dtype=np.floataa ) lowerCamelCase__ : Tuple = 1 lowerCamelCase__ , lowerCamelCase__ : str = index.search(UpperCAmelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> Any: import faiss lowerCamelCase__ : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) lowerCamelCase__ : Optional[int] = 'index.faiss' lowerCamelCase__ : Optional[Any] = F"""mock://{index_name}""" index.save(_UpperCAmelCase , storage_options=mockfs.storage_options ) lowerCamelCase__ : Tuple = FaissIndex.load(_UpperCAmelCase , storage_options=mockfs.storage_options ) lowerCamelCase__ : Optional[int] = np.zeros(5 , dtype=np.floataa ) lowerCamelCase__ : Dict = 1 lowerCamelCase__ , lowerCamelCase__ : str = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowerCAmelCase ( __UpperCamelCase ): def A_ ( self : Dict ) -> List[Any]: from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: lowerCamelCase__ : Any = Elasticsearch() lowerCamelCase__ : Tuple = {'acknowledged': True} lowerCamelCase__ : Tuple = ElasticSearchIndex(es_client=UpperCAmelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query lowerCamelCase__ : Optional[int] = 'foo' lowerCamelCase__ : str = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = index.search(UpperCAmelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout lowerCamelCase__ : Any = 'foo' lowerCamelCase__ : List[str] = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} lowerCamelCase__ , lowerCamelCase__ : Tuple = index.search(UpperCAmelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries lowerCamelCase__ : List[str] = ['foo', 'bar', 'foobar'] lowerCamelCase__ : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} lowerCamelCase__ , lowerCamelCase__ : str = index.search_batch(UpperCAmelCase ) lowerCamelCase__ : List[str] = [scores[0] for scores in total_scores] lowerCamelCase__ : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , UpperCAmelCase ) # batched queries with timeout lowerCamelCase__ : str = ['foo', 'bar', 'foobar'] lowerCamelCase__ : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = index.search_batch(UpperCAmelCase , request_timeout=30 ) lowerCamelCase__ : Optional[Any] = [scores[0] for scores in total_scores] lowerCamelCase__ : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , UpperCAmelCase )
50
1
"""simple docstring""" def A ( snake_case :int ) -> bool: return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print("Program to check whether a number is a Perfect number or not...") UpperCamelCase : Union[str, Any] = int(input("Enter number: ").strip()) print(f'''{number} is {"" if perfect(number) else "not "}a Perfect Number.''')
263
"""simple docstring""" def A ( snake_case :list[list[int]] , snake_case :int , snake_case :int , snake_case :list[int] ) -> bool: # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def A ( snake_case :list[list[int]] , snake_case :list[int] , snake_case :int ) -> bool: # Base Case if curr_ind == len(snake_case ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(snake_case ) ): if valid_connection(snake_case , snake_case , snake_case , snake_case ): # Insert current vertex into path as next transition __UpperCamelCase = next_ver # Validate created path if util_hamilton_cycle(snake_case , snake_case , curr_ind + 1 ): return True # Backtrack __UpperCamelCase = -1 return False def A ( snake_case :list[list[int]] , snake_case :int = 0 ) -> list[int]: __UpperCamelCase = [-1] * (len(snake_case ) + 1) # initialize start and end of path with starting index __UpperCamelCase = __UpperCamelCase = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(snake_case , snake_case , 1 ) else []
263
1
'''simple docstring''' class UpperCAmelCase__ : """simple docstring""" def __init__( self : Dict ): '''simple docstring''' _a : Dict = {} def __lowercase ( self : Union[str, Any] ): '''simple docstring''' print(self.vertex ) for i in self.vertex: print(_a ,' -> ' ,' -> '.join([str(_a ) for j in self.vertex[i]] ) ) def __lowercase ( self : Dict ,_a : int ,_a : int ): '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(_a ) else: # else make a new vertex _a : int = [to_vertex] def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : Tuple = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(_a ,_a ) def __lowercase ( self : Union[str, Any] ,_a : int ,_a : list ): '''simple docstring''' _a : List[Any] = True print(_a ,end=' ' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(_a ,_a ) if __name__ == "__main__": __lowerCAmelCase = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
271
'''simple docstring''' import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor __lowerCAmelCase = logging.get_logger(__name__) class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Tuple ,*_a : List[str] ,**_a : Any ): '''simple docstring''' warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' ,_a ,) super().__init__(*_a ,**_a )
271
1
'''simple docstring''' import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase ( SCREAMING_SNAKE_CASE__): _lowerCamelCase : List[str] = (UnCLIPScheduler,) def lowercase_ ( self : str, **a_ : Optional[int] ): """simple docstring""" UpperCamelCase__ = { "num_train_timesteps": 1000, "variance_type": "fixed_small_log", "clip_sample": True, "clip_sample_range": 1.0, "prediction_type": "epsilon", } config.update(**a_ ) return config def lowercase_ ( self : int ): """simple docstring""" for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=a_ ) def lowercase_ ( self : int ): """simple docstring""" for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=a_ ) def lowercase_ ( self : Optional[Any] ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=a_ ) def lowercase_ ( self : Optional[Any] ): """simple docstring""" for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=a_ ) def lowercase_ ( self : Union[str, Any] ): """simple docstring""" for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=a_ ) def lowercase_ ( self : Optional[Any] ): """simple docstring""" for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=a_, prev_timestep=a_ ) def lowercase_ ( self : Any ): """simple docstring""" UpperCamelCase__ = self.scheduler_classes[0] UpperCamelCase__ = self.get_scheduler_config(variance_type="fixed_small_log" ) UpperCamelCase__ = scheduler_class(**a_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0_0_0_0e-1_0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_549_625 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.9_994_987 ) ) < 1e-5 def lowercase_ ( self : Dict ): """simple docstring""" UpperCamelCase__ = self.scheduler_classes[0] UpperCamelCase__ = self.get_scheduler_config(variance_type="learned_range" ) UpperCamelCase__ = scheduler_class(**a_ ) UpperCamelCase__ = 0.5 assert scheduler._get_variance(1, predicted_variance=a_ ) - -10.1_712_790 < 1e-5 assert scheduler._get_variance(487, predicted_variance=a_ ) - -5.7_998_052 < 1e-5 assert scheduler._get_variance(999, predicted_variance=a_ ) - -0.0_010_011 < 1e-5 def lowercase_ ( self : str ): """simple docstring""" UpperCamelCase__ = self.scheduler_classes[0] UpperCamelCase__ = self.get_scheduler_config() UpperCamelCase__ = scheduler_class(**a_ ) UpperCamelCase__ = scheduler.timesteps UpperCamelCase__ = self.dummy_model() UpperCamelCase__ = self.dummy_sample_deter UpperCamelCase__ = torch.manual_seed(0 ) for i, t in enumerate(a_ ): # 1. predict noise residual UpperCamelCase__ = model(a_, a_ ) # 2. predict previous mean of sample x_t-1 UpperCamelCase__ = scheduler.step(a_, a_, a_, generator=a_ ).prev_sample UpperCamelCase__ = pred_prev_sample UpperCamelCase__ = torch.sum(torch.abs(a_ ) ) UpperCamelCase__ = torch.mean(torch.abs(a_ ) ) assert abs(result_sum.item() - 252.2_682_495 ) < 1e-2 assert abs(result_mean.item() - 0.3_284_743 ) < 1e-3 def lowercase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase__ = self.scheduler_classes[0] UpperCamelCase__ = self.get_scheduler_config() UpperCamelCase__ = scheduler_class(**a_ ) scheduler.set_timesteps(25 ) UpperCamelCase__ = scheduler.timesteps UpperCamelCase__ = self.dummy_model() UpperCamelCase__ = self.dummy_sample_deter UpperCamelCase__ = torch.manual_seed(0 ) for i, t in enumerate(a_ ): # 1. predict noise residual UpperCamelCase__ = model(a_, a_ ) if i + 1 == timesteps.shape[0]: UpperCamelCase__ = None else: UpperCamelCase__ = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 UpperCamelCase__ = scheduler.step( a_, a_, a_, prev_timestep=a_, generator=a_ ).prev_sample UpperCamelCase__ = pred_prev_sample UpperCamelCase__ = torch.sum(torch.abs(a_ ) ) UpperCamelCase__ = torch.mean(torch.abs(a_ ) ) assert abs(result_sum.item() - 258.2_044_983 ) < 1e-2 assert abs(result_mean.item() - 0.3_362_038 ) < 1e-3 def lowercase_ ( self : Optional[Any] ): """simple docstring""" pass def lowercase_ ( self : Tuple ): """simple docstring""" pass
31
'''simple docstring''' import argparse import json import subprocess def SCREAMING_SNAKE_CASE__( _UpperCamelCase : int , _UpperCamelCase : Tuple ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = [] UpperCamelCase__ = ( F'curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"' " https://api.github.com/repos/huggingface/transformers/actions/runners" ) UpperCamelCase__ = subprocess.run(_UpperCamelCase , shell=_UpperCamelCase , stdout=subprocess.PIPE ) UpperCamelCase__ = output.stdout.decode("utf-8" ) UpperCamelCase__ = json.loads(_UpperCamelCase ) UpperCamelCase__ = status["runners"] for runner in runners: if runner["name"] in target_runners: if runner["status"] == "offline": offline_runners.append(_UpperCamelCase ) # save the result so we can report them on Slack with open("offline_runners.txt" , "w" ) as fp: fp.write(json.dumps(_UpperCamelCase ) ) if len(_UpperCamelCase ) > 0: UpperCamelCase__ = "\n".join([x["name"] for x in offline_runners] ) raise ValueError(F'The following runners are offline:\n{failed}' ) if __name__ == "__main__": def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Dict ) -> Optional[Any]: '''simple docstring''' return values.split("," ) __lowercase: str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--target_runners", default=None, type=list_str, required=True, help="Comma-separated list of runners to check status.", ) parser.add_argument( "--token", default=None, type=str, required=True, help="A token that has actions:read permission." ) __lowercase: str = parser.parse_args() get_runner_status(args.target_runners, args.token)
31
1
"""simple docstring""" import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def UpperCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> Optional[int]: """simple docstring""" lowerCAmelCase_ : Tuple = [] embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight", f"stage{idx}.patch_embed.proj.weight", ) ) embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias", f"stage{idx}.patch_embed.proj.bias", ) ) embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight", f"stage{idx}.patch_embed.norm.weight", ) ) embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias", f"stage{idx}.patch_embed.norm.bias", ) ) return embed def UpperCamelCase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : Tuple ) -> Optional[Any]: """simple docstring""" lowerCAmelCase_ : Optional[int] = [] attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight", f"stage{idx}.blocks.{cnt}.attn.proj_q.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias", f"stage{idx}.blocks.{cnt}.attn.proj_q.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight", f"stage{idx}.blocks.{cnt}.attn.proj_k.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias", f"stage{idx}.blocks.{cnt}.attn.proj_k.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight", f"stage{idx}.blocks.{cnt}.attn.proj_v.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias", f"stage{idx}.blocks.{cnt}.attn.proj_v.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight", f"stage{idx}.blocks.{cnt}.attn.proj.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias", f"stage{idx}.blocks.{cnt}.attn.proj.bias", ) ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight", f"stage{idx}.blocks.{cnt}.mlp.fc1.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias", f"stage{idx}.blocks.{cnt}.mlp.fc1.bias") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight", f"stage{idx}.blocks.{cnt}.mlp.fc2.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias", f"stage{idx}.blocks.{cnt}.mlp.fc2.bias") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight", f"stage{idx}.blocks.{cnt}.norm1.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias", f"stage{idx}.blocks.{cnt}.norm1.bias") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight", f"stage{idx}.blocks.{cnt}.norm2.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias", f"stage{idx}.blocks.{cnt}.norm2.bias") ) return attention_weights def UpperCamelCase_ ( lowerCAmelCase__ : List[str] ) -> Tuple: """simple docstring""" lowerCAmelCase_ : List[str] = [] token.append((f"cvt.encoder.stages.{idx}.cls_token", 'stage2.cls_token') ) return token def UpperCamelCase_ ( ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase_ : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def UpperCamelCase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Union[str, Any] ) -> Any: """simple docstring""" lowerCAmelCase_ : Union[str, Any] = 'imagenet-1k-id2label.json' lowerCAmelCase_ : List[Any] = 1000 lowerCAmelCase_ : Optional[int] = 'huggingface/label-files' lowerCAmelCase_ : Optional[int] = num_labels lowerCAmelCase_ : str = json.load(open(cached_download(hf_hub_url(a__ , a__ , repo_type='dataset' ) ) , 'r' ) ) lowerCAmelCase_ : str = {int(a__ ): v for k, v in idalabel.items()} lowerCAmelCase_ : Union[str, Any] = idalabel lowerCAmelCase_ : Dict = {v: k for k, v in idalabel.items()} lowerCAmelCase_ : Any = CvtConfig(num_labels=a__ , idalabel=a__ , labelaid=a__ ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' , 1 )[-1][4:6] == "13": lowerCAmelCase_ : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' , 1 )[-1][4:6] == "21": lowerCAmelCase_ : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: lowerCAmelCase_ : Union[str, Any] = [2, 2, 20] lowerCAmelCase_ : Dict = [3, 12, 16] lowerCAmelCase_ : List[Any] = [192, 768, 1024] lowerCAmelCase_ : List[str] = CvtForImageClassification(a__ ) lowerCAmelCase_ : Optional[int] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) lowerCAmelCase_ : Optional[Any] = image_size lowerCAmelCase_ : List[str] = torch.load(a__ , map_location=torch.device('cpu' ) ) lowerCAmelCase_ : Optional[Any] = OrderedDict() lowerCAmelCase_ : Dict = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: lowerCAmelCase_ : int = list_of_state_dict + cls_token(a__ ) lowerCAmelCase_ : List[Any] = list_of_state_dict + embeddings(a__ ) for cnt in range(config.depth[idx] ): lowerCAmelCase_ : List[Any] = list_of_state_dict + attention(a__ , a__ ) lowerCAmelCase_ : Union[str, Any] = list_of_state_dict + final() for gg in list_of_state_dict: print(a__ ) for i in range(len(a__ ) ): lowerCAmelCase_ : int = original_weights[list_of_state_dict[i][1]] model.load_state_dict(a__ ) model.save_pretrained(a__ ) image_processor.save_pretrained(a__ ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": lowercase__ : Any = argparse.ArgumentParser() parser.add_argument( """--cvt_model""", default="""cvt-w24""", type=str, help="""Name of the cvt model you'd like to convert.""", ) parser.add_argument( """--image_size""", default=3_8_4, type=int, help="""Input Image Size""", ) parser.add_argument( """--cvt_file_name""", default=R"""cvtmodels\CvT-w24-384x384-IN-22k.pth""", type=str, help="""Input Image Size""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowercase__ : str = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
224
"""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 = logging.get_logger(__name__) UpperCAmelCase = {"""vocab_file""": """spiece.model"""} UpperCAmelCase = { """vocab_file""": { """bert_for_seq_generation""": ( """https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model""" ), } } UpperCAmelCase = {"""bert_for_seq_generation""": 512} class UpperCAmelCase_ ( _lowercase): snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = [] snake_case__ = ['''input_ids''', '''attention_mask'''] def __init__( self : Any , __UpperCamelCase : int , __UpperCamelCase : Optional[int]="<s>" , __UpperCamelCase : Optional[Any]="</s>" , __UpperCamelCase : Optional[Any]="<unk>" , __UpperCamelCase : Tuple="<pad>" , __UpperCamelCase : int="<::::>" , __UpperCamelCase : Optional[Dict[str, Any]] = None , **__UpperCamelCase : Any , ) -> None: _UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=__UpperCamelCase , eos_token=__UpperCamelCase , unk_token=__UpperCamelCase , pad_token=__UpperCamelCase , sep_token=__UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCamelCase , ) _UpperCamelCase = vocab_file _UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCamelCase ) @property def _UpperCamelCase ( self : Optional[int] ) -> Tuple: return self.sp_model.get_piece_size() def _UpperCamelCase ( self : int ) -> Optional[int]: _UpperCamelCase = {self.convert_ids_to_tokens(__UpperCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : List[Any] ) -> Union[str, Any]: _UpperCamelCase = self.__dict__.copy() _UpperCamelCase = None return state def __setstate__( self : str , __UpperCamelCase : Any ) -> Tuple: _UpperCamelCase = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _UpperCamelCase = {} _UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _UpperCamelCase ( self : Union[str, Any] , __UpperCamelCase : str ) -> List[str]: return self.sp_model.encode(__UpperCamelCase , out_type=__UpperCamelCase ) def _UpperCamelCase ( self : Tuple , __UpperCamelCase : Any ) -> Optional[int]: return self.sp_model.piece_to_id(__UpperCamelCase ) def _UpperCamelCase ( self : Optional[Any] , __UpperCamelCase : Optional[int] ) -> Optional[Any]: _UpperCamelCase = self.sp_model.IdToPiece(__UpperCamelCase ) return token def _UpperCamelCase ( self : str , __UpperCamelCase : Dict ) -> Optional[Any]: _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(__UpperCamelCase ) + token _UpperCamelCase = [] else: current_sub_tokens.append(__UpperCamelCase ) out_string += self.sp_model.decode(__UpperCamelCase ) return out_string.strip() def _UpperCamelCase ( self : Tuple , __UpperCamelCase : str , __UpperCamelCase : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__UpperCamelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return _UpperCamelCase = os.path.join( __UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __UpperCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCamelCase , '''wb''' ) as fi: _UpperCamelCase = self.sp_model.serialized_model_proto() fi.write(__UpperCamelCase ) return (out_vocab_file,)
256
0
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _lowercase ( _lowercase , unittest.TestCase ): a = KandinskyVaaPriorPipeline a = ["""prompt"""] a = ["""prompt""", """negative_prompt"""] a = [ """num_images_per_prompt""", """generator""", """num_inference_steps""", """latents""", """negative_prompt""", """guidance_scale""", """output_type""", """return_dict""", ] a = False @property def lowerCamelCase_ ( self: Union[str, Any] ): return 32 @property def lowerCamelCase_ ( self: Union[str, Any] ): return 32 @property def lowerCamelCase_ ( self: int ): return self.time_input_dim @property def lowerCamelCase_ ( self: Union[str, Any] ): return self.time_input_dim * 4 @property def lowerCamelCase_ ( self: Dict ): return 100 @property def lowerCamelCase_ ( self: List[str] ): lowerCamelCase__ : Optional[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def lowerCamelCase_ ( self: List[str] ): torch.manual_seed(0 ) lowerCamelCase__ : List[str] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(UpperCamelCase__ ) @property def lowerCamelCase_ ( self: Any ): torch.manual_seed(0 ) lowerCamelCase__ : List[str] = { """num_attention_heads""": 2, """attention_head_dim""": 12, """embedding_dim""": self.text_embedder_hidden_size, """num_layers""": 1, } lowerCamelCase__ : List[str] = PriorTransformer(**UpperCamelCase__ ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 lowerCamelCase__ : Optional[int] = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def lowerCamelCase_ ( self: Any ): torch.manual_seed(0 ) lowerCamelCase__ : Dict = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) lowerCamelCase__ : List[str] = CLIPVisionModelWithProjection(UpperCamelCase__ ) return model @property def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : Dict = CLIPImageProcessor( crop_size=224 , do_center_crop=UpperCamelCase__ , do_normalize=UpperCamelCase__ , do_resize=UpperCamelCase__ , image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073] , image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711] , resample=3 , size=224 , ) return image_processor def lowerCamelCase_ ( self: Any ): lowerCamelCase__ : Any = self.dummy_prior lowerCamelCase__ : Dict = self.dummy_image_encoder lowerCamelCase__ : int = self.dummy_text_encoder lowerCamelCase__ : Union[str, Any] = self.dummy_tokenizer lowerCamelCase__ : List[str] = self.dummy_image_processor lowerCamelCase__ : Dict = UnCLIPScheduler( variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1_000 , clip_sample=UpperCamelCase__ , clip_sample_range=10.0 , ) lowerCamelCase__ : List[str] = { """prior""": prior, """image_encoder""": image_encoder, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """scheduler""": scheduler, """image_processor""": image_processor, } return components def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: List[str] , UpperCamelCase__: List[str]=0 ): if str(UpperCamelCase__ ).startswith("""mps""" ): lowerCamelCase__ : str = torch.manual_seed(UpperCamelCase__ ) else: lowerCamelCase__ : Optional[Any] = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) lowerCamelCase__ : Dict = { """prompt""": """horse""", """generator""": generator, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCamelCase_ ( self: Optional[int] ): lowerCamelCase__ : str = """cpu""" lowerCamelCase__ : Dict = self.get_dummy_components() lowerCamelCase__ : Any = self.pipeline_class(**UpperCamelCase__ ) lowerCamelCase__ : Optional[int] = pipe.to(UpperCamelCase__ ) pipe.set_progress_bar_config(disable=UpperCamelCase__ ) lowerCamelCase__ : List[Any] = pipe(**self.get_dummy_inputs(UpperCamelCase__ ) ) lowerCamelCase__ : Tuple = output.image_embeds lowerCamelCase__ : Any = pipe( **self.get_dummy_inputs(UpperCamelCase__ ) , return_dict=UpperCamelCase__ , )[0] lowerCamelCase__ : Tuple = image[0, -10:] lowerCamelCase__ : List[Any] = image_from_tuple[0, -10:] assert image.shape == (1, 32) lowerCamelCase__ : List[str] = np.array( [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Dict = torch_device == """cpu""" lowerCamelCase__ : int = True lowerCamelCase__ : Optional[Any] = False self._test_inference_batch_single_identical( test_max_difference=UpperCamelCase__ , relax_max_difference=UpperCamelCase__ , test_mean_pixel_difference=UpperCamelCase__ , ) @skip_mps def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : Dict = torch_device == """cpu""" lowerCamelCase__ : int = False self._test_attention_slicing_forward_pass( test_max_difference=UpperCamelCase__ , test_mean_pixel_difference=UpperCamelCase__ , )
371
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _A : Union[str, Any] =logging.get_logger(__name__) _A : Optional[Any] ={'''vocab_file''': '''spiece.model'''} _A : Optional[Any] ={ '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _A : Union[str, Any] ={ '''t5-small''': 512, '''t5-base''': 512, '''t5-large''': 512, '''t5-3b''': 512, '''t5-11b''': 512, } _A : int ='''▁''' class _lowercase ( _lowercase ): a = VOCAB_FILES_NAMES a = PRETRAINED_VOCAB_FILES_MAP a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a = ["""input_ids""", """attention_mask"""] def __init__( self: int , UpperCamelCase__: int , UpperCamelCase__: List[str]="</s>" , UpperCamelCase__: Optional[Any]="<unk>" , UpperCamelCase__: Dict="<pad>" , UpperCamelCase__: List[Any]=100 , UpperCamelCase__: Dict=None , UpperCamelCase__: Optional[Dict[str, Any]] = None , UpperCamelCase__: Union[str, Any]=True , **UpperCamelCase__: Dict , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: lowerCamelCase__ : Union[str, Any] = [F'''<extra_id_{i}>''' for i in range(UpperCamelCase__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens lowerCamelCase__ : Optional[Any] = len(set(filter(lambda UpperCamelCase__ : bool("""extra_id""" in str(UpperCamelCase__ ) ) , UpperCamelCase__ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' """ provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids""" """ tokens""" ) if legacy: logger.warning_once( F'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565""" ) lowerCamelCase__ : Optional[int] = legacy lowerCamelCase__ : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , extra_ids=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , sp_model_kwargs=self.sp_model_kwargs , legacy=UpperCamelCase__ , **UpperCamelCase__ , ) lowerCamelCase__ : Tuple = vocab_file lowerCamelCase__ : Dict = extra_ids lowerCamelCase__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCamelCase__ ) @staticmethod def lowerCamelCase_ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: lowerCamelCase__ : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( """This tokenizer was incorrectly instantiated with a model max length of""" F''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' """ behavior is kept to avoid breaking backwards compatibility when padding/encoding with""" """ `truncation is True`.\n- Be aware that you SHOULD NOT rely on""" F''' {pretrained_model_name_or_path} automatically truncating your input to''' F''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' F''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' """ `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please""" """ instantiate this tokenizer with `model_max_length` set to your preferred value.""" , UpperCamelCase__ , ) return max_model_length @property def lowerCamelCase_ ( self: Any ): return self.sp_model.get_piece_size() + self._extra_ids def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : str = {self.convert_ids_to_tokens(UpperCamelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: List[int] , UpperCamelCase__: Optional[List[int]] = None , UpperCamelCase__: bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase__ , token_ids_a=UpperCamelCase__ , already_has_special_tokens=UpperCamelCase__ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(UpperCamelCase__ )) + [1] return ([0] * len(UpperCamelCase__ )) + [1] + ([0] * len(UpperCamelCase__ )) + [1] def lowerCamelCase_ ( self: Dict ): return list( set(filter(lambda UpperCamelCase__ : bool(re.search(R"""<extra_id_\d+>""" , UpperCamelCase__ ) ) is not None , self.additional_special_tokens ) ) ) def lowerCamelCase_ ( self: str ): return [self._convert_token_to_id(UpperCamelCase__ ) for token in self.get_sentinel_tokens()] def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: List[int] ): if len(UpperCamelCase__ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCamelCase_ ( self: str , UpperCamelCase__: List[int] , UpperCamelCase__: Optional[List[int]] = None ): lowerCamelCase__ : Optional[Any] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCamelCase_ ( self: int , UpperCamelCase__: List[int] , UpperCamelCase__: Optional[List[int]] = None ): lowerCamelCase__ : List[str] = self._add_eos_if_not_present(UpperCamelCase__ ) if token_ids_a is None: return token_ids_a else: lowerCamelCase__ : int = self._add_eos_if_not_present(UpperCamelCase__ ) return token_ids_a + token_ids_a def __getstate__( self: List[str] ): lowerCamelCase__ : Optional[int] = self.__dict__.copy() lowerCamelCase__ : Optional[Any] = None return state def __setstate__( self: List[Any] , UpperCamelCase__: Any ): lowerCamelCase__ : Tuple = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowerCamelCase__ : str = {} lowerCamelCase__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase__: "TextInput" , **UpperCamelCase__: List[str] ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: lowerCamelCase__ : List[Any] = SPIECE_UNDERLINE + text.replace(UpperCamelCase__ , """ """ ) return super().tokenize(UpperCamelCase__ , **UpperCamelCase__ ) def lowerCamelCase_ ( self: List[Any] , UpperCamelCase__: str , **UpperCamelCase__: str ): if not self.legacy: lowerCamelCase__ : List[Any] = text.startswith(UpperCamelCase__ ) if is_first: lowerCamelCase__ : Optional[int] = text[1:] lowerCamelCase__ : int = self.sp_model.encode(UpperCamelCase__ , out_type=UpperCamelCase__ ) if not self.legacy and not is_first and not text.startswith(""" """ ) and tokens[0].startswith(UpperCamelCase__ ): lowerCamelCase__ : str = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: Optional[Any] ): if token.startswith("""<extra_id_""" ): lowerCamelCase__ : List[Any] = re.match(R"""<extra_id_(\d+)>""" , UpperCamelCase__ ) lowerCamelCase__ : List[Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(UpperCamelCase__ ) def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: int ): if index < self.sp_model.get_piece_size(): lowerCamelCase__ : str = self.sp_model.IdToPiece(UpperCamelCase__ ) else: lowerCamelCase__ : Tuple = F'''<extra_id_{self.vocab_size - 1 - index}>''' return token def lowerCamelCase_ ( self: str , UpperCamelCase__: Tuple ): lowerCamelCase__ : str = [] lowerCamelCase__ : Any = """""" lowerCamelCase__ : Union[str, Any] = 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(UpperCamelCase__ ) + token lowerCamelCase__ : Dict = True lowerCamelCase__ : str = [] else: current_sub_tokens.append(UpperCamelCase__ ) lowerCamelCase__ : List[str] = False out_string += self.sp_model.decode(UpperCamelCase__ ) return out_string.strip() def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase__: str , UpperCamelCase__: Optional[str] = None ): if not os.path.isdir(UpperCamelCase__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase__ : List[Any] = os.path.join( UpperCamelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase__ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase__ , """wb""" ) as fi: lowerCamelCase__ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase__ ) return (out_vocab_file,)
129
0
"""simple docstring""" from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar lowercase_ = TypeVar('T') def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return (position - 1) // 2 def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return (2 * position) + 1 def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return (2 * position) + 2 class snake_case ( Generic[T] ): '''simple docstring''' def __init__( self : Optional[Any] ): '''simple docstring''' __A = [] __A = {} __A = 0 def __len__( self : Optional[int] ): '''simple docstring''' return self.elements def __repr__( self : Optional[Any] ): '''simple docstring''' return str(self.heap ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' # Check if the priority queue is empty return self.elements == 0 def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : T, _lowerCamelCase : int ): '''simple docstring''' # Add an element with given priority to the queue self.heap.append((elem, weight) ) __A = self.elements self.elements += 1 self._bubble_up(A_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0, self.elements - 1 ) __A , __A = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __A , __A = self.heap[0] self._bubble_down(A_ ) return elem def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : T, _lowerCamelCase : int ): '''simple docstring''' # Update the weight of the given key __A = self.position_map[elem] __A = (elem, weight) if position > 0: __A = get_parent_position(A_ ) __A , __A = self.heap[parent_position] if parent_weight > weight: self._bubble_up(A_ ) else: self._bubble_down(A_ ) else: self._bubble_down(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : T ): '''simple docstring''' # Place a node at the proper position (upward movement) [to be used internally # only] __A = self.position_map[elem] if curr_pos == 0: return None __A = get_parent_position(A_ ) __A , __A = self.heap[curr_pos] __A , __A = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(A_, A_ ) return self._bubble_up(A_ ) return None def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : T ): '''simple docstring''' # Place a node at the proper position (downward movement) [to be used # internally only] __A = self.position_map[elem] __A , __A = self.heap[curr_pos] __A = get_child_left_position(A_ ) __A = get_child_right_position(A_ ) if child_left_position < self.elements and child_right_position < self.elements: __A , __A = self.heap[child_left_position] __A , __A = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(A_, A_ ) return self._bubble_down(A_ ) if child_left_position < self.elements: __A , __A = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(A_, A_ ) return self._bubble_down(A_ ) else: return None if child_right_position < self.elements: __A , __A = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(A_, A_ ) return self._bubble_down(A_ ) return None def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' # Swap the nodes at the given positions __A = self.heap[nodea_pos][0] __A = self.heap[nodea_pos][0] __A , __A = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __A = nodea_pos __A = nodea_pos class snake_case ( Generic[T] ): '''simple docstring''' def __init__( self : Union[str, Any] ): '''simple docstring''' __A = {} __A = 0 def __repr__( self : Tuple ): '''simple docstring''' return str(self.connections ) def __len__( self : str ): '''simple docstring''' return self.nodes def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : T ): '''simple docstring''' # Add a node in the graph if it is not in the graph if node not in self.connections: __A = {} self.nodes += 1 def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : T, _lowerCamelCase : T, _lowerCamelCase : int ): '''simple docstring''' # Add an edge between 2 nodes in the graph self.add_node(A_ ) self.add_node(A_ ) __A = weight __A = weight def lowerCAmelCase ( __UpperCamelCase , ): """simple docstring""" __A = {node: maxsize for node in graph.connections} __A = {node: None for node in graph.connections} __A = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(snake_case__ , snake_case__ ) if priority_queue.is_empty(): return dist, parent # initialization __A = priority_queue.extract_min() __A = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __A = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(snake_case__ , dist[neighbour] ) __A = node # running prim's algorithm while not priority_queue.is_empty(): __A = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __A = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(snake_case__ , dist[neighbour] ) __A = node return dist, parent
266
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : int ,A_ : List[Any] ) -> Optional[Any]: for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] ,model_result['ss'] ): A = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(A_ ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: A = 'sgugger/tiny-distilbert-classification' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,only_pretrain_model=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,torchscript=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == 'cpu' ,'Cant do half precision' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,fpaa=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) # set architectures equal to `None` A = None A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == 'cpu' ,'Can\'t do half precision' ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = 'sshleifer/tiny-gpt2' A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,fpaa=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tiny-gpt2' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[str]: A = 'sshleifer/tinier_bart' A = AutoConfig.from_pretrained(A_ ) A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ,configs=[config] ) A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: A = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,save_to_csv=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,inference_time_csv_file=os.path.join(A_ ,'inf_time.csv' ) ,train_memory_csv_file=os.path.join(A_ ,'train_mem.csv' ) ,inference_memory_csv_file=os.path.join(A_ ,'inf_mem.csv' ) ,train_time_csv_file=os.path.join(A_ ,'train_time.csv' ) ,env_info_csv_file=os.path.join(A_ ,'env.csv' ) ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) benchmark.run() self.assertTrue(Path(os.path.join(A_ ,'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'train_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(A_ ,'env.csv' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: A = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(A_ : Optional[int] ): self.assertTrue(hasattr(A_ ,'sequential' ) ) self.assertTrue(hasattr(A_ ,'cumulative' ) ) self.assertTrue(hasattr(A_ ,'current' ) ) self.assertTrue(hasattr(A_ ,'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: A = PyTorchBenchmarkArguments( models=[MODEL_ID] ,training=A_ ,inference=A_ ,sequence_lengths=[8] ,batch_sizes=[1] ,log_filename=os.path.join(A_ ,'log.txt' ) ,log_print=A_ ,trace_memory_line_by_line=A_ ,multi_process=A_ ,) A = PyTorchBenchmark(A_ ) A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(A_ ,'log.txt' ) ).exists() )
74
0
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase : Union[str, Any] = { "configuration_mctct": ["MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MCTCTConfig"], "feature_extraction_mctct": ["MCTCTFeatureExtractor"], "processing_mctct": ["MCTCTProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Tuple = [ "MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST", "MCTCTForCTC", "MCTCTModel", "MCTCTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys lowercase : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
171
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_rembert import RemBertTokenizer else: lowercase : List[str] = None lowercase : Union[str, Any] = logging.get_logger(__name__) lowercase : int = {"vocab_file": "sentencepiece.model", "tokenizer_file": "tokenizer.json"} lowercase : Optional[Any] = { "vocab_file": { "google/rembert": "https://huggingface.co/google/rembert/resolve/main/sentencepiece.model", }, "tokenizer_file": { "google/rembert": "https://huggingface.co/google/rembert/resolve/main/tokenizer.json", }, } lowercase : List[str] = { "google/rembert": 256, } lowercase : Tuple = "▁" class SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ): """simple docstring""" lowercase : Optional[int] = VOCAB_FILES_NAMES lowercase : Dict = PRETRAINED_VOCAB_FILES_MAP lowercase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Optional[int] = RemBertTokenizer def __init__( self , __UpperCamelCase=None , __UpperCamelCase=None , __UpperCamelCase=True , __UpperCamelCase=True , __UpperCamelCase=False , __UpperCamelCase="[CLS]" , __UpperCamelCase="[SEP]" , __UpperCamelCase="<unk>" , __UpperCamelCase="[SEP]" , __UpperCamelCase="<pad>" , __UpperCamelCase="[CLS]" , __UpperCamelCase="[MASK]" , **__UpperCamelCase , ) -> Dict: '''simple docstring''' __UpperCamelCase : str = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else mask_token super().__init__( __UpperCamelCase , tokenizer_file=__UpperCamelCase , do_lower_case=__UpperCamelCase , remove_space=__UpperCamelCase , keep_accents=__UpperCamelCase , bos_token=__UpperCamelCase , eos_token=__UpperCamelCase , unk_token=__UpperCamelCase , sep_token=__UpperCamelCase , pad_token=__UpperCamelCase , cls_token=__UpperCamelCase , mask_token=__UpperCamelCase , **__UpperCamelCase , ) __UpperCamelCase : Any = do_lower_case __UpperCamelCase : List[str] = remove_space __UpperCamelCase : Optional[Any] = keep_accents __UpperCamelCase : Union[str, Any] = vocab_file __UpperCamelCase : Any = False if not self.vocab_file else True def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase = None ) -> List[int]: '''simple docstring''' __UpperCamelCase : Any = [self.sep_token_id] __UpperCamelCase : List[Any] = [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 __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = False ) -> List[int]: '''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(__UpperCamelCase )) + [1] + ([0] * len(__UpperCamelCase )) + [1] return [1] + ([0] * len(__UpperCamelCase )) + [1] def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase = None ) -> List[int]: '''simple docstring''' __UpperCamelCase : Tuple = [self.sep_token_id] __UpperCamelCase : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(__UpperCamelCase ): logger.error("Vocabulary path ({}) should be a directory".format(__UpperCamelCase ) ) return __UpperCamelCase : Optional[int] = os.path.join( __UpperCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCamelCase ): copyfile(self.vocab_file , __UpperCamelCase ) return (out_vocab_file,)
171
1
'''simple docstring''' from typing import Dict, Optional import numpy as np import datasets a_ = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n' a_ = '\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric("mean_iou")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n' a_ = '\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}' def _a( UpperCamelCase__ : Optional[Any], UpperCamelCase__ : str, UpperCamelCase__ : List[Any], UpperCamelCase__ : bool, UpperCamelCase__ : Optional[Dict[int, int]] = None, UpperCamelCase__ : bool = False, ): '''simple docstring''' if label_map is not None: for old_id, new_id in label_map.items(): SCREAMING_SNAKE_CASE__ : str =new_id # turn into Numpy arrays SCREAMING_SNAKE_CASE__ : str =np.array(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =np.array(UpperCamelCase__ ) if reduce_labels: SCREAMING_SNAKE_CASE__ : Union[str, Any] =2_5_5 SCREAMING_SNAKE_CASE__ : Tuple =label - 1 SCREAMING_SNAKE_CASE__ : List[Any] =2_5_5 SCREAMING_SNAKE_CASE__ : Union[str, Any] =label != ignore_index SCREAMING_SNAKE_CASE__ : Union[str, Any] =np.not_equal(UpperCamelCase__, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict =pred_label[mask] SCREAMING_SNAKE_CASE__ : Optional[int] =np.array(UpperCamelCase__ )[mask] SCREAMING_SNAKE_CASE__ : Optional[int] =pred_label[pred_label == label] SCREAMING_SNAKE_CASE__ : Optional[int] =np.histogram(UpperCamelCase__, bins=UpperCamelCase__, range=(0, num_labels - 1) )[0] SCREAMING_SNAKE_CASE__ : str =np.histogram(UpperCamelCase__, bins=UpperCamelCase__, range=(0, num_labels - 1) )[0] SCREAMING_SNAKE_CASE__ : Dict =np.histogram(UpperCamelCase__, bins=UpperCamelCase__, range=(0, num_labels - 1) )[0] SCREAMING_SNAKE_CASE__ : Any =area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def _a( UpperCamelCase__ : str, UpperCamelCase__ : Optional[Any], UpperCamelCase__ : List[Any], UpperCamelCase__ : bool, UpperCamelCase__ : Optional[Dict[int, int]] = None, UpperCamelCase__ : bool = False, ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =np.zeros((num_labels,), dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : Optional[int] =np.zeros((num_labels,), dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : Dict =np.zeros((num_labels,), dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : int =np.zeros((num_labels,), dtype=np.floataa ) for result, gt_seg_map in zip(UpperCamelCase__, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] =intersect_and_union( UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def _a( UpperCamelCase__ : Dict, UpperCamelCase__ : Tuple, UpperCamelCase__ : Tuple, UpperCamelCase__ : bool, UpperCamelCase__ : Optional[int] = None, UpperCamelCase__ : Optional[Dict[int, int]] = None, UpperCamelCase__ : bool = False, ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] =total_intersect_and_union( UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ) # compute metrics SCREAMING_SNAKE_CASE__ : str ={} SCREAMING_SNAKE_CASE__ : str =total_area_intersect.sum() / total_area_label.sum() SCREAMING_SNAKE_CASE__ : int =total_area_intersect / total_area_union SCREAMING_SNAKE_CASE__ : str =total_area_intersect / total_area_label SCREAMING_SNAKE_CASE__ : Optional[int] =np.nanmean(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =np.nanmean(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : str =all_acc SCREAMING_SNAKE_CASE__ : Optional[int] =iou SCREAMING_SNAKE_CASE__ : Optional[Any] =acc if nan_to_num is not None: SCREAMING_SNAKE_CASE__ : int ={metric: np.nan_to_num(UpperCamelCase__, nan=UpperCamelCase__ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def __magic_name__ ( self : Union[str, Any] ) -> Tuple: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { '''predictions''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16''' ) ) ), '''references''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16''' ) ) ), } ) , reference_urls=[ '''https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py''' ] , ) def __magic_name__ ( self : Tuple , __lowercase : str , __lowercase : Dict , __lowercase : int , __lowercase : bool , __lowercase : Optional[int] = None , __lowercase : Optional[Dict[int, int]] = None , __lowercase : bool = False , ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ : Tuple =mean_iou( results=__lowercase , gt_seg_maps=__lowercase , num_labels=__lowercase , ignore_index=__lowercase , nan_to_num=__lowercase , label_map=__lowercase , reduce_labels=__lowercase , ) return iou_result
152
'''simple docstring''' import unittest import numpy as np from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING from transformers.pipelines import AudioClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_torchaudio, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): snake_case_ = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING snake_case_ = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def __magic_name__ ( self : str , __lowercase : str , __lowercase : List[str] , __lowercase : Union[str, Any] ) -> Dict: SCREAMING_SNAKE_CASE__ : Union[str, Any] =AudioClassificationPipeline(model=__lowercase , feature_extractor=__lowercase ) # test with a raw waveform SCREAMING_SNAKE_CASE__ : Optional[int] =np.zeros((3_40_00,) ) SCREAMING_SNAKE_CASE__ : str =np.zeros((1_40_00,) ) return audio_classifier, [audioa, audio] def __magic_name__ ( self : Optional[int] , __lowercase : int , __lowercase : Optional[int] ) -> str: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict =examples SCREAMING_SNAKE_CASE__ : str =audio_classifier(__lowercase ) # by default a model is initialized with num_labels=2 self.assertEqual( __lowercase , [ {'''score''': ANY(__lowercase ), '''label''': ANY(__lowercase )}, {'''score''': ANY(__lowercase ), '''label''': ANY(__lowercase )}, ] , ) SCREAMING_SNAKE_CASE__ : List[Any] =audio_classifier(__lowercase , top_k=1 ) self.assertEqual( __lowercase , [ {'''score''': ANY(__lowercase ), '''label''': ANY(__lowercase )}, ] , ) self.run_torchaudio(__lowercase ) @require_torchaudio def __magic_name__ ( self : Union[str, Any] , __lowercase : str ) -> Optional[Any]: import datasets # test with a local file SCREAMING_SNAKE_CASE__ : Optional[int] =datasets.load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) SCREAMING_SNAKE_CASE__ : int =dataset[0]['''audio''']['''array'''] SCREAMING_SNAKE_CASE__ : Optional[Any] =audio_classifier(__lowercase ) self.assertEqual( __lowercase , [ {'''score''': ANY(__lowercase ), '''label''': ANY(__lowercase )}, {'''score''': ANY(__lowercase ), '''label''': ANY(__lowercase )}, ] , ) @require_torch def __magic_name__ ( self : List[str] ) -> Dict: SCREAMING_SNAKE_CASE__ : Dict ='''anton-l/wav2vec2-random-tiny-classifier''' SCREAMING_SNAKE_CASE__ : Optional[Any] =pipeline('''audio-classification''' , model=__lowercase ) SCREAMING_SNAKE_CASE__ : str =np.ones((80_00,) ) SCREAMING_SNAKE_CASE__ : List[str] =audio_classifier(__lowercase , top_k=4 ) SCREAMING_SNAKE_CASE__ : Dict =[ {'''score''': 0.0842, '''label''': '''no'''}, {'''score''': 0.0838, '''label''': '''up'''}, {'''score''': 0.0837, '''label''': '''go'''}, {'''score''': 0.0834, '''label''': '''right'''}, ] SCREAMING_SNAKE_CASE__ : List[str] =[ {'''score''': 0.0845, '''label''': '''stop'''}, {'''score''': 0.0844, '''label''': '''on'''}, {'''score''': 0.0841, '''label''': '''right'''}, {'''score''': 0.0834, '''label''': '''left'''}, ] self.assertIn(nested_simplify(__lowercase , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) SCREAMING_SNAKE_CASE__ : List[str] ={'''array''': np.ones((80_00,) ), '''sampling_rate''': audio_classifier.feature_extractor.sampling_rate} SCREAMING_SNAKE_CASE__ : Tuple =audio_classifier(__lowercase , top_k=4 ) self.assertIn(nested_simplify(__lowercase , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def __magic_name__ ( self : Dict ) -> Any: import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] ='''superb/wav2vec2-base-superb-ks''' SCREAMING_SNAKE_CASE__ : Optional[int] =pipeline('''audio-classification''' , model=__lowercase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] =datasets.load_dataset('''anton-l/superb_dummy''' , '''ks''' , split='''test''' ) SCREAMING_SNAKE_CASE__ : List[str] =np.array(dataset[3]['''speech'''] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : int =audio_classifier(__lowercase , top_k=4 ) self.assertEqual( nested_simplify(__lowercase , decimals=3 ) , [ {'''score''': 0.981, '''label''': '''go'''}, {'''score''': 0.007, '''label''': '''up'''}, {'''score''': 0.006, '''label''': '''_unknown_'''}, {'''score''': 0.001, '''label''': '''down'''}, ] , ) @require_tf @unittest.skip('''Audio classification is not implemented for TF''' ) def __magic_name__ ( self : List[str] ) -> Optional[int]: pass
152
1
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
367
from __future__ import annotations def UpperCAmelCase_ ( _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = len(_A ) // 2 # choose the middle 3 elements SCREAMING_SNAKE_CASE__ = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
218
0
'''simple docstring''' import sys a_ : Tuple = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def a_ ( __snake_case : str = N ) -> int: """simple docstring""" lowerCamelCase_ =-sys.maxsize - 1 for i in range(len(__snake_case ) - 12 ): lowerCamelCase_ =1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: lowerCamelCase_ =product return largest_product if __name__ == "__main__": print(F"""{solution() = }""")
75
'''simple docstring''' from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class __UpperCamelCase : lowercase : Union[str, Any] =XGLMConfig lowercase : Optional[Any] ={} lowercase : Optional[int] ='gelu' def __init__( self, lowerCAmelCase, lowerCAmelCase=14, lowerCAmelCase=7, lowerCAmelCase=True, lowerCAmelCase=True, lowerCAmelCase=True, lowerCAmelCase=99, lowerCAmelCase=32, lowerCAmelCase=2, lowerCAmelCase=4, lowerCAmelCase=37, lowerCAmelCase="gelu", lowerCAmelCase=0.1, lowerCAmelCase=0.1, lowerCAmelCase=512, lowerCAmelCase=0.0_2, ): """simple docstring""" lowerCamelCase_ =parent lowerCamelCase_ =batch_size lowerCamelCase_ =seq_length lowerCamelCase_ =is_training lowerCamelCase_ =use_input_mask lowerCamelCase_ =use_labels lowerCamelCase_ =vocab_size lowerCamelCase_ =d_model lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =ffn_dim lowerCamelCase_ =activation_function lowerCamelCase_ =activation_dropout lowerCamelCase_ =attention_dropout lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =initializer_range lowerCamelCase_ =None lowerCamelCase_ =0 lowerCamelCase_ =2 lowerCamelCase_ =1 def lowercase__ ( self ): """simple docstring""" return XGLMConfig.from_pretrained('''facebook/xglm-564M''' ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length], self.vocab_size ), clip_value_min=0, clip_value_max=3 ) lowerCamelCase_ =None if self.use_input_mask: lowerCamelCase_ =random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase_ =self.get_config() lowerCamelCase_ =floats_tensor([self.num_hidden_layers, self.num_attention_heads], 2 ) return ( config, input_ids, input_mask, head_mask, ) def lowercase__ ( self ): """simple docstring""" return XGLMConfig( vocab_size=self.vocab_size, d_model=self.hidden_size, num_layers=self.num_hidden_layers, attention_heads=self.num_attention_heads, ffn_dim=self.ffn_dim, activation_function=self.activation_function, activation_dropout=self.activation_dropout, attention_dropout=self.attention_dropout, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, use_cache=lowerCAmelCase, bos_token_id=self.bos_token_id, eos_token_id=self.eos_token_id, pad_token_id=self.pad_token_id, return_dict=lowerCAmelCase, ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.prepare_config_and_inputs() ( ( lowerCamelCase_ ), ( lowerCamelCase_ ), ( lowerCamelCase_ ), ( lowerCamelCase_ ), ) =config_and_inputs lowerCamelCase_ ={ '''input_ids''': input_ids, '''head_mask''': head_mask, } return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase : int =(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () lowercase : Optional[Any] =(TFXGLMForCausalLM,) if is_tf_available() else () lowercase : Tuple =( {'feature-extraction': TFXGLMModel, 'text-generation': TFXGLMForCausalLM} if is_tf_available() else {} ) lowercase : Optional[Any] =False lowercase : Optional[Any] =False lowercase : Optional[int] =False def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =TFXGLMModelTester(self ) lowerCamelCase_ =ConfigTester(self, config_class=lowerCAmelCase, n_embd=37 ) def lowercase__ ( self ): """simple docstring""" self.config_tester.run_common_tests() @slow def lowercase__ ( self ): """simple docstring""" for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase_ =TFXGLMModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.''' ) def lowercase__ ( self ): """simple docstring""" super().test_resize_token_embeddings() @require_tf class __UpperCamelCase ( unittest.TestCase ): @slow def lowercase__ ( self, lowerCAmelCase=True ): """simple docstring""" lowerCamelCase_ =TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' ) lowerCamelCase_ =tf.convert_to_tensor([[2, 268, 9_865]], dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off lowerCamelCase_ =[2, 268, 9_865, 67, 11, 1_988, 57_252, 9_865, 5, 984, 67, 1_988, 213_838, 1_658, 53, 70_446, 33, 6_657, 278, 1_581] # fmt: on lowerCamelCase_ =model.generate(lowerCAmelCase, do_sample=lowerCAmelCase, num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist(), lowerCAmelCase ) @slow def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) lowerCamelCase_ =TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' ) tf.random.set_seed(0 ) lowerCamelCase_ =tokenizer('''Today is a nice day and''', return_tensors='''tf''' ) lowerCamelCase_ =tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(''':/CPU:0''' ): lowerCamelCase_ =model.generate(lowerCAmelCase, do_sample=lowerCAmelCase, seed=[7, 0] ) lowerCamelCase_ =tokenizer.decode(output_ids[0], skip_special_tokens=lowerCAmelCase ) lowerCamelCase_ =( '''Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due''' ) self.assertEqual(lowerCAmelCase, lowerCAmelCase ) @slow def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M''' ) lowerCamelCase_ =XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) lowerCamelCase_ ='''left''' # use different length sentences to test batching lowerCamelCase_ =[ '''This is an extremelly long sentence that only exists to test the ability of the model to cope with ''' '''left-padding, such as in batched generation. The output for the sequence below should be the same ''' '''regardless of whether left padding is applied or not. When''', '''Hello, my dog is a little''', ] lowerCamelCase_ =tokenizer(lowerCAmelCase, return_tensors='''tf''', padding=lowerCAmelCase ) lowerCamelCase_ =inputs['''input_ids'''] lowerCamelCase_ =model.generate(input_ids=lowerCAmelCase, attention_mask=inputs['''attention_mask'''], max_new_tokens=12 ) lowerCamelCase_ =tokenizer(sentences[0], return_tensors='''tf''' ).input_ids lowerCamelCase_ =model.generate(input_ids=lowerCAmelCase, max_new_tokens=12 ) lowerCamelCase_ =tokenizer(sentences[1], return_tensors='''tf''' ).input_ids lowerCamelCase_ =model.generate(input_ids=lowerCAmelCase, max_new_tokens=12 ) lowerCamelCase_ =tokenizer.batch_decode(lowerCAmelCase, skip_special_tokens=lowerCAmelCase ) lowerCamelCase_ =tokenizer.decode(output_non_padded[0], skip_special_tokens=lowerCAmelCase ) lowerCamelCase_ =tokenizer.decode(output_padded[0], skip_special_tokens=lowerCAmelCase ) lowerCamelCase_ =[ '''This is an extremelly long sentence that only exists to test the ability of the model to cope with ''' '''left-padding, such as in batched generation. The output for the sequence below should be the same ''' '''regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ''' '''a single''', '''Hello, my dog is a little bit of a shy one, but he is very friendly''', ] self.assertListEqual(lowerCAmelCase, lowerCAmelCase ) self.assertListEqual(lowerCAmelCase, [non_padded_sentence, padded_sentence] )
75
1
"""simple docstring""" def _A ( UpperCamelCase_ : int, UpperCamelCase_ : int) -> int: '''simple docstring''' while a != 0: __lowercase ,__lowercase = b % a, a return b def _A ( UpperCamelCase_ : int, UpperCamelCase_ : int) -> int: '''simple docstring''' if gcd(UpperCamelCase__, UpperCamelCase__) != 1: __lowercase = F"""mod inverse of {a!r} and {m!r} does not exist""" raise ValueError(UpperCamelCase__) __lowercase ,__lowercase ,__lowercase = 1, 0, a __lowercase ,__lowercase ,__lowercase = 0, 1, m while va != 0: __lowercase = ua // va __lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
367
"""simple docstring""" import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def _A ( UpperCamelCase_ : str, UpperCamelCase_ : str, **UpperCamelCase_ : Optional[int]) -> Tuple: '''simple docstring''' __lowercase = AutoConfig.from_pretrained(UpperCamelCase_, **UpperCamelCase_) __lowercase = AutoModelForSeqaSeqLM.from_config(UpperCamelCase_) model.save_pretrained(UpperCamelCase_) AutoTokenizer.from_pretrained(UpperCamelCase_).save_pretrained(UpperCamelCase_) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
144
0
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class __A : '''simple docstring''' def __init__( self , __lowerCAmelCase = None ): '''simple docstring''' if components is None: lowerCamelCase__ = [] lowerCamelCase__ = list(__lowerCAmelCase ) def __len__( self ): '''simple docstring''' return len(self.__components ) def __str__( self ): '''simple docstring''' return "(" + ",".join(map(__lowerCAmelCase , self.__components ) ) + ")" def __add__( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = len(self ) if size == len(__lowerCAmelCase ): lowerCamelCase__ = [self.__components[i] + other.component(__lowerCAmelCase ) for i in range(__lowerCAmelCase )] return Vector(__lowerCAmelCase ) else: raise Exception('''must have the same size''' ) def __sub__( self , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = len(self ) if size == len(__lowerCAmelCase ): lowerCamelCase__ = [self.__components[i] - other.component(__lowerCAmelCase ) for i in range(__lowerCAmelCase )] return Vector(__lowerCAmelCase ) else: # error case raise Exception('''must have the same size''' ) @overload def __mul__( self , __lowerCAmelCase ): '''simple docstring''' ... @overload def __mul__( self , __lowerCAmelCase ): '''simple docstring''' ... def __mul__( self , __lowerCAmelCase ): '''simple docstring''' if isinstance(__lowerCAmelCase , (float, int) ): lowerCamelCase__ = [c * other for c in self.__components] return Vector(__lowerCAmelCase ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ) and len(self ) == len(__lowerCAmelCase ): lowerCamelCase__ = len(self ) lowerCamelCase__ = [self.__components[i] * other.component(__lowerCAmelCase ) for i in range(__lowerCAmelCase )] return sum(__lowerCAmelCase ) else: # error case raise Exception('''invalid operand!''' ) def __lowerCamelCase ( self ): '''simple docstring''' return Vector(self.__components ) def __lowerCamelCase ( self , __lowerCAmelCase ): '''simple docstring''' if isinstance(__lowerCAmelCase , __lowerCAmelCase ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('''index out of range''' ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase ): '''simple docstring''' assert -len(self.__components ) <= pos < len(self.__components ) lowerCamelCase__ = value def __lowerCamelCase ( self ): '''simple docstring''' if len(self.__components ) == 0: raise Exception('''Vector is empty''' ) lowerCamelCase__ = [c**2 for c in self.__components] return math.sqrt(sum(__lowerCAmelCase ) ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase = False ): '''simple docstring''' lowerCamelCase__ = self * other lowerCamelCase__ = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def lowerCAmelCase__(__snake_case ) -> Vector: '''simple docstring''' assert isinstance(__snake_case ,__snake_case ) return Vector([0] * dimension ) def lowerCAmelCase__(__snake_case ,__snake_case ) -> Vector: '''simple docstring''' assert isinstance(__snake_case ,__snake_case ) and (isinstance(__snake_case ,__snake_case )) lowerCamelCase__ = [0] * dimension lowerCamelCase__ = 1 return Vector(__snake_case ) def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ) -> Vector: '''simple docstring''' assert ( isinstance(__snake_case ,__snake_case ) and isinstance(__snake_case ,__snake_case ) and (isinstance(__snake_case ,(int, float) )) ) return x * scalar + y def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ) -> Vector: '''simple docstring''' random.seed(__snake_case ) lowerCamelCase__ = [random.randint(__snake_case ,__snake_case ) for _ in range(__snake_case )] return Vector(__snake_case ) class __A : '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): '''simple docstring''' lowerCamelCase__ = matrix lowerCamelCase__ = w lowerCamelCase__ = h def __str__( self ): '''simple docstring''' lowerCamelCase__ = '''''' 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 , __lowerCAmelCase ): '''simple docstring''' if self.__width == other.width() and self.__height == other.height(): lowerCamelCase__ = [] for i in range(self.__height ): lowerCamelCase__ = [ self.__matrix[i][j] + other.component(__lowerCAmelCase , __lowerCAmelCase ) for j in range(self.__width ) ] matrix.append(__lowerCAmelCase ) return Matrix(__lowerCAmelCase , self.__width , self.__height ) else: raise Exception('''matrix must have the same dimension!''' ) def __sub__( self , __lowerCAmelCase ): '''simple docstring''' if self.__width == other.width() and self.__height == other.height(): lowerCamelCase__ = [] for i in range(self.__height ): lowerCamelCase__ = [ self.__matrix[i][j] - other.component(__lowerCAmelCase , __lowerCAmelCase ) for j in range(self.__width ) ] matrix.append(__lowerCAmelCase ) return Matrix(__lowerCAmelCase , self.__width , self.__height ) else: raise Exception('''matrices must have the same dimension!''' ) @overload def __mul__( self , __lowerCAmelCase ): '''simple docstring''' ... @overload def __mul__( self , __lowerCAmelCase ): '''simple docstring''' ... def __mul__( self , __lowerCAmelCase ): '''simple docstring''' if isinstance(__lowerCAmelCase , __lowerCAmelCase ): # matrix-vector if len(__lowerCAmelCase ) == self.__width: lowerCamelCase__ = zero_vector(self.__height ) for i in range(self.__height ): lowerCamelCase__ = [ self.__matrix[i][j] * other.component(__lowerCAmelCase ) for j in range(self.__width ) ] ans.change_component(__lowerCAmelCase , sum(__lowerCAmelCase ) ) return ans else: raise Exception( '''vector must have the same size as the ''' '''number of columns of the matrix!''' ) elif isinstance(__lowerCAmelCase , (int, float) ): # matrix-scalar lowerCamelCase__ = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(__lowerCAmelCase , self.__width , self.__height ) return None def __lowerCamelCase ( self ): '''simple docstring''' return self.__height def __lowerCamelCase ( self ): '''simple docstring''' return self.__width def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase ): '''simple docstring''' 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 __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): '''simple docstring''' if 0 <= x < self.__height and 0 <= y < self.__width: lowerCamelCase__ = value else: raise Exception('''change_component: indices out of bounds''' ) def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase ): '''simple docstring''' if self.__height != self.__width: raise Exception('''Matrix is not square''' ) lowerCamelCase__ = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(__lowerCAmelCase ) ): lowerCamelCase__ = minor[i][:y] + minor[i][y + 1 :] return Matrix(__lowerCAmelCase , self.__width - 1 , self.__height - 1 ).determinant() def __lowerCamelCase ( self , __lowerCAmelCase , __lowerCAmelCase ): '''simple docstring''' 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(__lowerCAmelCase , __lowerCAmelCase ) else: raise Exception('''Indices out of bounds''' ) def __lowerCamelCase ( self ): '''simple docstring''' 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: lowerCamelCase__ = [ self.__matrix[0][y] * self.cofactor(0 , __lowerCAmelCase ) for y in range(self.__width ) ] return sum(__lowerCAmelCase ) def lowerCAmelCase__(__snake_case ) -> Matrix: '''simple docstring''' lowerCamelCase__ = [[0] * n for _ in range(__snake_case )] return Matrix(__snake_case ,__snake_case ,__snake_case ) def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> Matrix: '''simple docstring''' random.seed(__snake_case ) lowerCamelCase__ = [ [random.randint(__snake_case ,__snake_case ) for _ in range(__snake_case )] for _ in range(__snake_case ) ] return Matrix(__snake_case ,__snake_case ,__snake_case )
209
def lowerCAmelCase__(__snake_case ,__snake_case ) -> float: '''simple docstring''' if mass < 0: raise ValueError('''The mass of a body cannot be negative''' ) return 0.5 * mass * abs(__snake_case ) * abs(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
209
1
"""simple docstring""" import baseaa def UpperCamelCase_ ( lowerCAmelCase__ : str ) -> bytes: """simple docstring""" return baseaa.baaencode(string.encode('utf-8' ) ) def UpperCamelCase_ ( lowerCAmelCase__ : bytes ) -> str: """simple docstring""" return baseaa.baadecode(_lowerCamelCase ).decode('utf-8' ) if __name__ == "__main__": lowercase__ : Dict = """Hello World!""" lowercase__ : str = baseaa_encode(test) print(encoded) lowercase__ : Tuple = baseaa_decode(encoded) print(decoded)
370
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase__ : Dict = { """configuration_falcon""": ["""FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FalconConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : str = [ """FALCON_PRETRAINED_MODEL_ARCHIVE_LIST""", """FalconForCausalLM""", """FalconModel""", """FalconPreTrainedModel""", """FalconForSequenceClassification""", """FalconForTokenClassification""", """FalconForQuestionAnswering""", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys lowercase__ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
289
0
"""simple docstring""" import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''''' a__ =( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) a__ =None # compression type in fsspec. ex: "gzip" a__ =None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self , A = "" , A = None , A = None , **A ) -> Optional[Any]: super().__init__(self , **A ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode _UpperCAmelCase : Optional[Any] = fsspec.open( A , mode='''rb''' , protocol=A , compression=self.compression , client_kwargs={ '''requote_redirect_url''': False, # see https://github.com/huggingface/datasets/pull/5459 '''trust_env''': True, # Enable reading proxy env variables. **(target_options or {}).pop('''client_kwargs''' , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) _UpperCAmelCase : Optional[Any] = os.path.basename(self.file.path.split('''::''' )[0] ) _UpperCAmelCase : Any = ( self.compressed_name[: self.compressed_name.rindex('''.''' )] if '''.''' in self.compressed_name else self.compressed_name ) _UpperCAmelCase : Any = None @classmethod def __lowerCAmelCase ( cls , A ) -> Tuple: # compressed file paths are always relative to the archive root return super()._strip_protocol(A ).lstrip('''/''' ) def __lowerCAmelCase ( self ) -> Any: if self.dir_cache is None: _UpperCAmelCase : Dict = {**self.file.fs.info(self.file.path ), '''name''': self.uncompressed_name} _UpperCAmelCase : Tuple = {f['''name''']: f} def __lowerCAmelCase ( self , A ) -> Tuple: return self.file.open().read() def __lowerCAmelCase ( self , A , A = "rb" , A=None , A=True , A=None , **A , ) -> List[Any]: _UpperCAmelCase : Optional[Any] = self._strip_protocol(A ) if mode != "rb": raise ValueError(f'Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'' ) return self.file.open() class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''bz2''' a__ ='''bz2''' a__ ='''.bz2''' class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''gzip''' a__ ='''gzip''' a__ ='''.gz''' class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''lz4''' a__ ='''lz4''' a__ ='''.lz4''' class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''xz''' a__ ='''xz''' a__ ='''.xz''' class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''zstd''' a__ ='''zstd''' a__ ='''.zst''' def __init__( self , A , A = "rb" , A = None , A = None , A = DEFAULT_BLOCK_SIZE , **A , ) -> str: super().__init__( fo=A , mode=A , target_protocol=A , target_options=A , block_size=A , **A , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 _UpperCAmelCase : int = self.file.__enter__ class _UpperCAmelCase : '''simple docstring''' def __init__( self , A ) -> Optional[Any]: _UpperCAmelCase : Optional[int] = file_ def __enter__( self ) -> List[str]: self._file.__enter__() return self def __exit__( self , *A , **A ) -> Union[str, Any]: self._file.__exit__(*A , **A ) def __iter__( self ) -> Any: return iter(self._file ) def __lowerCAmelCase ( self ) -> List[str]: return next(self._file ) def __getattr__( self , A ) -> List[Any]: return getattr(self._file , A ) def fixed_enter(*A , **A ): return WrappedFile(_enter(*A , **A ) ) _UpperCAmelCase : Tuple = fixed_enter
263
"""simple docstring""" def lowerCamelCase_ (UpperCamelCase__ : int , UpperCamelCase__ : int ): if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) _UpperCAmelCase : List[str] = str(bin(UpperCamelCase__ ) )[2:] # remove the leading "0b" _UpperCAmelCase : str = str(bin(UpperCamelCase__ ) )[2:] _UpperCAmelCase : List[str] = max(len(UpperCamelCase__ ) , len(UpperCamelCase__ ) ) return "0b" + "".join( str(int('''1''' in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(UpperCamelCase__ ) , b_binary.zfill(UpperCamelCase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
263
1
import os def _lowerCamelCase( ) -> List[Any]: '''simple docstring''' __lowercase= os.path.join(os.path.dirname(lowercase__ ) , 'num.txt' ) with open(lowercase__ ) as file_hand: return str(sum(int(lowercase__ ) for line in file_hand ) )[:1_0] if __name__ == "__main__": print(solution())
304
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _lowerCamelCase( lowercase__ ) -> List[str]: '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _lowerCamelCase( lowercase__ ) -> int: '''simple docstring''' __lowercase= create_tensor(lowercase__ ) __lowercase= gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _lowerCamelCase( lowercase__ ) -> int: '''simple docstring''' __lowercase= [state.process_index] __lowercase= gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, F'{gathered_obj}, {len(lowercase__ )} != {state.num_processes}' assert gathered_obj == list(range(state.num_processes ) ), F'{gathered_obj} != {list(range(state.num_processes ) )}' def _lowerCamelCase( lowercase__ ) -> List[str]: '''simple docstring''' __lowercase= create_tensor(lowercase__ ) __lowercase= broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _lowerCamelCase( lowercase__ ) -> List[Any]: '''simple docstring''' if state.is_main_process: __lowercase= torch.arange(state.num_processes + 1 ).to(state.device ) else: __lowercase= torch.arange(state.num_processes ).to(state.device ) __lowercase= pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _lowerCamelCase( lowercase__ ) -> Any: '''simple docstring''' if state.num_processes != 2: return __lowercase= create_tensor(lowercase__ ) __lowercase= reduce(lowercase__ , 'sum' ) __lowercase= torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), F'{reduced_tensor} != {truth_tensor}' def _lowerCamelCase( lowercase__ ) -> Union[str, Any]: '''simple docstring''' if state.num_processes != 2: return __lowercase= create_tensor(lowercase__ ) __lowercase= reduce(lowercase__ , 'mean' ) __lowercase= torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), F'{reduced_tensor} != {truth_tensor}' def _lowerCamelCase( lowercase__ ) -> List[str]: '''simple docstring''' main() def _lowerCamelCase( ) -> List[str]: '''simple docstring''' __lowercase= PartialState() state.print(F'State: {state}' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
304
1
'''simple docstring''' import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def UpperCamelCase_ ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Optional[Any]=False ) -> Any: """simple docstring""" _UpperCAmelCase : Optional[int] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""module.blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""module.blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""module.blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""module.blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""module.blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("module.cls_token", "vit.embeddings.cls_token"), ("module.patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"), ("module.patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"), ("module.pos_embed", "vit.embeddings.position_embeddings"), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("module.norm.weight", "layernorm.weight"), ("module.norm.bias", "layernorm.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _UpperCAmelCase : str = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) return rename_keys def UpperCamelCase_ ( _UpperCAmelCase : int , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Dict=False ) -> Optional[Any]: """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: _UpperCAmelCase : int = "" else: _UpperCAmelCase : Any = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _UpperCAmelCase : List[Any] = state_dict.pop(F"""module.blocks.{i}.attn.qkv.weight""" ) _UpperCAmelCase : Optional[int] = state_dict.pop(F"""module.blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict _UpperCAmelCase : List[Any] = in_proj_weight[ : config.hidden_size, : ] _UpperCAmelCase : List[str] = in_proj_bias[: config.hidden_size] _UpperCAmelCase : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _UpperCAmelCase : str = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _UpperCAmelCase : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] _UpperCAmelCase : List[str] = in_proj_bias[-config.hidden_size :] def UpperCamelCase_ ( _UpperCAmelCase : List[str] ) -> Optional[int]: """simple docstring""" _UpperCAmelCase : str = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase ) def UpperCamelCase_ ( _UpperCAmelCase : List[Any] ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase : List[str] = [ "module.fc.fc1.weight", "module.fc.fc1.bias", "module.fc.bn1.weight", "module.fc.bn1.bias", "module.fc.bn1.running_mean", "module.fc.bn1.running_var", "module.fc.bn1.num_batches_tracked", "module.fc.fc2.weight", "module.fc.fc2.bias", "module.fc.bn2.weight", "module.fc.bn2.bias", "module.fc.bn2.running_mean", "module.fc.bn2.running_var", "module.fc.bn2.num_batches_tracked", "module.fc.fc3.weight", "module.fc.fc3.bias", ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase ) def UpperCamelCase_ ( _UpperCAmelCase : Dict , _UpperCAmelCase : Any , _UpperCAmelCase : Tuple ) -> List[str]: """simple docstring""" _UpperCAmelCase : List[Any] = dct.pop(_UpperCAmelCase ) _UpperCAmelCase : int = val def UpperCamelCase_ ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Dict ) -> str: """simple docstring""" _UpperCAmelCase : List[Any] = ViTMSNConfig() _UpperCAmelCase : Optional[int] = 1_000 _UpperCAmelCase : str = "datasets/huggingface/label-files" _UpperCAmelCase : List[str] = "imagenet-1k-id2label.json" _UpperCAmelCase : Optional[Any] = json.load(open(hf_hub_download(_UpperCAmelCase , _UpperCAmelCase ) , "r" ) ) _UpperCAmelCase : List[Any] = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} _UpperCAmelCase : Tuple = idalabel _UpperCAmelCase : Dict = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: _UpperCAmelCase : Dict = 384 _UpperCAmelCase : Any = 1_536 _UpperCAmelCase : str = 6 elif "l16" in checkpoint_url: _UpperCAmelCase : Union[str, Any] = 1_024 _UpperCAmelCase : Any = 4_096 _UpperCAmelCase : List[Any] = 24 _UpperCAmelCase : Tuple = 16 _UpperCAmelCase : Optional[Any] = 0.1 elif "b4" in checkpoint_url: _UpperCAmelCase : Optional[Any] = 4 elif "l7" in checkpoint_url: _UpperCAmelCase : List[str] = 7 _UpperCAmelCase : Optional[Any] = 1_024 _UpperCAmelCase : List[str] = 4_096 _UpperCAmelCase : Optional[int] = 24 _UpperCAmelCase : Union[str, Any] = 16 _UpperCAmelCase : Optional[int] = 0.1 _UpperCAmelCase : Tuple = ViTMSNModel(_UpperCAmelCase ) _UpperCAmelCase : int = torch.hub.load_state_dict_from_url(_UpperCAmelCase , map_location="cpu" )["target_encoder"] _UpperCAmelCase : List[Any] = ViTImageProcessor(size=config.image_size ) remove_projection_head(_UpperCAmelCase ) _UpperCAmelCase : str = create_rename_keys(_UpperCAmelCase , base_model=_UpperCAmelCase ) for src, dest in rename_keys: rename_key(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) read_in_q_k_v(_UpperCAmelCase , _UpperCAmelCase , base_model=_UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ) model.eval() _UpperCAmelCase : Any = "http://images.cocodataset.org/val2017/000000039769.jpg" _UpperCAmelCase : List[Any] = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw ) _UpperCAmelCase : Any = ViTImageProcessor( size=config.image_size , image_mean=_UpperCAmelCase , image_std=_UpperCAmelCase ) _UpperCAmelCase : Dict = image_processor(images=_UpperCAmelCase , return_tensors="pt" ) # forward pass torch.manual_seed(2 ) _UpperCAmelCase : Tuple = model(**_UpperCAmelCase ) _UpperCAmelCase : int = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: _UpperCAmelCase : Optional[int] = torch.tensor([[-1.0_9_1_5, -1.4_8_7_6, -1.1_8_0_9]] ) elif "b16" in checkpoint_url: _UpperCAmelCase : List[str] = torch.tensor([[1_4.2_8_8_9, -1_8.9_0_4_5, 1_1.7_2_8_1]] ) elif "l16" in checkpoint_url: _UpperCAmelCase : Optional[int] = torch.tensor([[4_1.5_0_2_8, -2_2.8_6_8_1, 4_5.6_4_7_5]] ) elif "b4" in checkpoint_url: _UpperCAmelCase : List[str] = torch.tensor([[-4.3_8_6_8, 5.2_9_3_2, -0.4_1_3_7]] ) else: _UpperCAmelCase : str = torch.tensor([[-0.1_7_9_2, -0.6_4_6_5, 2.4_2_6_3]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , _UpperCAmelCase , atol=1e-4 ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(_UpperCAmelCase ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar""", type=str, help="""URL of the checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) __SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
31
'''simple docstring''' from typing import Any def UpperCamelCase_ ( _UpperCAmelCase : list , _UpperCAmelCase : list , _UpperCAmelCase : dict , _UpperCAmelCase : dict , _UpperCAmelCase : dict , ) -> list: """simple docstring""" _validation( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) # Creates data structures and fill initial step _UpperCAmelCase : dict = {} _UpperCAmelCase : dict = {} for state in states_space: _UpperCAmelCase : Union[str, Any] = observations_space[0] _UpperCAmelCase : Tuple = ( initial_probabilities[state] * emission_probabilities[state][observation] ) _UpperCAmelCase : List[str] = None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1 , len(_UpperCAmelCase ) ): _UpperCAmelCase : Optional[Any] = observations_space[o] _UpperCAmelCase : int = observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function _UpperCAmelCase : str = "" _UpperCAmelCase : Tuple = -1 for k_state in states_space: _UpperCAmelCase : Any = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: _UpperCAmelCase : Union[str, Any] = probability _UpperCAmelCase : str = k_state # Update probabilities and pointers dicts _UpperCAmelCase : Optional[int] = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) _UpperCAmelCase : Tuple = arg_max # The final observation _UpperCAmelCase : Optional[Any] = observations_space[len(_UpperCAmelCase ) - 1] # argmax for given final observation _UpperCAmelCase : List[str] = "" _UpperCAmelCase : Any = -1 for k_state in states_space: _UpperCAmelCase : Optional[int] = probabilities[(k_state, final_observation)] if probability > max_probability: _UpperCAmelCase : int = probability _UpperCAmelCase : Dict = k_state _UpperCAmelCase : Dict = arg_max # Process pointers backwards _UpperCAmelCase : List[Any] = last_state _UpperCAmelCase : str = [] for o in range(len(_UpperCAmelCase ) - 1 , -1 , -1 ): result.append(_UpperCAmelCase ) _UpperCAmelCase : List[Any] = pointers[previous, observations_space[o]] result.reverse() return result def UpperCamelCase_ ( _UpperCAmelCase : Any , _UpperCAmelCase : Any , _UpperCAmelCase : Any , _UpperCAmelCase : Any , _UpperCAmelCase : Any , ) -> None: """simple docstring""" _validate_not_empty( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) _validate_lists(_UpperCAmelCase , _UpperCAmelCase ) _validate_dicts( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) def UpperCamelCase_ ( _UpperCAmelCase : Any , _UpperCAmelCase : Any , _UpperCAmelCase : Any , _UpperCAmelCase : Any , _UpperCAmelCase : Any , ) -> None: """simple docstring""" if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("There's an empty parameter" ) def UpperCamelCase_ ( _UpperCAmelCase : Any , _UpperCAmelCase : Any ) -> None: """simple docstring""" _validate_list(_UpperCAmelCase , "observations_space" ) _validate_list(_UpperCAmelCase , "states_space" ) def UpperCamelCase_ ( _UpperCAmelCase : Any , _UpperCAmelCase : str ) -> None: """simple docstring""" if not isinstance(_object , _UpperCAmelCase ): _UpperCAmelCase : Optional[int] = F"""{var_name} must be a list""" raise ValueError(_UpperCAmelCase ) else: for x in _object: if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): _UpperCAmelCase : Optional[int] = F"""{var_name} must be a list of strings""" raise ValueError(_UpperCAmelCase ) def UpperCamelCase_ ( _UpperCAmelCase : Any , _UpperCAmelCase : Any , _UpperCAmelCase : Any , ) -> None: """simple docstring""" _validate_dict(_UpperCAmelCase , "initial_probabilities" , _UpperCAmelCase ) _validate_nested_dict(_UpperCAmelCase , "transition_probabilities" ) _validate_nested_dict(_UpperCAmelCase , "emission_probabilities" ) def UpperCamelCase_ ( _UpperCAmelCase : Any , _UpperCAmelCase : str ) -> None: """simple docstring""" _validate_dict(_object , _UpperCAmelCase , _UpperCAmelCase ) for x in _object.values(): _validate_dict(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) def UpperCamelCase_ ( _UpperCAmelCase : Any , _UpperCAmelCase : str , _UpperCAmelCase : type , _UpperCAmelCase : bool = False ) -> None: """simple docstring""" if not isinstance(_object , _UpperCAmelCase ): _UpperCAmelCase : Any = F"""{var_name} must be a dict""" raise ValueError(_UpperCAmelCase ) if not all(isinstance(_UpperCAmelCase , _UpperCAmelCase ) for x in _object ): _UpperCAmelCase : Tuple = F"""{var_name} all keys must be strings""" raise ValueError(_UpperCAmelCase ) if not all(isinstance(_UpperCAmelCase , _UpperCAmelCase ) for x in _object.values() ): _UpperCAmelCase : List[str] = "nested dictionary " if nested else "" _UpperCAmelCase : List[str] = F"""{var_name} {nested_text}all values must be {value_type.__name__}""" raise ValueError(_UpperCAmelCase ) if __name__ == "__main__": from doctest import testmod testmod()
31
1
def __lowerCamelCase (UpperCAmelCase__ : float , UpperCAmelCase__ : int ): if digit_amount > 0: return round(number - int(UpperCAmelCase__ ) , UpperCAmelCase__ ) return number - int(UpperCAmelCase__ ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
206
import argparse import collections import json import os import re import string import sys import numpy as np _lowerCamelCase : Dict = re.compile(r'''\b(a|an|the)\b''', re.UNICODE) _lowerCamelCase : Optional[int] = None def __lowerCamelCase (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=UpperCAmelCase__ , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=UpperCAmelCase__ , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __lowerCamelCase (UpperCAmelCase__ : Optional[int] ): SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = bool(qa["answers"]["text"] ) return qid_to_has_ans def __lowerCamelCase (UpperCAmelCase__ : Union[str, Any] ): def remove_articles(UpperCAmelCase__ : List[str] ): return ARTICLES_REGEX.sub(" " , UpperCAmelCase__ ) def white_space_fix(UpperCAmelCase__ : Dict ): return " ".join(text.split() ) def remove_punc(UpperCAmelCase__ : str ): SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(UpperCAmelCase__ : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(UpperCAmelCase__ ) ) ) ) def __lowerCamelCase (UpperCAmelCase__ : List[str] ): if not s: return [] return normalize_answer(UpperCAmelCase__ ).split() def __lowerCamelCase (UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ): return int(normalize_answer(UpperCAmelCase__ ) == normalize_answer(UpperCAmelCase__ ) ) def __lowerCamelCase (UpperCAmelCase__ : Any , UpperCAmelCase__ : str ): SCREAMING_SNAKE_CASE = get_tokens(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = get_tokens(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = collections.Counter(UpperCAmelCase__ ) & collections.Counter(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = sum(common.values() ) if len(UpperCAmelCase__ ) == 0 or len(UpperCAmelCase__ ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 SCREAMING_SNAKE_CASE = 1.0 * num_same / len(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = 1.0 * num_same / len(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = (2 * precision * recall) / (precision + recall) return fa def __lowerCamelCase (UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple ): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: SCREAMING_SNAKE_CASE = qa["id"] SCREAMING_SNAKE_CASE = [t for t in qa["answers"]["text"] if normalize_answer(UpperCAmelCase__ )] if not gold_answers: # For unanswerable questions, only correct answer is empty string SCREAMING_SNAKE_CASE = [""] if qid not in preds: print(F"Missing prediction for {qid}" ) continue SCREAMING_SNAKE_CASE = preds[qid] # Take max over all gold answers SCREAMING_SNAKE_CASE = max(compute_exact(UpperCAmelCase__ , UpperCAmelCase__ ) for a in gold_answers ) SCREAMING_SNAKE_CASE = max(compute_fa(UpperCAmelCase__ , UpperCAmelCase__ ) for a in gold_answers ) return exact_scores, fa_scores def __lowerCamelCase (UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str ): SCREAMING_SNAKE_CASE = {} for qid, s in scores.items(): SCREAMING_SNAKE_CASE = na_probs[qid] > na_prob_thresh if pred_na: SCREAMING_SNAKE_CASE = float(not qid_to_has_ans[qid] ) else: SCREAMING_SNAKE_CASE = s return new_scores def __lowerCamelCase (UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict=None ): if not qid_list: SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def __lowerCamelCase (UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] ): for k in new_eval: SCREAMING_SNAKE_CASE = new_eval[k] def __lowerCamelCase (UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] ): plt.step(UpperCAmelCase__ , UpperCAmelCase__ , color="b" , alpha=0.2 , where="post" ) plt.fill_between(UpperCAmelCase__ , UpperCAmelCase__ , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(UpperCAmelCase__ ) plt.savefig(UpperCAmelCase__ ) plt.clf() def __lowerCamelCase (UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : str=None ): SCREAMING_SNAKE_CASE = sorted(UpperCAmelCase__ , key=lambda UpperCAmelCase__ : na_probs[k] ) SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = 1.0 SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = [1.0] SCREAMING_SNAKE_CASE = [0.0] SCREAMING_SNAKE_CASE = 0.0 for i, qid in enumerate(UpperCAmelCase__ ): if qid_to_has_ans[qid]: true_pos += scores[qid] SCREAMING_SNAKE_CASE = true_pos / float(i + 1 ) SCREAMING_SNAKE_CASE = true_pos / float(UpperCAmelCase__ ) if i == len(UpperCAmelCase__ ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(UpperCAmelCase__ ) recalls.append(UpperCAmelCase__ ) if out_image: plot_pr_curve(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return {"ap": 100.0 * avg_prec} def __lowerCamelCase (UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] ): if out_image_dir and not os.path.exists(UpperCAmelCase__ ): os.makedirs(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return SCREAMING_SNAKE_CASE = make_precision_recall_eval( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , out_image=os.path.join(UpperCAmelCase__ , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) SCREAMING_SNAKE_CASE = make_precision_recall_eval( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , out_image=os.path.join(UpperCAmelCase__ , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) SCREAMING_SNAKE_CASE = {k: float(UpperCAmelCase__ ) for k, v in qid_to_has_ans.items()} SCREAMING_SNAKE_CASE = make_precision_recall_eval( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , out_image=os.path.join(UpperCAmelCase__ , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(UpperCAmelCase__ , UpperCAmelCase__ , "pr_exact" ) merge_eval(UpperCAmelCase__ , UpperCAmelCase__ , "pr_f1" ) merge_eval(UpperCAmelCase__ , UpperCAmelCase__ , "pr_oracle" ) def __lowerCamelCase (UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int ): if not qid_list: return SCREAMING_SNAKE_CASE = [na_probs[k] for k in qid_list] SCREAMING_SNAKE_CASE = np.ones_like(UpperCAmelCase__ ) / float(len(UpperCAmelCase__ ) ) plt.hist(UpperCAmelCase__ , weights=UpperCAmelCase__ , bins=2_0 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F"Histogram of no-answer probability: {name}" ) plt.savefig(os.path.join(UpperCAmelCase__ , F"na_prob_hist_{name}.png" ) ) plt.clf() def __lowerCamelCase (UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ): SCREAMING_SNAKE_CASE = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) SCREAMING_SNAKE_CASE = num_no_ans SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = sorted(UpperCAmelCase__ , key=lambda UpperCAmelCase__ : na_probs[k] ) for i, qid in enumerate(UpperCAmelCase__ ): if qid not in scores: continue if qid_to_has_ans[qid]: SCREAMING_SNAKE_CASE = scores[qid] else: if preds[qid]: SCREAMING_SNAKE_CASE = -1 else: SCREAMING_SNAKE_CASE = 0 cur_score += diff if cur_score > best_score: SCREAMING_SNAKE_CASE = cur_score SCREAMING_SNAKE_CASE = na_probs[qid] return 100.0 * best_score / len(UpperCAmelCase__ ), best_thresh def __lowerCamelCase (UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = find_best_thresh(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = best_exact SCREAMING_SNAKE_CASE = exact_thresh SCREAMING_SNAKE_CASE = best_fa SCREAMING_SNAKE_CASE = fa_thresh def __lowerCamelCase (): with open(OPTS.data_file ) as f: SCREAMING_SNAKE_CASE = json.load(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = dataset_json["data"] with open(OPTS.pred_file ) as f: SCREAMING_SNAKE_CASE = json.load(UpperCAmelCase__ ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: SCREAMING_SNAKE_CASE = json.load(UpperCAmelCase__ ) else: SCREAMING_SNAKE_CASE = {k: 0.0 for k in preds} SCREAMING_SNAKE_CASE = make_qid_to_has_ans(UpperCAmelCase__ ) # maps qid to True/False SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if v] SCREAMING_SNAKE_CASE = [k for k, v in qid_to_has_ans.items() if not v] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_raw_scores(UpperCAmelCase__ , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , OPTS.na_prob_thresh ) SCREAMING_SNAKE_CASE = apply_no_ans_threshold(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , OPTS.na_prob_thresh ) SCREAMING_SNAKE_CASE = make_eval_dict(UpperCAmelCase__ , UpperCAmelCase__ ) if has_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(UpperCAmelCase__ , UpperCAmelCase__ , qid_list=UpperCAmelCase__ ) merge_eval(UpperCAmelCase__ , UpperCAmelCase__ , "HasAns" ) if no_ans_qids: SCREAMING_SNAKE_CASE = make_eval_dict(UpperCAmelCase__ , UpperCAmelCase__ , qid_list=UpperCAmelCase__ ) merge_eval(UpperCAmelCase__ , UpperCAmelCase__ , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , OPTS.out_image_dir ) histogram_na_prob(UpperCAmelCase__ , UpperCAmelCase__ , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(UpperCAmelCase__ , UpperCAmelCase__ , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) else: print(json.dumps(UpperCAmelCase__ , indent=2 ) ) if __name__ == "__main__": _lowerCamelCase : Optional[Any] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('''Agg''') import matplotlib.pyplot as plt main()
206
1
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging A__ = """\ """ A__ = """ Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity """ A__ = """ Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to 'cuda' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric(\"perplexity\") >>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"] >>> results = perplexity.compute(model_id='gpt2', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) ['perplexities', 'mean_perplexity'] >>> print(round(results[\"mean_perplexity\"], 2)) 78.22 >>> print(round(results[\"perplexities\"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric(\"perplexity\") >>> input_texts = datasets.load_dataset(\"wikitext\", ... \"wikitext-2-raw-v1\", ... split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=''] >>> results = perplexity.compute(model_id='gpt2', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) ['perplexities', 'mean_perplexity'] >>> print(round(results[\"mean_perplexity\"], 2)) 60.35 >>> print(round(results[\"perplexities\"][0], 2)) 81.12 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def snake_case ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """input_texts""": datasets.Value("""string""" ), } ) , reference_urls=["""https://huggingface.co/docs/transformers/perplexity"""] , ) def snake_case ( self , _snake_case , _snake_case , _snake_case = 16 , _snake_case = True , _snake_case=None ): """simple docstring""" if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": _lowerCAmelCase = """cuda""" else: _lowerCAmelCase = """cuda""" if torch.cuda.is_available() else """cpu""" _lowerCAmelCase = AutoModelForCausalLM.from_pretrained(_snake_case ) _lowerCAmelCase = model.to(_snake_case ) _lowerCAmelCase = AutoTokenizer.from_pretrained(_snake_case ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: _lowerCAmelCase = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(_snake_case ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({"""pad_token""": existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" _lowerCAmelCase = model.config.max_length - 1 else: _lowerCAmelCase = model.config.max_length _lowerCAmelCase = tokenizer( _snake_case , add_special_tokens=_snake_case , padding=_snake_case , truncation=_snake_case , max_length=_snake_case , return_tensors="""pt""" , return_attention_mask=_snake_case , ).to(_snake_case ) _lowerCAmelCase = encodings["""input_ids"""] _lowerCAmelCase = encodings["""attention_mask"""] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." _lowerCAmelCase = [] _lowerCAmelCase = CrossEntropyLoss(reduction="""none""" ) for start_index in logging.tqdm(range(0 , len(_snake_case ) , _snake_case ) ): _lowerCAmelCase = min(start_index + batch_size , len(_snake_case ) ) _lowerCAmelCase = encoded_texts[start_index:end_index] _lowerCAmelCase = attn_masks[start_index:end_index] if add_start_token: _lowerCAmelCase = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(_snake_case ) _lowerCAmelCase = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) _lowerCAmelCase = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(_snake_case ), attn_mask] , dim=1 ) _lowerCAmelCase = encoded_batch with torch.no_grad(): _lowerCAmelCase = model(_snake_case , attention_mask=_snake_case ).logits _lowerCAmelCase = out_logits[..., :-1, :].contiguous() _lowerCAmelCase = labels[..., 1:].contiguous() _lowerCAmelCase = attn_mask[..., 1:].contiguous() _lowerCAmelCase = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , _snake_case ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(_snake_case )}
82
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Dict: """simple docstring""" return params[f"{prefix}/{prefix}/relpos_bias/rel_embedding"][:, i, :] def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase="attention" ) -> Optional[Any]: """simple docstring""" lowerCamelCase__ : str = np.ascontiguousarray(params[f"{prefix}/{prefix}/{layer_name}/key/kernel"][:, i, :, :] ) lowerCamelCase__ : Union[str, Any] = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) lowerCamelCase__ : Dict = np.ascontiguousarray(params[f"{prefix}/{prefix}/{layer_name}/out/kernel"][:, i, :, :] ) lowerCamelCase__ : Tuple = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) lowerCamelCase__ : int = np.ascontiguousarray(params[f"{prefix}/{prefix}/{layer_name}/query/kernel"][:, i, :, :] ) lowerCamelCase__ : str = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) lowerCamelCase__ : Any = np.ascontiguousarray(params[f"{prefix}/{prefix}/{layer_name}/value/kernel"][:, i, :, :] ) lowerCamelCase__ : Optional[int] = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=False ) -> Union[str, Any]: """simple docstring""" if split_mlp_wi: lowerCamelCase__ : Dict = params[f"{prefix}/{prefix}/mlp/wi_0/kernel"][:, i, :] lowerCamelCase__ : List[Any] = params[f"{prefix}/{prefix}/mlp/wi_1/kernel"][:, i, :] lowerCamelCase__ : str = (wi_a, wi_a) else: lowerCamelCase__ : Optional[int] = params[f"{prefix}/{prefix}/mlp/wi/kernel"][:, i, :] lowerCamelCase__ : Tuple = params[f"{prefix}/{prefix}/mlp/wo/kernel"][:, i, :] return wi, wo def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: """simple docstring""" return params[f"{prefix}/{prefix}/{layer_name}/scale"][:, i] def _a ( UpperCAmelCase , *, UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = False ) -> Union[str, Any]: """simple docstring""" lowerCamelCase__ : List[str] = traverse_util.flatten_dict(variables['''target'''] ) lowerCamelCase__ : Union[str, Any] = {'''/'''.join(UpperCAmelCase ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi lowerCamelCase__ : Any = '''encoder/encoder/mlp/wi_0/kernel''' in old print('''Split MLP:''' , UpperCAmelCase ) lowerCamelCase__ : List[str] = collections.OrderedDict() # Shared embeddings. lowerCamelCase__ : List[Any] = old['''token_embedder/embedding'''] # Encoder. for i in range(UpperCAmelCase ): # Block i, layer 0 (Self Attention). lowerCamelCase__ : int = tax_layer_norm_lookup(UpperCAmelCase , UpperCAmelCase , '''encoder''' , '''pre_attention_layer_norm''' ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : List[str] = tax_attention_lookup(UpperCAmelCase , UpperCAmelCase , '''encoder''' , '''attention''' ) lowerCamelCase__ : Optional[Any] = layer_norm lowerCamelCase__ : Tuple = k.T lowerCamelCase__ : Tuple = o.T lowerCamelCase__ : List[Any] = q.T lowerCamelCase__ : Optional[int] = v.T # Block i, layer 1 (MLP). lowerCamelCase__ : Optional[Any] = tax_layer_norm_lookup(UpperCAmelCase , UpperCAmelCase , '''encoder''' , '''pre_mlp_layer_norm''' ) lowerCamelCase__ , lowerCamelCase__ : Any = tax_mlp_lookup(UpperCAmelCase , UpperCAmelCase , '''encoder''' , UpperCAmelCase ) lowerCamelCase__ : Any = layer_norm if split_mlp_wi: lowerCamelCase__ : Any = wi[0].T lowerCamelCase__ : Any = wi[1].T else: lowerCamelCase__ : Tuple = wi.T lowerCamelCase__ : List[str] = wo.T if scalable_attention: # convert the rel_embedding of each layer lowerCamelCase__ : Tuple = tax_relpos_bias_lookup( UpperCAmelCase , UpperCAmelCase , '''encoder''' ).T lowerCamelCase__ : List[Any] = old['''encoder/encoder_norm/scale'''] if not scalable_attention: lowerCamelCase__ : Optional[Any] = tax_relpos_bias_lookup( UpperCAmelCase , 0 , '''encoder''' ).T lowerCamelCase__ : Any = tax_relpos_bias_lookup( UpperCAmelCase , 0 , '''decoder''' ).T if not is_encoder_only: # Decoder. for i in range(UpperCAmelCase ): # Block i, layer 0 (Self Attention). lowerCamelCase__ : int = tax_layer_norm_lookup(UpperCAmelCase , UpperCAmelCase , '''decoder''' , '''pre_self_attention_layer_norm''' ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Optional[Any] = tax_attention_lookup(UpperCAmelCase , UpperCAmelCase , '''decoder''' , '''self_attention''' ) lowerCamelCase__ : Tuple = layer_norm lowerCamelCase__ : Tuple = k.T lowerCamelCase__ : List[Any] = o.T lowerCamelCase__ : List[Any] = q.T lowerCamelCase__ : Union[str, Any] = v.T # Block i, layer 1 (Cross Attention). lowerCamelCase__ : Dict = tax_layer_norm_lookup(UpperCAmelCase , UpperCAmelCase , '''decoder''' , '''pre_cross_attention_layer_norm''' ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : List[Any] = tax_attention_lookup(UpperCAmelCase , UpperCAmelCase , '''decoder''' , '''encoder_decoder_attention''' ) lowerCamelCase__ : int = layer_norm lowerCamelCase__ : int = k.T lowerCamelCase__ : List[Any] = o.T lowerCamelCase__ : Dict = q.T lowerCamelCase__ : Union[str, Any] = v.T # Block i, layer 2 (MLP). lowerCamelCase__ : List[str] = tax_layer_norm_lookup(UpperCAmelCase , UpperCAmelCase , '''decoder''' , '''pre_mlp_layer_norm''' ) lowerCamelCase__ , lowerCamelCase__ : int = tax_mlp_lookup(UpperCAmelCase , UpperCAmelCase , '''decoder''' , UpperCAmelCase ) lowerCamelCase__ : Optional[int] = layer_norm if split_mlp_wi: lowerCamelCase__ : List[str] = wi[0].T lowerCamelCase__ : Optional[int] = wi[1].T else: lowerCamelCase__ : List[str] = wi.T lowerCamelCase__ : Tuple = wo.T if scalable_attention: # convert the rel_embedding of each layer lowerCamelCase__ : Dict = tax_relpos_bias_lookup(UpperCAmelCase , UpperCAmelCase , '''decoder''' ).T lowerCamelCase__ : str = old['''decoder/decoder_norm/scale'''] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: lowerCamelCase__ : Dict = old['''decoder/logits_dense/kernel'''].T return new def _a ( UpperCAmelCase , UpperCAmelCase ) -> int: """simple docstring""" lowerCamelCase__ : str = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: lowerCamelCase__ : str = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: lowerCamelCase__ : Optional[Any] = state_dict['''shared.weight'''] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) lowerCamelCase__ : Dict = state_dict['''shared.weight'''] return state_dict def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> int: """simple docstring""" lowerCamelCase__ : str = checkpoints.load_tax_checkpoint(UpperCAmelCase ) lowerCamelCase__ : str = convert_tax_to_pytorch( UpperCAmelCase , num_layers=config.num_layers , is_encoder_only=UpperCAmelCase , scalable_attention=UpperCAmelCase ) lowerCamelCase__ : int = make_state_dict(UpperCAmelCase , UpperCAmelCase ) model.load_state_dict(UpperCAmelCase , strict=UpperCAmelCase ) def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = False , UpperCAmelCase = False , ) -> str: """simple docstring""" lowerCamelCase__ : List[Any] = MTaConfig.from_json_file(UpperCAmelCase ) print(f"Building PyTorch model from configuration: {config}" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: lowerCamelCase__ : Optional[int] = UMTaEncoderModel(UpperCAmelCase ) else: lowerCamelCase__ : List[str] = UMTaForConditionalGeneration(UpperCAmelCase ) # Load weights from tf checkpoint load_tax_weights_in_ta(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) model.save_pretrained(UpperCAmelCase ) # Verify that we can load the checkpoint. model.from_pretrained(UpperCAmelCase ) print('''Done''' ) if __name__ == "__main__": _A : Union[str, Any] = argparse.ArgumentParser(description='Converts a native T5X checkpoint into a PyTorch checkpoint.') # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path to the T5X checkpoint.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_encoder_only', action='store_true', help='Check if the model is encoder-decoder model', default=False ) parser.add_argument( '--scalable_attention', action='store_true', help='Whether the model uses scaled attention (umt5 model)', default=False, ) _A : str = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
142
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger(__name__) def __a ( lowerCAmelCase_ : str ,lowerCAmelCase_ : int=False ,lowerCAmelCase_ : List[Any]=False ,lowerCAmelCase_ : Optional[int]=False ) -> List[str]: '''simple docstring''' UpperCAmelCase_= [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""transformer.blocks.{i}.norm1.weight""", F"""vilt.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.norm1.bias""", F"""vilt.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""transformer.blocks.{i}.attn.proj.weight""", F"""vilt.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append( (F"""transformer.blocks.{i}.attn.proj.bias""", F"""vilt.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""transformer.blocks.{i}.norm2.weight""", F"""vilt.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.norm2.bias""", F"""vilt.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append( (F"""transformer.blocks.{i}.mlp.fc1.weight""", F"""vilt.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.mlp.fc1.bias""", F"""vilt.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""transformer.blocks.{i}.mlp.fc2.weight""", F"""vilt.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""transformer.blocks.{i}.mlp.fc2.bias""", F"""vilt.encoder.layer.{i}.output.dense.bias""") ) # embeddings rename_keys.extend( [ # text embeddings ("""text_embeddings.word_embeddings.weight""", """vilt.embeddings.text_embeddings.word_embeddings.weight"""), ( """text_embeddings.position_embeddings.weight""", """vilt.embeddings.text_embeddings.position_embeddings.weight""", ), ("""text_embeddings.position_ids""", """vilt.embeddings.text_embeddings.position_ids"""), ( """text_embeddings.token_type_embeddings.weight""", """vilt.embeddings.text_embeddings.token_type_embeddings.weight""", ), ("""text_embeddings.LayerNorm.weight""", """vilt.embeddings.text_embeddings.LayerNorm.weight"""), ("""text_embeddings.LayerNorm.bias""", """vilt.embeddings.text_embeddings.LayerNorm.bias"""), # patch embeddings ("""transformer.cls_token""", """vilt.embeddings.cls_token"""), ("""transformer.patch_embed.proj.weight""", """vilt.embeddings.patch_embeddings.projection.weight"""), ("""transformer.patch_embed.proj.bias""", """vilt.embeddings.patch_embeddings.projection.bias"""), ("""transformer.pos_embed""", """vilt.embeddings.position_embeddings"""), # token type embeddings ("""token_type_embeddings.weight""", """vilt.embeddings.token_type_embeddings.weight"""), ] ) # final layernorm + pooler rename_keys.extend( [ ("""transformer.norm.weight""", """vilt.layernorm.weight"""), ("""transformer.norm.bias""", """vilt.layernorm.bias"""), ("""pooler.dense.weight""", """vilt.pooler.dense.weight"""), ("""pooler.dense.bias""", """vilt.pooler.dense.bias"""), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ("""vqa_classifier.0.weight""", """classifier.0.weight"""), ("""vqa_classifier.0.bias""", """classifier.0.bias"""), ("""vqa_classifier.1.weight""", """classifier.1.weight"""), ("""vqa_classifier.1.bias""", """classifier.1.bias"""), ("""vqa_classifier.3.weight""", """classifier.3.weight"""), ("""vqa_classifier.3.bias""", """classifier.3.bias"""), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ("""nlvr2_classifier.0.weight""", """classifier.0.weight"""), ("""nlvr2_classifier.0.bias""", """classifier.0.bias"""), ("""nlvr2_classifier.1.weight""", """classifier.1.weight"""), ("""nlvr2_classifier.1.bias""", """classifier.1.bias"""), ("""nlvr2_classifier.3.weight""", """classifier.3.weight"""), ("""nlvr2_classifier.3.bias""", """classifier.3.bias"""), ] ) else: pass return rename_keys def __a ( lowerCAmelCase_ : Tuple ,lowerCAmelCase_ : Tuple ) -> Optional[int]: '''simple docstring''' for i in range(config.num_hidden_layers ): UpperCAmelCase_= """vilt.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase_= state_dict.pop(F"""transformer.blocks.{i}.attn.qkv.weight""" ) UpperCAmelCase_= state_dict.pop(F"""transformer.blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase_= in_proj_weight[ : config.hidden_size, : ] UpperCAmelCase_= in_proj_bias[: config.hidden_size] UpperCAmelCase_= in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase_= in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase_= in_proj_weight[ -config.hidden_size :, : ] UpperCAmelCase_= in_proj_bias[-config.hidden_size :] def __a ( lowerCAmelCase_ : Tuple ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_= ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ ,lowerCAmelCase_ ) def __a ( lowerCAmelCase_ : Tuple ,lowerCAmelCase_ : Optional[Any] ,lowerCAmelCase_ : Union[str, Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_= dct.pop(lowerCAmelCase_ ) UpperCAmelCase_= val @torch.no_grad() def __a ( lowerCAmelCase_ : List[str] ,lowerCAmelCase_ : List[str] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_= ViltConfig(image_size=3_84 ,patch_size=32 ,tie_word_embeddings=lowerCAmelCase_ ) UpperCAmelCase_= False UpperCAmelCase_= False UpperCAmelCase_= False UpperCAmelCase_= False if "vqa" in checkpoint_url: UpperCAmelCase_= True UpperCAmelCase_= 31_29 UpperCAmelCase_= """huggingface/label-files""" UpperCAmelCase_= """vqa2-id2label.json""" UpperCAmelCase_= json.load(open(hf_hub_download(lowerCAmelCase_ ,lowerCAmelCase_ ,repo_type="""dataset""" ) ,"""r""" ) ) UpperCAmelCase_= {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} UpperCAmelCase_= idalabel UpperCAmelCase_= {v: k for k, v in idalabel.items()} UpperCAmelCase_= ViltForQuestionAnswering(lowerCAmelCase_ ) elif "nlvr" in checkpoint_url: UpperCAmelCase_= True UpperCAmelCase_= 2 UpperCAmelCase_= {0: """False""", 1: """True"""} UpperCAmelCase_= {v: k for k, v in config.idalabel.items()} UpperCAmelCase_= 3 UpperCAmelCase_= ViltForImagesAndTextClassification(lowerCAmelCase_ ) elif "irtr" in checkpoint_url: UpperCAmelCase_= True UpperCAmelCase_= ViltForImageAndTextRetrieval(lowerCAmelCase_ ) elif "mlm_itm" in checkpoint_url: UpperCAmelCase_= True UpperCAmelCase_= ViltForMaskedLM(lowerCAmelCase_ ) else: raise ValueError("""Unknown model type""" ) # load state_dict of original model, remove and rename some keys UpperCAmelCase_= torch.hub.load_state_dict_from_url(lowerCAmelCase_ ,map_location="""cpu""" )["""state_dict"""] UpperCAmelCase_= create_rename_keys(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) for src, dest in rename_keys: rename_key(lowerCAmelCase_ ,lowerCAmelCase_ ,lowerCAmelCase_ ) read_in_q_k_v(lowerCAmelCase_ ,lowerCAmelCase_ ) if mlm_model or irtr_model: UpperCAmelCase_= ["""itm_score.fc.weight""", """itm_score.fc.bias"""] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ ,lowerCAmelCase_ ) # load state dict into HuggingFace model model.eval() if mlm_model: UpperCAmelCase_, UpperCAmelCase_= model.load_state_dict(lowerCAmelCase_ ,strict=lowerCAmelCase_ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowerCAmelCase_ ) # Define processor UpperCAmelCase_= ViltImageProcessor(size=3_84 ) UpperCAmelCase_= BertTokenizer.from_pretrained("""bert-base-uncased""" ) UpperCAmelCase_= ViltProcessor(lowerCAmelCase_ ,lowerCAmelCase_ ) # Forward pass on example inputs (image + text) if nlvr_model: UpperCAmelCase_= Image.open(requests.get("""https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg""" ,stream=lowerCAmelCase_ ).raw ) UpperCAmelCase_= Image.open(requests.get("""https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg""" ,stream=lowerCAmelCase_ ).raw ) UpperCAmelCase_= ( """The left image contains twice the number of dogs as the right image, and at least two dogs in total are""" """ standing.""" ) UpperCAmelCase_= processor(lowerCAmelCase_ ,lowerCAmelCase_ ,return_tensors="""pt""" ) UpperCAmelCase_= processor(lowerCAmelCase_ ,lowerCAmelCase_ ,return_tensors="""pt""" ) UpperCAmelCase_= model( input_ids=encoding_a.input_ids ,pixel_values=encoding_a.pixel_values ,pixel_values_a=encoding_a.pixel_values ,) else: UpperCAmelCase_= Image.open(requests.get("""http://images.cocodataset.org/val2017/000000039769.jpg""" ,stream=lowerCAmelCase_ ).raw ) if mlm_model: UpperCAmelCase_= """a bunch of [MASK] laying on a [MASK].""" else: UpperCAmelCase_= """How many cats are there?""" UpperCAmelCase_= processor(lowerCAmelCase_ ,lowerCAmelCase_ ,return_tensors="""pt""" ) UpperCAmelCase_= model(**lowerCAmelCase_ ) # Verify outputs if mlm_model: UpperCAmelCase_= torch.Size([1, 11, 3_05_22] ) UpperCAmelCase_= torch.tensor([-12.5_061, -12.5_123, -12.5_174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] ,lowerCAmelCase_ ,atol=1E-4 ) # verify masked token prediction equals "cats" UpperCAmelCase_= outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: UpperCAmelCase_= torch.Size([1, 31_29] ) UpperCAmelCase_= torch.tensor([-15.9_495, -18.1_472, -10.3_041] ) assert torch.allclose(outputs.logits[0, :3] ,lowerCAmelCase_ ,atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] ,lowerCAmelCase_ ,atol=1E-4 ) # verify vqa prediction equals "2" UpperCAmelCase_= outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: UpperCAmelCase_= torch.Size([1, 2] ) UpperCAmelCase_= torch.tensor([-2.8_721, 2.1_291] ) assert torch.allclose(outputs.logits[0, :3] ,lowerCAmelCase_ ,atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) print(F"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) __A = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
277
import warnings from functools import wraps from typing import Callable def __a ( lowerCAmelCase_ : Callable ) -> Callable: '''simple docstring''' @wraps(lowerCAmelCase_ ) def _inner_fn(*lowerCAmelCase_ : List[Any] ,**lowerCAmelCase_ : Tuple ): warnings.warn( (F"""'{fn.__name__}' is experimental and might be subject to breaking changes in the future.""") ,lowerCAmelCase_ ,) return fn(*lowerCAmelCase_ ,**lowerCAmelCase_ ) return _inner_fn
277
1
import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCamelCase__ ( A__ ) -> List[str]: snake_case__ : str = checkpoints.load_tax_checkpoint(A__ ) snake_case__ : str = flatten_dict(A__ ) return flax_params def UpperCamelCase__ ( A__ ) -> Dict: snake_case__ : Optional[int] = {} snake_case__ : 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', } snake_case__ : str = { '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 snake_case__ : Any = '.'.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): snake_case__ : Union[str, Any] = new_key.replace(A__ , A__ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): 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 snake_case__ : Optional[Any] = re.sub(r'layers_(\d+)' , r'layer.\1' , A__ ) snake_case__ : List[str] = new_key.replace('encoder' , 'encoder.encoder' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number snake_case__ : List[Any] = re.sub(r'layers_(\d+)' , r'layer.\1' , A__ ) snake_case__ : List[Any] = flax_dict[key] 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): snake_case__ : Dict = torch.from_numpy(converted_dict[key].T ) else: snake_case__ : int = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCamelCase__ ( A__ , A__ , A__=False , A__=False ) -> List[Any]: snake_case__ : Optional[Any] = get_flax_param(A__ ) if not use_large: snake_case__ : str = PixaStructVisionConfig() snake_case__ : Dict = PixaStructTextConfig() else: snake_case__ : Union[str, Any] = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) snake_case__ : List[Any] = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) snake_case__ : Optional[int] = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=A__ ) snake_case__ : Optional[Any] = PixaStructForConditionalGeneration(A__ ) snake_case__ : Optional[Any] = rename_and_convert_flax_params(A__ ) model.load_state_dict(A__ ) snake_case__ : Dict = AutoTokenizer.from_pretrained('ybelkada/test-pix2struct-tokenizer' ) snake_case__ : int = PixaStructImageProcessor() snake_case__ : Optional[Any] = PixaStructProcessor(image_processor=A__ , tokenizer=A__ ) if use_large: snake_case__ : Optional[int] = 4096 snake_case__ : Dict = 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__": lowerCAmelCase__ : str = 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.''') lowerCAmelCase__ : str = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
143
import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) 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 __snake_case ( _lowerCamelCase ,unittest.TestCase ): __lowerCamelCase = KandinskyVaaControlnetPipeline __lowerCamelCase = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowerCamelCase = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowerCamelCase = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowerCamelCase = False @property def __a ( self ) -> List[Any]: '''simple docstring''' return 32 @property def __a ( self ) -> int: '''simple docstring''' return 32 @property def __a ( self ) -> List[str]: '''simple docstring''' return self.time_input_dim @property def __a ( self ) -> Any: '''simple docstring''' return self.time_input_dim * 4 @property def __a ( self ) -> List[Any]: '''simple docstring''' return 100 @property def __a ( self ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) snake_case__ : Tuple = { 'in_channels': 8, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'image_hint', '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': 'image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } snake_case__ : Tuple = UNetaDConditionModel(**__UpperCamelCase ) return model @property def __a ( self ) -> Tuple: '''simple docstring''' return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "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", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def __a ( self ) -> int: '''simple docstring''' torch.manual_seed(0 ) snake_case__ : Tuple = VQModel(**self.dummy_movq_kwargs ) return model def __a ( self ) -> Dict: '''simple docstring''' snake_case__ : int = self.dummy_unet snake_case__ : Tuple = self.dummy_movq snake_case__ : Union[str, Any] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule='linear' , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , clip_sample=__UpperCamelCase , set_alpha_to_one=__UpperCamelCase , steps_offset=1 , prediction_type='epsilon' , thresholding=__UpperCamelCase , ) snake_case__ : str = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def __a ( self , __UpperCamelCase , __UpperCamelCase=0 ) -> int: '''simple docstring''' snake_case__ : Any = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__UpperCamelCase ) ).to(__UpperCamelCase ) snake_case__ : List[str] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( __UpperCamelCase ) # create hint snake_case__ : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(__UpperCamelCase ) ).to(__UpperCamelCase ) if str(__UpperCamelCase ).startswith('mps' ): snake_case__ : Any = torch.manual_seed(__UpperCamelCase ) else: snake_case__ : str = torch.Generator(device=__UpperCamelCase ).manual_seed(__UpperCamelCase ) snake_case__ : int = { 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'hint': hint, 'generator': generator, 'height': 64, 'width': 64, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def __a ( self ) -> List[Any]: '''simple docstring''' snake_case__ : List[Any] = 'cpu' snake_case__ : Any = self.get_dummy_components() snake_case__ : Optional[Any] = self.pipeline_class(**__UpperCamelCase ) snake_case__ : Dict = pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) snake_case__ : Optional[Any] = pipe(**self.get_dummy_inputs(__UpperCamelCase ) ) snake_case__ : Dict = output.images snake_case__ : Any = pipe( **self.get_dummy_inputs(__UpperCamelCase ) , return_dict=__UpperCamelCase , )[0] snake_case__ : Optional[int] = image[0, -3:, -3:, -1] snake_case__ : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case__ : str = np.array( [0.6_9_5_9_8_2_6, 0.8_6_8_2_7_9, 0.7_5_5_8_0_9_2, 0.6_8_7_6_9_4_6_7, 0.8_5_8_0_5_8_0_4, 0.6_5_9_7_7_4_9_6, 0.4_4_8_8_5_3_0_2, 0.5_9_5_9_1_1_1, 0.4_2_5_1_5_9_5] ) 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 __snake_case ( unittest.TestCase ): def __a ( self ) -> str: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __a ( self ) -> Optional[int]: '''simple docstring''' snake_case__ : List[Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy' ) snake_case__ : Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/hint_image_cat.png' ) snake_case__ : List[str] = torch.from_numpy(np.array(__UpperCamelCase ) ).float() / 2_5_5.0 snake_case__ : Dict = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case__ : int = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(__UpperCamelCase ) snake_case__ : int = KandinskyVaaControlnetPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-controlnet-depth' , torch_dtype=torch.floataa ) snake_case__ : List[Any] = pipeline.to(__UpperCamelCase ) pipeline.set_progress_bar_config(disable=__UpperCamelCase ) snake_case__ : Optional[int] = 'A robot, 4k photo' snake_case__ : List[Any] = torch.Generator(device='cuda' ).manual_seed(0 ) snake_case__ , snake_case__ : Tuple = pipe_prior( __UpperCamelCase , generator=__UpperCamelCase , num_inference_steps=5 , negative_prompt='' , ).to_tuple() snake_case__ : List[Any] = torch.Generator(device='cuda' ).manual_seed(0 ) snake_case__ : Dict = pipeline( image_embeds=__UpperCamelCase , negative_image_embeds=__UpperCamelCase , hint=__UpperCamelCase , generator=__UpperCamelCase , num_inference_steps=100 , output_type='np' , ) snake_case__ : Union[str, Any] = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(__UpperCamelCase , __UpperCamelCase )
143
1
"""simple docstring""" import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _A ( __lowercase ): """simple docstring""" def __snake_case ( self : Dict): a : List[str] = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(_a , "width_multiplier")) class _A : """simple docstring""" def __init__( self : str , __UpperCAmelCase : Any , __UpperCAmelCase : Tuple=13 , __UpperCAmelCase : int=64 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : List[Any]=3 , __UpperCAmelCase : int="swish" , __UpperCAmelCase : int=3 , __UpperCAmelCase : Tuple=32 , __UpperCAmelCase : List[str]=0.1 , __UpperCAmelCase : Any=0.02 , __UpperCAmelCase : Optional[Any]=True , __UpperCAmelCase : Any=True , __UpperCAmelCase : Dict=10 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : int=0.25 , __UpperCAmelCase : Optional[int]=0.0 , __UpperCAmelCase : List[Any]=0.0 , ): a : int = parent a : str = batch_size a : Dict = image_size a : str = patch_size a : Optional[Any] = num_channels a : str = make_divisible(512 * width_multiplier , divisor=8) a : Any = hidden_act a : Dict = conv_kernel_size a : List[Any] = output_stride a : Any = classifier_dropout_prob a : Optional[int] = use_labels a : List[str] = is_training a : List[Any] = num_labels a : Any = initializer_range a : Union[str, Any] = scope a : Dict = width_multiplier a : int = ffn_dropout a : int = attn_dropout def __snake_case ( self : Optional[int]): a : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) a : Union[str, Any] = None a : List[str] = None if self.use_labels: a : Union[str, Any] = ids_tensor([self.batch_size] , self.num_labels) a : Tuple = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels) a : Optional[Any] = self.get_config() return config, pixel_values, labels, pixel_labels def __snake_case ( self : Optional[int]): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def __snake_case ( self : int , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Union[str, Any]): a : str = MobileViTVaModel(config=_a) model.to(_a) model.eval() a : List[str] = model(_a) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case ( self : int , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Dict): a : Union[str, Any] = self.num_labels a : int = MobileViTVaForImageClassification(_a) model.to(_a) model.eval() a : List[Any] = model(_a , labels=_a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def __snake_case ( self : Any , __UpperCAmelCase : int , __UpperCAmelCase : Any , __UpperCAmelCase : str , __UpperCAmelCase : Dict): a : Optional[Any] = self.num_labels a : List[str] = MobileViTVaForSemanticSegmentation(_a) model.to(_a) model.eval() a : Optional[int] = model(_a) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) a : Union[str, Any] = model(_a , labels=_a) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case ( self : Optional[Any]): a : str = self.prepare_config_and_inputs() a : Dict = config_and_inputs a : Optional[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class _A ( __lowercase ,__lowercase ,unittest.TestCase ): """simple docstring""" UpperCAmelCase : List[Any] = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) UpperCAmelCase : List[str] = ( { "feature-extraction": MobileViTVaModel, "image-classification": MobileViTVaForImageClassification, "image-segmentation": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCAmelCase : int = False UpperCAmelCase : str = False UpperCAmelCase : Optional[Any] = False UpperCAmelCase : str = False def __snake_case ( self : int): a : Any = MobileViTVaModelTester(self) a : List[Any] = MobileViTVaConfigTester(self , config_class=_a , has_text_modality=_a) def __snake_case ( self : List[Any]): self.config_tester.run_common_tests() @unittest.skip(reason="MobileViTV2 does not use inputs_embeds") def __snake_case ( self : Optional[int]): pass @unittest.skip(reason="MobileViTV2 does not support input and output embeddings") def __snake_case ( self : int): pass @unittest.skip(reason="MobileViTV2 does not output attentions") def __snake_case ( self : Any): pass @require_torch_multi_gpu @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run.") def __snake_case ( self : Dict): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.") def __snake_case ( self : Optional[int]): pass def __snake_case ( self : str): a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a : Dict = model_class(_a) a : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic a : Optional[int] = [*signature.parameters.keys()] a : int = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _a) def __snake_case ( self : List[Any]): a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a) def __snake_case ( self : str): def check_hidden_states_output(__UpperCAmelCase : List[str] , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any]): a : List[Any] = model_class(_a) model.to(_a) model.eval() with torch.no_grad(): a : Tuple = model(**self._prepare_for_class(_a , _a)) a : Optional[int] = outputs.hidden_states a : List[str] = 5 self.assertEqual(len(_a) , _a) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. a : List[str] = 2 for i in range(len(_a)): self.assertListEqual( list(hidden_states[i].shape[-2:]) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2) a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a : List[str] = True check_hidden_states_output(_a , _a , _a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a : List[str] = True check_hidden_states_output(_a , _a , _a) def __snake_case ( self : str): a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a) def __snake_case ( self : Any): a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a) @slow def __snake_case ( self : Union[str, Any]): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Any = MobileViTVaModel.from_pretrained(_a) self.assertIsNotNone(_a) def lowercase ( )-> Union[str, Any]: '''simple docstring''' a : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class _A ( unittest.TestCase ): """simple docstring""" @cached_property def __snake_case ( self : Any): return ( MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256") if is_vision_available() else None ) @slow def __snake_case ( self : Dict): a : Tuple = MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256").to( _a) a : str = self.default_image_processor a : List[Any] = prepare_img() a : str = image_processor(images=_a , return_tensors="pt").to(_a) # forward pass with torch.no_grad(): a : Any = model(**_a) # verify the logits a : List[str] = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , _a) a : Dict = torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]).to(_a) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4)) @slow def __snake_case ( self : List[str]): a : int = MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3") a : List[str] = model.to(_a) a : Any = MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3") a : Any = prepare_img() a : Any = image_processor(images=_a , return_tensors="pt").to(_a) # forward pass with torch.no_grad(): a : List[Any] = model(**_a) a : Dict = outputs.logits # verify the logits a : Tuple = torch.Size((1, 21, 32, 32)) self.assertEqual(logits.shape , _a) a : Any = torch.tensor( [ [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]], [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]], [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]], ] , device=_a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1e-4)) @slow def __snake_case ( self : Any): a : Optional[int] = MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3") a : Optional[Any] = model.to(_a) a : str = MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3") a : List[str] = prepare_img() a : Dict = image_processor(images=_a , return_tensors="pt").to(_a) # forward pass with torch.no_grad(): a : int = model(**_a) a : List[Any] = outputs.logits.detach().cpu() a : List[Any] = image_processor.post_process_semantic_segmentation(outputs=_a , target_sizes=[(50, 60)]) a : Tuple = torch.Size((50, 60)) self.assertEqual(segmentation[0].shape , _a) a : Union[str, Any] = image_processor.post_process_semantic_segmentation(outputs=_a) a : Optional[int] = torch.Size((32, 32)) self.assertEqual(segmentation[0].shape , _a)
365
"""simple docstring""" from math import ceil, sqrt def lowercase ( A_ = 1_000_000 )-> int: '''simple docstring''' a : Tuple = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a : str = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: a : Tuple = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f'''{solution() = }''')
226
0
'''simple docstring''' from __future__ import annotations import time import numpy as np UpperCamelCase_ = [8, 5, 9, 7] UpperCamelCase_ = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCamelCase_ = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class a_ : def __init__( self , snake_case_ , snake_case_ , snake_case_ , ): _lowerCAmelCase : List[Any] = claim_vector _lowerCAmelCase : Tuple = allocated_resources_table _lowerCAmelCase : Dict = maximum_claim_table def __UpperCamelCase ( self ): return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def __UpperCamelCase ( self ): return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def __UpperCamelCase ( self ): return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__snake_case ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def __UpperCamelCase ( self ): return {self.__need().index(__snake_case ): i for i in self.__need()} def __UpperCamelCase ( self , **snake_case_ ): _lowerCAmelCase : Tuple = self.__need() _lowerCAmelCase : str = self.__allocated_resources_table _lowerCAmelCase : Tuple = self.__available_resources() _lowerCAmelCase : Dict = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("""_""" * 5_0 + """\n""" ) while need_list: _lowerCAmelCase : Union[str, Any] = False for each_need in need_list: _lowerCAmelCase : Dict = True for index, need in enumerate(__snake_case ): if need > available_resources[index]: _lowerCAmelCase : str = False break if execution: _lowerCAmelCase : Optional[int] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: _lowerCAmelCase : Optional[int] = original_need_index print(f'Process {process_number + 1} is executing.' ) # remove the process run from stack need_list.remove(__snake_case ) # update available/freed resources stack _lowerCAmelCase : Any = np.array(__snake_case ) + np.array( alloc_resources_table[process_number] ) print( """Updated available resource stack for processes: """ + """ """.join([str(__snake_case ) for x in available_resources] ) ) break if safe: print("""The process is in a safe state.\n""" ) else: print("""System in unsafe state. Aborting...\n""" ) break def __UpperCamelCase ( self ): print(""" """ * 9 + """Allocated Resource Table""" ) for item in self.__allocated_resources_table: print( f'P{self.__allocated_resources_table.index(__snake_case ) + 1}' + """ """.join(f'{it:>8}' for it in item ) + """\n""" ) print(""" """ * 9 + """System Resource Table""" ) for item in self.__maximum_claim_table: print( f'P{self.__maximum_claim_table.index(__snake_case ) + 1}' + """ """.join(f'{it:>8}' for it in item ) + """\n""" ) print( """Current Usage by Active Processes: """ + """ """.join(str(__snake_case ) for x in self.__claim_vector ) ) print( """Initial Available Resources: """ + """ """.join(str(__snake_case ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
309
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : Optional[int] = logging.get_logger(__name__) _lowerCAmelCase : List[str] = { "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json", } class __magic_name__ ( lowerCAmelCase_ ): SCREAMING_SNAKE_CASE = 'git_vision_model' def __init__( self , __snake_case=768 , __snake_case=3072 , __snake_case=12 , __snake_case=12 , __snake_case=3 , __snake_case=224 , __snake_case=16 , __snake_case="quick_gelu" , __snake_case=1e-5 , __snake_case=0.0 , __snake_case=0.02 , **__snake_case , ) -> int: '''simple docstring''' super().__init__(**__snake_case ) __a =hidden_size __a =intermediate_size __a =num_hidden_layers __a =num_attention_heads __a =num_channels __a =patch_size __a =image_size __a =initializer_range __a =attention_dropout __a =layer_norm_eps __a =hidden_act @classmethod def __magic_name__ ( cls , __snake_case , **__snake_case ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__snake_case ) __a , __a =cls.get_config_dict(__snake_case , **__snake_case ) # get the vision config dict if we are loading from GITConfig if config_dict.get('model_type' ) == "git": __a =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(__snake_case , **__snake_case ) class __magic_name__ ( lowerCAmelCase_ ): SCREAMING_SNAKE_CASE = 'git' def __init__( self , __snake_case=None , __snake_case=3_0522 , __snake_case=768 , __snake_case=6 , __snake_case=12 , __snake_case=3072 , __snake_case="gelu" , __snake_case=0.1 , __snake_case=0.1 , __snake_case=1024 , __snake_case=0.02 , __snake_case=1e-12 , __snake_case=0 , __snake_case="absolute" , __snake_case=True , __snake_case=False , __snake_case=101 , __snake_case=102 , __snake_case=None , **__snake_case , ) -> Optional[int]: '''simple docstring''' super().__init__(bos_token_id=__snake_case , eos_token_id=__snake_case , pad_token_id=__snake_case , **__snake_case ) if vision_config is None: __a ={} logger.info('vision_config is None. initializing the GitVisionConfig with default values.' ) __a =GitVisionConfig(**__snake_case ) __a =vocab_size __a =hidden_size __a =num_hidden_layers __a =num_attention_heads __a =hidden_act __a =intermediate_size __a =hidden_dropout_prob __a =attention_probs_dropout_prob __a =max_position_embeddings __a =initializer_range __a =layer_norm_eps __a =position_embedding_type __a =use_cache __a =tie_word_embeddings __a =num_image_with_embedding __a =bos_token_id __a =eos_token_id def __magic_name__ ( self ) -> Optional[Any]: '''simple docstring''' __a =copy.deepcopy(self.__dict__ ) __a =self.vision_config.to_dict() __a =self.__class__.model_type return output
218
0
"""simple docstring""" import argparse import os import re _lowerCAmelCase : int = '''src/diffusers''' # Pattern that looks at the indentation in a line. _lowerCAmelCase : Optional[int] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. _lowerCAmelCase : Any = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. _lowerCAmelCase : str = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. _lowerCAmelCase : str = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. _lowerCAmelCase : Dict = re.compile(R'''\[([^\]]+)\]''') def lowerCamelCase_( _lowerCamelCase ) -> str: '''simple docstring''' _lowerCamelCase : Tuple = _re_indent.search(_lowerCamelCase ) return "" if search is None else search.groups()[0] def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase="" , _lowerCamelCase=None , _lowerCamelCase=None ) -> Optional[int]: '''simple docstring''' _lowerCamelCase : Tuple = 0 _lowerCamelCase : List[Any] = code.split("\n" ) if start_prompt is not None: while not lines[index].startswith(_lowerCamelCase ): index += 1 _lowerCamelCase : Union[str, Any] = ["\n".join(lines[:index] )] else: _lowerCamelCase : Optional[Any] = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). _lowerCamelCase : int = [lines[index]] index += 1 while index < len(_lowerCamelCase ) and (end_prompt is None or not lines[index].startswith(_lowerCamelCase )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_lowerCamelCase ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + " " ): current_block.append(lines[index] ) blocks.append("\n".join(_lowerCamelCase ) ) if index < len(_lowerCamelCase ) - 1: _lowerCamelCase : str = [lines[index + 1]] index += 1 else: _lowerCamelCase : Dict = [] else: blocks.append("\n".join(_lowerCamelCase ) ) _lowerCamelCase : Tuple = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_lowerCamelCase ) > 0: blocks.append("\n".join(_lowerCamelCase ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_lowerCamelCase ): blocks.append("\n".join(lines[index:] ) ) return blocks def lowerCamelCase_( _lowerCamelCase ) -> Dict: '''simple docstring''' def _inner(_lowerCamelCase ): return key(_lowerCamelCase ).lower().replace("_" , "" ) return _inner def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase=None ) -> List[str]: '''simple docstring''' def noop(_lowerCamelCase ): return x if key is None: _lowerCamelCase : Tuple = noop # Constants are all uppercase, they go first. _lowerCamelCase : Union[str, Any] = [obj for obj in objects if key(_lowerCamelCase ).isupper()] # Classes are not all uppercase but start with a capital, they go second. _lowerCamelCase : Optional[int] = [obj for obj in objects if key(_lowerCamelCase )[0].isupper() and not key(_lowerCamelCase ).isupper()] # Functions begin with a lowercase, they go last. _lowerCamelCase : Any = [obj for obj in objects if not key(_lowerCamelCase )[0].isupper()] _lowerCamelCase : Tuple = ignore_underscore(_lowerCamelCase ) return sorted(_lowerCamelCase , key=_lowerCamelCase ) + sorted(_lowerCamelCase , key=_lowerCamelCase ) + sorted(_lowerCamelCase , key=_lowerCamelCase ) def lowerCamelCase_( _lowerCamelCase ) -> str: '''simple docstring''' def _replace(_lowerCamelCase ): _lowerCamelCase : Any = match.groups()[0] if "," not in imports: return F"""[{imports}]""" _lowerCamelCase : Optional[Any] = [part.strip().replace("\"" , "" ) for part in imports.split("," )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: _lowerCamelCase : List[str] = keys[:-1] return "[" + ", ".join([F"""\"{k}\"""" for k in sort_objects(_lowerCamelCase )] ) + "]" _lowerCamelCase : int = import_statement.split("\n" ) if len(_lowerCamelCase ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. _lowerCamelCase : int = 2 if lines[1].strip() == "[" else 1 _lowerCamelCase : Any = [(i, _re_strip_line.search(_lowerCamelCase ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] _lowerCamelCase : Union[str, Any] = sort_objects(_lowerCamelCase , key=lambda _lowerCamelCase : x[1] ) _lowerCamelCase : Dict = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_lowerCamelCase ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: _lowerCamelCase : List[str] = _re_bracket_content.sub(_replace , lines[1] ) else: _lowerCamelCase : Optional[Any] = [part.strip().replace("\"" , "" ) for part in lines[1].split("," )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: _lowerCamelCase : Optional[Any] = keys[:-1] _lowerCamelCase : Optional[Any] = get_indent(lines[1] ) + ", ".join([F"""\"{k}\"""" for k in sort_objects(_lowerCamelCase )] ) return "\n".join(_lowerCamelCase ) else: # Finally we have to deal with imports fitting on one line _lowerCamelCase : Any = _re_bracket_content.sub(_replace , _lowerCamelCase ) return import_statement def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase=True ) -> int: '''simple docstring''' with open(_lowerCamelCase , "r" ) as f: _lowerCamelCase : int = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 _lowerCamelCase : Optional[Any] = split_code_in_indented_blocks( _lowerCamelCase , start_prompt="_import_structure = {" , end_prompt="if TYPE_CHECKING:" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_lowerCamelCase ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. _lowerCamelCase : str = main_blocks[block_idx] _lowerCamelCase : Optional[Any] = block.split("\n" ) # Get to the start of the imports. _lowerCamelCase : Any = 0 while line_idx < len(_lowerCamelCase ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: _lowerCamelCase : Dict = len(_lowerCamelCase ) else: line_idx += 1 if line_idx >= len(_lowerCamelCase ): continue # Ignore beginning and last line: they don't contain anything. _lowerCamelCase : Optional[Any] = "\n".join(block_lines[line_idx:-1] ) _lowerCamelCase : str = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. _lowerCamelCase : Union[str, Any] = split_code_in_indented_blocks(_lowerCamelCase , indent_level=_lowerCamelCase ) # We have two categories of import key: list or _import_structure[key].append/extend _lowerCamelCase : Optional[Any] = _re_direct_key if "_import_structure" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. _lowerCamelCase : Dict = [(pattern.search(_lowerCamelCase ).groups()[0] if pattern.search(_lowerCamelCase ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. _lowerCamelCase : Any = [(i, key) for i, key in enumerate(_lowerCamelCase ) if key is not None] _lowerCamelCase : Tuple = [x[0] for x in sorted(_lowerCamelCase , key=lambda _lowerCamelCase : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. _lowerCamelCase : Any = 0 _lowerCamelCase : str = [] for i in range(len(_lowerCamelCase ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: _lowerCamelCase : Optional[int] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(_lowerCamelCase ) count += 1 # And we put our main block back together with its first and last line. _lowerCamelCase : str = "\n".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(_lowerCamelCase ): if check_only: return True else: print(F"""Overwriting {file}.""" ) with open(_lowerCamelCase , "w" ) as f: f.write("\n".join(_lowerCamelCase ) ) def lowerCamelCase_( _lowerCamelCase=True ) -> Union[str, Any]: '''simple docstring''' _lowerCamelCase : int = [] for root, _, files in os.walk(_lowerCamelCase ): if "__init__.py" in files: _lowerCamelCase : Tuple = sort_imports(os.path.join(_lowerCamelCase , "__init__.py" ) , check_only=_lowerCamelCase ) if result: _lowerCamelCase : int = [os.path.join(_lowerCamelCase , "__init__.py" )] if len(_lowerCamelCase ) > 0: raise ValueError(F"""Would overwrite {len(_lowerCamelCase )} files, run `make style`.""" ) if __name__ == "__main__": _lowerCAmelCase : int = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') _lowerCAmelCase : Dict = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
340
"""simple docstring""" 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 _lowerCAmelCase : str = '''0.12''' # assumed parallelism: 8 if is_torch_available(): import torch def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None ) -> List[Any]: '''simple docstring''' if rng is None: _lowerCamelCase : Union[str, Any] = random.Random() _lowerCamelCase : Union[str, Any] = 1 for dim in shape: total_dims *= dim _lowerCamelCase : Optional[int] = [] for _ in range(_lowerCamelCase ): values.append(rng.randint(0 , vocab_size - 1 ) ) _lowerCamelCase : Union[str, Any] = np.array(_lowerCamelCase , dtype=jnp.intaa ).reshape(_lowerCamelCase ) return output def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase=None ) -> Union[str, Any]: '''simple docstring''' _lowerCamelCase : Optional[int] = ids_tensor(_lowerCamelCase , vocab_size=2 , rng=_lowerCamelCase ) # make sure that at least one token is attended to for each batch _lowerCamelCase : List[str] = 1 return attn_mask @require_flax class A_ : lowerCAmelCase__ = None lowerCAmelCase__ = () def _lowercase ( self: Any ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 _lowerCamelCase : List[str] = 2 _lowerCamelCase : str = inputs["input_ids"].shape[-1] // 2 _lowerCamelCase : Tuple = inputs["input_ids"][:max_batch_size, :sequence_length] _lowerCamelCase : Any = jnp.ones_like(__lowerCAmelCase ) _lowerCamelCase : List[Any] = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens _lowerCamelCase : Optional[Any] = 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()` _lowerCamelCase : List[str] = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def _lowercase ( self: Tuple ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Tuple = self._get_input_ids_and_config() _lowerCamelCase : List[Any] = False _lowerCamelCase : Dict = max_length _lowerCamelCase : Tuple = 0 for model_class in self.all_generative_model_classes: _lowerCamelCase : str = model_class(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = model_class.__name__[4:] # Skip the "Flax" at the beginning _lowerCamelCase : Any = getattr(__lowerCAmelCase ,__lowerCAmelCase ) _lowerCamelCase : Dict = pt_model_class(__lowerCAmelCase ).eval() _lowerCamelCase : Optional[Any] = load_flax_weights_in_pytorch_model(__lowerCAmelCase ,flax_model.params ) _lowerCamelCase : int = flax_model.generate(__lowerCAmelCase ).sequences _lowerCamelCase : Optional[int] = pt_model.generate(torch.tensor(__lowerCAmelCase ,dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: _lowerCamelCase : List[Any] = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() ,flax_generation_outputs.tolist() ) def _lowercase ( self: Optional[Any] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Optional[int] = self._get_input_ids_and_config() _lowerCamelCase : Union[str, Any] = False _lowerCamelCase : Union[str, Any] = max_length for model_class in self.all_generative_model_classes: _lowerCamelCase : Optional[int] = model_class(__lowerCAmelCase ) _lowerCamelCase : Tuple = model.generate(__lowerCAmelCase ).sequences self.assertEqual(generation_outputs.shape[-1] ,__lowerCAmelCase ) _lowerCamelCase : Dict = jit(model.generate ) _lowerCamelCase : List[str] = jit_generate(__lowerCAmelCase ).sequences self.assertListEqual(generation_outputs.tolist() ,jit_generation_outputs.tolist() ) def _lowercase ( self: Tuple ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Optional[Any] = self._get_input_ids_and_config() _lowerCamelCase : List[Any] = True _lowerCamelCase : Optional[int] = max_length for model_class in self.all_generative_model_classes: _lowerCamelCase : Union[str, Any] = model_class(__lowerCAmelCase ) _lowerCamelCase : List[Any] = model.generate(__lowerCAmelCase ).sequences self.assertEqual(generation_outputs.shape[-1] ,__lowerCAmelCase ) _lowerCamelCase : Dict = jit(model.generate ) _lowerCamelCase : int = jit_generate(__lowerCAmelCase ).sequences self.assertListEqual(generation_outputs.tolist() ,jit_generation_outputs.tolist() ) def _lowercase ( self: Union[str, Any] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Optional[Any] = self._get_input_ids_and_config() _lowerCamelCase : int = False _lowerCamelCase : Optional[Any] = max_length _lowerCamelCase : Dict = 2 for model_class in self.all_generative_model_classes: _lowerCamelCase : List[str] = model_class(__lowerCAmelCase ) _lowerCamelCase : Dict = model.generate(__lowerCAmelCase ).sequences self.assertEqual(generation_outputs.shape[-1] ,__lowerCAmelCase ) _lowerCamelCase : Tuple = jit(model.generate ) _lowerCamelCase : List[str] = jit_generate(__lowerCAmelCase ).sequences self.assertListEqual(generation_outputs.tolist() ,jit_generation_outputs.tolist() ) def _lowercase ( self: List[Any] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Dict = self._get_input_ids_and_config() _lowerCamelCase : Tuple = False _lowerCamelCase : Union[str, Any] = max_length _lowerCamelCase : List[str] = 2 _lowerCamelCase : Optional[int] = 2 for model_class in self.all_generative_model_classes: _lowerCamelCase : List[Any] = model_class(__lowerCAmelCase ) _lowerCamelCase : str = model.generate(__lowerCAmelCase ).sequences self.assertEqual(generation_outputs.shape[0] ,input_ids.shape[0] * config.num_return_sequences ) def _lowercase ( self: List[Any] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : int = self._get_input_ids_and_config() _lowerCamelCase : int = True _lowerCamelCase : List[Any] = max_length _lowerCamelCase : Optional[Any] = 0.8 _lowerCamelCase : Union[str, Any] = 10 _lowerCamelCase : List[str] = 0.3 _lowerCamelCase : Tuple = 1 _lowerCamelCase : Any = 8 _lowerCamelCase : str = 9 for model_class in self.all_generative_model_classes: _lowerCamelCase : Optional[int] = model_class(__lowerCAmelCase ) _lowerCamelCase : Any = model.generate(__lowerCAmelCase ).sequences self.assertEqual(generation_outputs.shape[-1] ,__lowerCAmelCase ) _lowerCamelCase : int = jit(model.generate ) _lowerCamelCase : Optional[int] = jit_generate(__lowerCAmelCase ).sequences self.assertListEqual(generation_outputs.tolist() ,jit_generation_outputs.tolist() ) def _lowercase ( self: Optional[int] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : List[Any] = self._get_input_ids_and_config() _lowerCamelCase : List[str] = max_length _lowerCamelCase : Tuple = 1 _lowerCamelCase : Any = 8 _lowerCamelCase : Dict = 9 for model_class in self.all_generative_model_classes: _lowerCamelCase : Any = model_class(__lowerCAmelCase ) _lowerCamelCase : Tuple = model.generate(__lowerCAmelCase ).sequences self.assertEqual(generation_outputs.shape[-1] ,__lowerCAmelCase ) _lowerCamelCase : Any = jit(model.generate ) _lowerCamelCase : Any = jit_generate(__lowerCAmelCase ).sequences self.assertListEqual(generation_outputs.tolist() ,jit_generation_outputs.tolist() ) def _lowercase ( self: List[str] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : List[str] = self._get_input_ids_and_config() _lowerCamelCase : Dict = max_length _lowerCamelCase : List[Any] = 2 _lowerCamelCase : Tuple = 1 _lowerCamelCase : List[str] = 8 _lowerCamelCase : List[Any] = 9 for model_class in self.all_generative_model_classes: _lowerCamelCase : int = model_class(__lowerCAmelCase ) _lowerCamelCase : Optional[int] = model.generate(__lowerCAmelCase ).sequences self.assertEqual(generation_outputs.shape[-1] ,__lowerCAmelCase ) _lowerCamelCase : Tuple = jit(model.generate ) _lowerCamelCase : Optional[Any] = jit_generate(__lowerCAmelCase ).sequences self.assertListEqual(generation_outputs.tolist() ,jit_generation_outputs.tolist() ) def _lowercase ( self: Dict ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : List[str] = self._get_input_ids_and_config() # pad attention mask on the left _lowerCamelCase : Tuple = attention_mask.at[(0, 0)].set(0 ) _lowerCamelCase : Dict = False _lowerCamelCase : Any = max_length for model_class in self.all_generative_model_classes: _lowerCamelCase : List[Any] = model_class(__lowerCAmelCase ) _lowerCamelCase : Tuple = model.generate(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ).sequences self.assertEqual(generation_outputs.shape[-1] ,__lowerCAmelCase ) _lowerCamelCase : Any = jit(model.generate ) _lowerCamelCase : List[str] = jit_generate(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ).sequences self.assertListEqual(generation_outputs.tolist() ,jit_generation_outputs.tolist() ) def _lowercase ( self: Optional[Any] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Any = self._get_input_ids_and_config() # pad attention mask on the left _lowerCamelCase : Optional[Any] = attention_mask.at[(0, 0)].set(0 ) _lowerCamelCase : List[str] = True _lowerCamelCase : Optional[Any] = max_length for model_class in self.all_generative_model_classes: _lowerCamelCase : Union[str, Any] = model_class(__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = model.generate(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ).sequences self.assertEqual(generation_outputs.shape[-1] ,__lowerCAmelCase ) _lowerCamelCase : Any = jit(model.generate ) _lowerCamelCase : List[Any] = jit_generate(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ).sequences self.assertListEqual(generation_outputs.tolist() ,jit_generation_outputs.tolist() ) def _lowercase ( self: Union[str, Any] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : int = self._get_input_ids_and_config() # pad attention mask on the left _lowerCamelCase : List[str] = attention_mask.at[(0, 0)].set(0 ) _lowerCamelCase : int = 2 _lowerCamelCase : int = max_length for model_class in self.all_generative_model_classes: _lowerCamelCase : List[Any] = model_class(__lowerCAmelCase ) _lowerCamelCase : int = model.generate(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ).sequences self.assertEqual(generation_outputs.shape[-1] ,__lowerCAmelCase ) _lowerCamelCase : Dict = jit(model.generate ) _lowerCamelCase : Dict = jit_generate(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ).sequences self.assertListEqual(generation_outputs.tolist() ,jit_generation_outputs.tolist() ) @require_flax class A_ ( unittest.TestCase ): def _lowercase ( self: Any ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-bert" ) _lowerCamelCase : Union[str, Any] = FlaxAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) _lowerCamelCase : Optional[Any] = "Hello world" _lowerCamelCase : str = tokenizer(__lowerCAmelCase ,return_tensors="np" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(__lowerCAmelCase ,"do_samples" ): model.generate(__lowerCAmelCase ,do_samples=__lowerCAmelCase ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(__lowerCAmelCase ,"foo" ): _lowerCamelCase : List[str] = {"foo": "bar"} model.generate(__lowerCAmelCase ,**__lowerCAmelCase )
340
1
'''simple docstring''' import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class _snake_case : def __init__( self , a__ , a__=13 , a__=7 , a__=True , a__=True , a__=True , a__=True , a__=99 , a__=64 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=16 , a__=2 , a__=0.0_2 , a__=3 , a__=4 , a__=None , ) -> List[Any]: '''simple docstring''' snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = num_choices snake_case_ = scope snake_case_ = vocab_size - 1 def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, input_mask, token_labels def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' return GPTNeoXConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a__ , initializer_range=self.initializer_range , pad_token_id=self.pad_token_id , ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.prepare_config_and_inputs() snake_case_ = True return config, input_ids, input_mask, token_labels def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> str: '''simple docstring''' snake_case_ = GPTNeoXModel(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ ) snake_case_ = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> List[str]: '''simple docstring''' snake_case_ = True snake_case_ = GPTNeoXModel(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> int: '''simple docstring''' snake_case_ = GPTNeoXForCausalLM(config=a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> List[str]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = GPTNeoXForQuestionAnswering(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> Dict: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = GPTNeoXForSequenceClassification(a__ ) model.to(a__ ) model.eval() snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = model(a__ , attention_mask=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = self.num_labels snake_case_ = GPTNeoXForTokenClassification(a__ ) model.to(a__ ) model.eval() snake_case_ = model(a__ , attention_mask=a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> List[Any]: '''simple docstring''' snake_case_ = True snake_case_ = GPTNeoXForCausalLM(config=a__ ) model.to(a__ ) model.eval() # first forward pass snake_case_ = model(a__ , attention_mask=a__ , use_cache=a__ ) snake_case_ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids snake_case_ = ids_tensor((self.batch_size, 3) , config.vocab_size ) snake_case_ = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and snake_case_ = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case_ = torch.cat([input_mask, next_mask] , dim=-1 ) snake_case_ = model(a__ , attention_mask=a__ , output_hidden_states=a__ ) snake_case_ = output_from_no_past["hidden_states"][0] snake_case_ = model( a__ , attention_mask=a__ , past_key_values=a__ , output_hidden_states=a__ , )["hidden_states"][0] # select random slice snake_case_ = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case_ = output_from_no_past[:, -3:, random_slice_idx].detach() snake_case_ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a__ , a__ , atol=1e-3 ) ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _snake_case ( lowercase_ , lowercase_ , lowercase_ , unittest.TestCase ): lowerCAmelCase_ : List[Any] = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) lowerCAmelCase_ : List[Any] = (GPTNeoXForCausalLM,) if is_torch_available() else () lowerCAmelCase_ : str = ( { "feature-extraction": GPTNeoXModel, "question-answering": GPTNeoXForQuestionAnswering, "text-classification": GPTNeoXForSequenceClassification, "text-generation": GPTNeoXForCausalLM, "token-classification": GPTNeoXForTokenClassification, "zero-shot": GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase_ : str = False lowerCAmelCase_ : Optional[Any] = False lowerCAmelCase_ : List[str] = False lowerCAmelCase_ : Dict = False def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = GPTNeoXModelTester(self ) snake_case_ = ConfigTester(self , config_class=a__ , hidden_size=64 , num_attention_heads=8 ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a__ , a__ , a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(a__ , a__ , a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_decoder() snake_case_ = None self.model_tester.create_and_check_model_as_decoder(a__ , a__ , a__ ) def lowerCAmelCase__ ( self ) -> Tuple: '''simple docstring''' snake_case_ , snake_case_ , snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(a__ , a__ , a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*a__ ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a__ ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a__ ) @unittest.skip(reason="Feed forward chunking is not implemented" ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' pass @parameterized.expand([("linear",), ("dynamic",)] ) def lowerCAmelCase__ ( self , a__ ) -> Optional[Any]: '''simple docstring''' snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = ids_tensor([1, 10] , config.vocab_size ) snake_case_ = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights snake_case_ = GPTNeoXModel(a__ ) original_model.to(a__ ) original_model.eval() snake_case_ = original_model(a__ ).last_hidden_state snake_case_ = original_model(a__ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights snake_case_ = {"type": scaling_type, "factor": 1_0.0} snake_case_ = GPTNeoXModel(a__ ) scaled_model.to(a__ ) scaled_model.eval() snake_case_ = scaled_model(a__ ).last_hidden_state snake_case_ = scaled_model(a__ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a__ , a__ , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(a__ , a__ , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(a__ , a__ , atol=1e-5 ) ) @require_torch class _snake_case ( unittest.TestCase ): @slow def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' snake_case_ = AutoTokenizer.from_pretrained("EleutherAI/pythia-410m-deduped" ) for checkpointing in [True, False]: snake_case_ = GPTNeoXForCausalLM.from_pretrained("EleutherAI/pythia-410m-deduped" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(a__ ) snake_case_ = tokenizer("My favorite food is" , return_tensors="pt" ).to(a__ ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 snake_case_ = "My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure" snake_case_ = model.generate(**a__ , do_sample=a__ , max_new_tokens=20 ) snake_case_ = tokenizer.batch_decode(a__ )[0] self.assertEqual(a__ , a__ )
85
'''simple docstring''' import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def UpperCamelCase_( snake_case : Tuple ): '''simple docstring''' snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = FileLock(str(tmpdir / "foo.lock" ) ) snake_case_ = 0.01 with locka.acquire(): with pytest.raises(snake_case ): snake_case_ = time.time() locka.acquire(snake_case ) assert time.time() - _start > timeout def UpperCamelCase_( snake_case : str ): '''simple docstring''' snake_case_ = "a" * 1_0_0_0 + ".lock" snake_case_ = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith(".lock" ) assert not locka._lock_file.endswith(snake_case ) assert len(os.path.basename(locka._lock_file ) ) <= 2_5_5 snake_case_ = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(snake_case ): locka.acquire(0 )
85
1
def _SCREAMING_SNAKE_CASE ( lowercase : Any ): '''simple docstring''' assert isinstance(__lowerCamelCase , __lowerCamelCase ), f"""The input value of [n={number}] is not an integer""" if number == 1: return 2 elif number < 1: lowerCamelCase_ = f"""The input value of [n={number}] has to be > 0""" raise ValueError(__lowerCamelCase ) else: lowerCamelCase_ = sylvester(number - 1 ) lowerCamelCase_ = num - 1 lowerCamelCase_ = num return lower * upper + 1 if __name__ == "__main__": print(F"""The 8th number in Sylvester's sequence: {sylvester(8)}""")
351
import os import time import numpy as np import onnxruntime as ort lowerCamelCase : int = "1" lowerCamelCase : int = "0" lowerCamelCase : Union[str, Any] = "1" lowerCamelCase : List[Any] = ort.SessionOptions() lowerCamelCase : Optional[Any] = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print("Create inference session...") lowerCamelCase : Union[str, Any] = ["TensorrtExecutionProvider", "CUDAExecutionProvider"] lowerCamelCase : Tuple = ort.InferenceSession("model.onnx", sess_options=sess_opt, providers=execution_provider) lowerCamelCase : List[Any] = ort.RunOptions() lowerCamelCase : List[str] = 128 lowerCamelCase : List[Any] = 1 lowerCamelCase : Union[str, Any] = np.ones((batch, sequence), dtype=np.intaa) lowerCamelCase : Dict = np.ones((batch, sequence), dtype=np.intaa) lowerCamelCase : Optional[Any] = np.ones((batch, sequence), dtype=np.intaa) print("Warm up phase...") sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print("Start inference...") lowerCamelCase : int = time.time() lowerCamelCase : Dict = 2_000 lowerCamelCase : Any = {} for iter in range(max_iters): lowerCamelCase : Union[str, Any] = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print("Average Inference Time = {:.3f} ms".format((time.time() - start_time) * 1_000 / max_iters))
208
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu 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 enable_full_determinism() class A_ ( a__ , a__ , a__ , unittest.TestCase ): _UpperCAmelCase : Optional[int] = AltDiffusionPipeline _UpperCAmelCase : Optional[Any] = TEXT_TO_IMAGE_PARAMS _UpperCAmelCase : Optional[Any] = TEXT_TO_IMAGE_BATCH_PARAMS _UpperCAmelCase : List[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS _UpperCAmelCase : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCAmelCase ( self : Optional[Any]): torch.manual_seed(0) __lowerCamelCase : Union[str, Any] = UNetaDConditionModel( block_out_channels=(3_2, 6_4) ,layers_per_block=2 ,sample_size=3_2 ,in_channels=4 ,out_channels=4 ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,cross_attention_dim=3_2 ,) __lowerCamelCase : Any = DDIMScheduler( beta_start=0.00085 ,beta_end=0.012 ,beta_schedule='scaled_linear' ,clip_sample=SCREAMING_SNAKE_CASE_ ,set_alpha_to_one=SCREAMING_SNAKE_CASE_ ,) torch.manual_seed(0) __lowerCamelCase : Tuple = AutoencoderKL( block_out_channels=[3_2, 6_4] ,in_channels=3 ,out_channels=3 ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,latent_channels=4 ,) # TODO: address the non-deterministic text encoder (fails for save-load tests) # torch.manual_seed(0) # text_encoder_config = RobertaSeriesConfig( # hidden_size=32, # project_dim=32, # intermediate_size=37, # layer_norm_eps=1e-05, # num_attention_heads=4, # num_hidden_layers=5, # vocab_size=5002, # ) # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config) torch.manual_seed(0) __lowerCamelCase : List[str] = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=3_2 ,projection_dim=3_2 ,intermediate_size=3_7 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=5_0_0_2 ,) __lowerCamelCase : str = CLIPTextModel(SCREAMING_SNAKE_CASE_) __lowerCamelCase : List[Any] = XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta') __lowerCamelCase : Union[str, Any] = 7_7 __lowerCamelCase : Dict = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : List[str]=0): if str(SCREAMING_SNAKE_CASE_).startswith('mps'): __lowerCamelCase : Union[str, Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_) else: __lowerCamelCase : List[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE_).manual_seed(SCREAMING_SNAKE_CASE_) __lowerCamelCase : Union[str, Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def lowerCAmelCase ( self : List[Any]): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3) def lowerCAmelCase ( self : List[Any]): super().test_inference_batch_single_identical(expected_max_diff=3E-3) def lowerCAmelCase ( self : List[str]): __lowerCamelCase : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[str] = self.get_dummy_components() torch.manual_seed(0) __lowerCamelCase : Optional[Any] = RobertaSeriesConfig( hidden_size=3_2 ,project_dim=3_2 ,intermediate_size=3_7 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,vocab_size=5_0_0_2 ,) # TODO: remove after fixing the non-deterministic text encoder __lowerCamelCase : Tuple = RobertaSeriesModelWithTransformation(SCREAMING_SNAKE_CASE_) __lowerCamelCase : Any = text_encoder __lowerCamelCase : Tuple = AltDiffusionPipeline(**SCREAMING_SNAKE_CASE_) __lowerCamelCase : Union[str, Any] = alt_pipe.to(SCREAMING_SNAKE_CASE_) alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_) __lowerCamelCase : List[Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_) __lowerCamelCase : Optional[Any] = 'A photo of an astronaut' __lowerCamelCase : int = alt_pipe(**SCREAMING_SNAKE_CASE_) __lowerCamelCase : int = output.images __lowerCamelCase : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCamelCase : int = np.array( [0.5748162, 0.60447145, 0.48821217, 0.50100636, 0.5431185, 0.45763683, 0.49657696, 0.48132733, 0.47573093]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_) torch.manual_seed(0) __lowerCamelCase : Optional[int] = RobertaSeriesConfig( hidden_size=3_2 ,project_dim=3_2 ,intermediate_size=3_7 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,vocab_size=5_0_0_2 ,) # TODO: remove after fixing the non-deterministic text encoder __lowerCamelCase : Any = RobertaSeriesModelWithTransformation(SCREAMING_SNAKE_CASE_) __lowerCamelCase : Union[str, Any] = text_encoder __lowerCamelCase : str = AltDiffusionPipeline(**SCREAMING_SNAKE_CASE_) __lowerCamelCase : str = alt_pipe.to(SCREAMING_SNAKE_CASE_) alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_) __lowerCamelCase : Optional[int] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_) __lowerCamelCase : List[str] = alt_pipe(**SCREAMING_SNAKE_CASE_) __lowerCamelCase : Tuple = output.images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCamelCase : Optional[int] = np.array( [0.51605093, 0.5707241, 0.47365507, 0.50578886, 0.5633877, 0.4642503, 0.5182081, 0.48763484, 0.49084237]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 @slow @require_torch_gpu class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Optional[Any]): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : Union[str, Any]): # make sure here that pndm scheduler skips prk __lowerCamelCase : List[str] = AltDiffusionPipeline.from_pretrained('BAAI/AltDiffusion' ,safety_checker=SCREAMING_SNAKE_CASE_) __lowerCamelCase : List[Any] = alt_pipe.to(SCREAMING_SNAKE_CASE_) alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_) __lowerCamelCase : Tuple = 'A painting of a squirrel eating a burger' __lowerCamelCase : Any = torch.manual_seed(0) __lowerCamelCase : Optional[int] = alt_pipe([prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=6.0 ,num_inference_steps=2_0 ,output_type='np') __lowerCamelCase : str = output.images __lowerCamelCase : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : Union[str, Any] = np.array([0.1010, 0.0800, 0.0794, 0.0885, 0.0843, 0.0762, 0.0769, 0.0729, 0.0586]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def lowerCAmelCase ( self : Any): __lowerCamelCase : List[str] = DDIMScheduler.from_pretrained('BAAI/AltDiffusion' ,subfolder='scheduler') __lowerCamelCase : Tuple = AltDiffusionPipeline.from_pretrained('BAAI/AltDiffusion' ,scheduler=SCREAMING_SNAKE_CASE_ ,safety_checker=SCREAMING_SNAKE_CASE_) __lowerCamelCase : int = alt_pipe.to(SCREAMING_SNAKE_CASE_) alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_) __lowerCamelCase : Tuple = 'A painting of a squirrel eating a burger' __lowerCamelCase : int = torch.manual_seed(0) __lowerCamelCase : Optional[Any] = alt_pipe([prompt] ,generator=SCREAMING_SNAKE_CASE_ ,num_inference_steps=2 ,output_type='numpy') __lowerCamelCase : Optional[int] = output.images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCamelCase : Any = np.array([0.4019, 0.4052, 0.3810, 0.4119, 0.3916, 0.3982, 0.4651, 0.4195, 0.5323]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
73
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { '''google/canine-s''': '''https://huggingface.co/google/canine-s/resolve/main/config.json''', # See all CANINE models at https://huggingface.co/models?filter=canine } class lowerCAmelCase_ ( a__ ): UpperCAmelCase__ : Any = "canine" def __init__( self, SCREAMING_SNAKE_CASE_=768, SCREAMING_SNAKE_CASE_=12, SCREAMING_SNAKE_CASE_=12, SCREAMING_SNAKE_CASE_=3072, SCREAMING_SNAKE_CASE_="gelu", SCREAMING_SNAKE_CASE_=0.1, SCREAMING_SNAKE_CASE_=0.1, SCREAMING_SNAKE_CASE_=1_6384, SCREAMING_SNAKE_CASE_=16, SCREAMING_SNAKE_CASE_=0.02, SCREAMING_SNAKE_CASE_=1e-12, SCREAMING_SNAKE_CASE_=0, SCREAMING_SNAKE_CASE_=0XE000, SCREAMING_SNAKE_CASE_=0XE001, SCREAMING_SNAKE_CASE_=4, SCREAMING_SNAKE_CASE_=4, SCREAMING_SNAKE_CASE_=8, SCREAMING_SNAKE_CASE_=1_6384, SCREAMING_SNAKE_CASE_=128, **SCREAMING_SNAKE_CASE_, ) -> int: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_, bos_token_id=SCREAMING_SNAKE_CASE_, eos_token_id=SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = max_position_embeddings UpperCamelCase : Tuple = hidden_size UpperCamelCase : Union[str, Any] = num_hidden_layers UpperCamelCase : Optional[int] = num_attention_heads UpperCamelCase : Tuple = intermediate_size UpperCamelCase : List[str] = hidden_act UpperCamelCase : Union[str, Any] = hidden_dropout_prob UpperCamelCase : Optional[int] = attention_probs_dropout_prob UpperCamelCase : Optional[Any] = initializer_range UpperCamelCase : Tuple = type_vocab_size UpperCamelCase : Any = layer_norm_eps # Character config: UpperCamelCase : List[Any] = downsampling_rate UpperCamelCase : Optional[int] = upsampling_kernel_size UpperCamelCase : Tuple = num_hash_functions UpperCamelCase : Union[str, Any] = num_hash_buckets UpperCamelCase : str = local_transformer_stride
119
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_ = {"""configuration_deit""": ["""DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DeiTConfig""", """DeiTOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""DeiTFeatureExtractor"""] SCREAMING_SNAKE_CASE_ = ["""DeiTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """DEIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """DeiTForImageClassification""", """DeiTForImageClassificationWithTeacher""", """DeiTForMaskedImageModeling""", """DeiTModel""", """DeiTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFDeiTForImageClassification""", """TFDeiTForImageClassificationWithTeacher""", """TFDeiTForMaskedImageModeling""", """TFDeiTModel""", """TFDeiTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
352
from __future__ import annotations import math def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __lowercase ( _SCREAMING_SNAKE_CASE ) -> list[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = str(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = [n] for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' if len(str(_SCREAMING_SNAKE_CASE ) ) > 3: if not is_prime(int(str(_SCREAMING_SNAKE_CASE )[-3:] ) ) or not is_prime(int(str(_SCREAMING_SNAKE_CASE )[:3] ) ): return False return True def __lowercase ( _SCREAMING_SNAKE_CASE = 11 ) -> list[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 13 while len(_SCREAMING_SNAKE_CASE ) != count: if validate(_SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE = list_truncated_nums(_SCREAMING_SNAKE_CASE ) if all(is_prime(_SCREAMING_SNAKE_CASE ) for i in list_nums ): list_truncated_primes.append(_SCREAMING_SNAKE_CASE ) num += 2 return list_truncated_primes def __lowercase ( ) -> int: '''simple docstring''' return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(F'''{sum(compute_truncated_primes(1_1)) = }''')
193
0
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { """Salesforce/codegen-350M-nl""": """https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json""", """Salesforce/codegen-350M-multi""": """https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json""", """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json""", """Salesforce/codegen-2B-nl""": """https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json""", """Salesforce/codegen-2B-multi""": """https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json""", """Salesforce/codegen-2B-mono""": """https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json""", """Salesforce/codegen-6B-nl""": """https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json""", """Salesforce/codegen-6B-multi""": """https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json""", """Salesforce/codegen-6B-mono""": """https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json""", """Salesforce/codegen-16B-nl""": """https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json""", """Salesforce/codegen-16B-multi""": """https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json""", """Salesforce/codegen-16B-mono""": """https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json""", } class A__ ( __magic_name__ ): lowercase = 'codegen' lowercase = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Dict , a : Union[str, Any]=50_400 , a : Union[str, Any]=2_048 , a : int=2_048 , a : int=4_096 , a : Any=28 , a : Any=16 , a : List[str]=64 , a : Tuple=None , a : Optional[Any]="gelu_new" , a : Optional[int]=0.0 , a : Optional[Any]=0.0 , a : List[str]=0.0 , a : Dict=1E-5 , a : Any=0.0_2 , a : int=True , a : List[Any]=50_256 , a : List[str]=50_256 , a : List[str]=False , **a : str , ): '''simple docstring''' lowerCAmelCase__ : str = vocab_size lowerCAmelCase__ : int = n_ctx lowerCAmelCase__ : Dict = n_positions lowerCAmelCase__ : Union[str, Any] = n_embd lowerCAmelCase__ : Tuple = n_layer lowerCAmelCase__ : Tuple = n_head lowerCAmelCase__ : Dict = n_inner lowerCAmelCase__ : List[str] = rotary_dim lowerCAmelCase__ : Tuple = activation_function lowerCAmelCase__ : Optional[Any] = resid_pdrop lowerCAmelCase__ : int = embd_pdrop lowerCAmelCase__ : Union[str, Any] = attn_pdrop lowerCAmelCase__ : Optional[int] = layer_norm_epsilon lowerCAmelCase__ : Optional[Any] = initializer_range lowerCAmelCase__ : Optional[int] = use_cache lowerCAmelCase__ : str = bos_token_id lowerCAmelCase__ : List[str] = eos_token_id super().__init__( bos_token_id=a , eos_token_id=a , tie_word_embeddings=a , **a ) class A__ ( __magic_name__ ): def __init__( self : List[str] , a : PretrainedConfig , a : str = "default" , a : List[PatchingSpec] = None , a : bool = False , ): '''simple docstring''' super().__init__(a , task=a , patching_specs=a , use_past=a ) if not getattr(self._config , 'pad_token_id' , a ): # TODO: how to do that better? lowerCAmelCase__ : List[str] = 0 @property def _lowerCamelCase ( self : Union[str, Any] ): '''simple docstring''' lowerCAmelCase__ : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(a , direction='inputs' ) lowerCAmelCase__ : Dict = {0: 'batch', 1: 'past_sequence + sequence'} else: lowerCAmelCase__ : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def _lowerCamelCase ( self : Optional[Any] ): '''simple docstring''' return self._config.n_layer @property def _lowerCamelCase ( self : List[Any] ): '''simple docstring''' return self._config.n_head def _lowerCamelCase ( self : Any , a : PreTrainedTokenizer , a : int = -1 , a : int = -1 , a : bool = False , a : Optional[TensorType] = None , ): '''simple docstring''' lowerCAmelCase__ : Tuple = super(a , self ).generate_dummy_inputs( a , batch_size=a , seq_length=a , is_pair=a , framework=a ) # We need to order the input in the way they appears in the forward() lowerCAmelCase__ : List[str] = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch lowerCAmelCase__ , lowerCAmelCase__ : Optional[Any] = common_inputs['input_ids'].shape # Not using the same length for past_key_values lowerCAmelCase__ : Tuple = seqlen + 2 lowerCAmelCase__ : Any = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) lowerCAmelCase__ : Tuple = [ (torch.zeros(a ), torch.zeros(a )) for _ in range(self.num_layers ) ] lowerCAmelCase__ : str = common_inputs['attention_mask'] if self.use_past: lowerCAmelCase__ : Dict = ordered_inputs['attention_mask'].dtype lowerCAmelCase__ : Union[str, Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(a , a , dtype=a )] , dim=1 ) return ordered_inputs @property def _lowerCamelCase ( self : List[Any] ): '''simple docstring''' return 13
212
import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase__ = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class A__ ( __magic_name__ , unittest.TestCase ): lowercase = AlbertTokenizer lowercase = AlbertTokenizerFast lowercase = True lowercase = True lowercase = True def _lowerCamelCase ( self : int ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ : int = AlbertTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) def _lowerCamelCase ( self : List[str] , a : int ): '''simple docstring''' lowerCAmelCase__ : Any = 'this is a test' lowerCAmelCase__ : List[Any] = 'this is a test' return input_text, output_text def _lowerCamelCase ( self : Tuple ): '''simple docstring''' lowerCAmelCase__ : Tuple = '<pad>' lowerCAmelCase__ : Optional[Any] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _lowerCamelCase ( self : Union[str, Any] ): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '▁eloquent' ) self.assertEqual(len(a ) , 30_000 ) def _lowerCamelCase ( self : Optional[Any] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 30_000 ) def _lowerCamelCase ( self : List[str] ): '''simple docstring''' if not self.test_rust_tokenizer: return lowerCAmelCase__ : str = self.get_tokenizer() lowerCAmelCase__ : str = self.get_rust_tokenizer() lowerCAmelCase__ : List[Any] = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ : str = tokenizer.tokenize(a ) lowerCAmelCase__ : Optional[int] = rust_tokenizer.tokenize(a ) self.assertListEqual(a , a ) lowerCAmelCase__ : Tuple = tokenizer.encode(a , add_special_tokens=a ) lowerCAmelCase__ : Union[str, Any] = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) lowerCAmelCase__ : Optional[Any] = self.get_rust_tokenizer() lowerCAmelCase__ : Dict = tokenizer.encode(a ) lowerCAmelCase__ : List[Any] = rust_tokenizer.encode(a ) self.assertListEqual(a , a ) def _lowerCamelCase ( self : int ): '''simple docstring''' lowerCAmelCase__ : Tuple = AlbertTokenizer(a , keep_accents=a ) lowerCAmelCase__ : Union[str, Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(a , ['▁this', '▁is', '▁a', '▁test'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , [48, 25, 21, 1_289] ) lowerCAmelCase__ : Tuple = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( a , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.'] ) lowerCAmelCase__ : Any = tokenizer.convert_tokens_to_ids(a ) self.assertListEqual(a , [31, 23, 386, 19, 561, 3_050, 15, 17, 48, 25, 8_256, 18, 1, 9] ) lowerCAmelCase__ : Any = tokenizer.convert_ids_to_tokens(a ) self.assertListEqual( a , ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.'] , ) def _lowerCamelCase ( self : List[str] ): '''simple docstring''' lowerCAmelCase__ : List[str] = AlbertTokenizer(a ) lowerCAmelCase__ : Tuple = tokenizer.encode('sequence builders' ) lowerCAmelCase__ : Any = tokenizer.encode('multi-sequence build' ) lowerCAmelCase__ : Dict = tokenizer.build_inputs_with_special_tokens(a ) lowerCAmelCase__ : Tuple = tokenizer.build_inputs_with_special_tokens(a , a ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ] @slow def _lowerCamelCase ( self : Union[str, Any] ): '''simple docstring''' lowerCAmelCase__ : Dict = {'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'input_ids': [[2, 21_970, 13, 5, 6_092, 167, 28, 7_103, 2_153, 673, 8, 7_028, 12_051, 18, 17, 7_103, 2_153, 673, 8, 3_515, 18_684, 8, 4_461, 6, 1_927, 297, 8, 12_060, 2_607, 18, 13, 5, 4_461, 15, 10_538, 38, 8, 135, 15, 822, 58, 15, 993, 10_363, 15, 1_460, 8_005, 4_461, 15, 993, 255, 2_328, 9, 9, 9, 6, 26, 1_112, 816, 3_260, 13, 5, 103, 2_377, 6, 17, 1_112, 816, 2_782, 13, 5, 103, 10_641, 6, 29, 84, 2_512, 2_430, 782, 18_684, 2_761, 19, 808, 2_430, 2_556, 17, 855, 1_480, 9_477, 4_091, 128, 11_712, 15, 7_103, 2_153, 673, 17, 24_883, 9_990, 9, 3], [2, 11_502, 25, 1_006, 20, 782, 8, 11_809, 855, 1_732, 19_393, 18_667, 37, 367, 21_018, 69, 1_854, 34, 11_860, 19_124, 27, 156, 225, 17, 193, 4_141, 19, 65, 9_124, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 14, 2_231, 886, 2_385, 17_659, 84, 14, 16_792, 1_952, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='albert-base-v2' , revision='6b6560eaf5ff2e250b00c50f380c5389a9c2d82e' , )
212
1
"""simple docstring""" import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 A : Optional[Any] = get_tests_dir("fixtures") class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case ( self ): # A mock response for an HTTP head request to emulate server down __lowerCAmelCase = mock.Mock() __lowerCAmelCase = 5_00 __lowerCAmelCase = {} __lowerCAmelCase = HTTPError __lowerCAmelCase = {} # Download this model to make sure it's in the cache. __lowerCAmelCase = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=__a ) as mock_head: __lowerCAmelCase = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit" ) # This check we did call the fake head request mock_head.assert_called() def snake_case ( self ): # This test is for deprecated behavior and can be removed in v5 __lowerCAmelCase = ViTImageProcessor.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json" ) def snake_case ( self ): with self.assertRaises(__a ): # config is in subfolder, the following should not work without specifying the subfolder __lowerCAmelCase = AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants" ) __lowerCAmelCase = AutoImageProcessor.from_pretrained( "hf-internal-testing/stable-diffusion-all-variants" , subfolder="feature_extractor" ) self.assertIsNotNone(__a ) @is_staging_test class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @classmethod def snake_case ( cls ): __lowerCAmelCase = TOKEN HfFolder.save_token(__a ) @classmethod def snake_case ( cls ): try: delete_repo(token=cls._token , repo_id="test-image-processor" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-image-processor-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-image-processor" ) except HTTPError: pass def snake_case ( self ): __lowerCAmelCase = ViTImageProcessor.from_pretrained(__a ) image_processor.push_to_hub("test-image-processor" , use_auth_token=self._token ) __lowerCAmelCase = ViTImageProcessor.from_pretrained(f"{USER}/test-image-processor" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__a , getattr(__a , __a ) ) # Reset repo delete_repo(token=self._token , repo_id="test-image-processor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( __a , repo_id="test-image-processor" , push_to_hub=__a , use_auth_token=self._token ) __lowerCAmelCase = ViTImageProcessor.from_pretrained(f"{USER}/test-image-processor" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__a , getattr(__a , __a ) ) def snake_case ( self ): __lowerCAmelCase = ViTImageProcessor.from_pretrained(__a ) image_processor.push_to_hub("valid_org/test-image-processor" , use_auth_token=self._token ) __lowerCAmelCase = ViTImageProcessor.from_pretrained("valid_org/test-image-processor" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__a , getattr(__a , __a ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-image-processor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( __a , repo_id="valid_org/test-image-processor-org" , push_to_hub=__a , use_auth_token=self._token ) __lowerCAmelCase = ViTImageProcessor.from_pretrained("valid_org/test-image-processor-org" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__a , getattr(__a , __a ) ) def snake_case ( self ): CustomImageProcessor.register_for_auto_class() __lowerCAmelCase = CustomImageProcessor.from_pretrained(__a ) image_processor.push_to_hub("test-dynamic-image-processor" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {"AutoImageProcessor": "custom_image_processing.CustomImageProcessor"} , ) __lowerCAmelCase = AutoImageProcessor.from_pretrained( f"{USER}/test-dynamic-image-processor" , trust_remote_code=__a ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , "CustomImageProcessor" )
259
"""simple docstring""" import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer A : Any = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' __UpperCAmelCase : int ="""AutoTokenizer""" __UpperCAmelCase : Union[str, Any] =["""tokenizer"""] __UpperCAmelCase : Tuple ={ """semantic_prompt""": 1, """coarse_prompt""": 2, """fine_prompt""": 2, } def __init__( self , __a , __a=None ): super().__init__(__a ) __lowerCAmelCase = speaker_embeddings @classmethod def snake_case ( cls , __a , __a="speaker_embeddings_path.json" , **__a ): if speaker_embeddings_dict_path is not None: __lowerCAmelCase = get_file_from_repo( __a , __a , subfolder=kwargs.pop("subfolder" , __a ) , cache_dir=kwargs.pop("cache_dir" , __a ) , force_download=kwargs.pop("force_download" , __a ) , proxies=kwargs.pop("proxies" , __a ) , resume_download=kwargs.pop("resume_download" , __a ) , local_files_only=kwargs.pop("local_files_only" , __a ) , use_auth_token=kwargs.pop("use_auth_token" , __a ) , revision=kwargs.pop("revision" , __a ) , ) if speaker_embeddings_path is None: logger.warning( f"`{os.path.join(__a , __a )}` does not exists\n , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json\n dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`." ) __lowerCAmelCase = None else: with open(__a ) as speaker_embeddings_json: __lowerCAmelCase = json.load(__a ) else: __lowerCAmelCase = None __lowerCAmelCase = AutoTokenizer.from_pretrained(__a , **__a ) return cls(tokenizer=__a , speaker_embeddings=__a ) def snake_case ( self , __a , __a="speaker_embeddings_path.json" , __a="speaker_embeddings" , __a = False , **__a , ): if self.speaker_embeddings is not None: os.makedirs(os.path.join(__a , __a , "v2" ) , exist_ok=__a ) __lowerCAmelCase = {} __lowerCAmelCase = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": __lowerCAmelCase = self._load_voice_preset(__a ) __lowerCAmelCase = {} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict["repo_or_path"] , __a , f"{prompt_key}_{key}" ) , voice_preset[key] , allow_pickle=__a , ) __lowerCAmelCase = os.path.join(__a , f"{prompt_key}_{key}.npy" ) __lowerCAmelCase = tmp_dict with open(os.path.join(__a , __a ) , "w" ) as fp: json.dump(__a , __a ) super().save_pretrained(__a , __a , **__a ) def snake_case ( self , __a = None , **__a ): __lowerCAmelCase = self.speaker_embeddings[voice_preset] __lowerCAmelCase = {} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( f"Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}]." ) __lowerCAmelCase = get_file_from_repo( self.speaker_embeddings.get("repo_or_path" , "/" ) , voice_preset_paths[key] , subfolder=kwargs.pop("subfolder" , __a ) , cache_dir=kwargs.pop("cache_dir" , __a ) , force_download=kwargs.pop("force_download" , __a ) , proxies=kwargs.pop("proxies" , __a ) , resume_download=kwargs.pop("resume_download" , __a ) , local_files_only=kwargs.pop("local_files_only" , __a ) , use_auth_token=kwargs.pop("use_auth_token" , __a ) , revision=kwargs.pop("revision" , __a ) , ) if path is None: raise ValueError( f"`{os.path.join(self.speaker_embeddings.get('repo_or_path' , '/' ) , voice_preset_paths[key] )}` does not exists\n , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}\n embeddings." ) __lowerCAmelCase = np.load(__a ) return voice_preset_dict def snake_case ( self , __a = None ): for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(f"Voice preset unrecognized, missing {key} as a key." ) if not isinstance(voice_preset[key] , np.ndarray ): raise ValueError(f"{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray." ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(f"{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray." ) def __call__( self , __a=None , __a=None , __a="pt" , __a=2_56 , __a=False , __a=True , __a=False , **__a , ): if voice_preset is not None and not isinstance(__a , __a ): if ( isinstance(__a , __a ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): __lowerCAmelCase = self._load_voice_preset(__a ) else: if isinstance(__a , __a ) and not voice_preset.endswith(".npz" ): __lowerCAmelCase = voice_preset + ".npz" __lowerCAmelCase = np.load(__a ) if voice_preset is not None: self._validate_voice_preset_dict(__a , **__a ) __lowerCAmelCase = BatchFeature(data=__a , tensor_type=__a ) __lowerCAmelCase = self.tokenizer( __a , return_tensors=__a , padding="max_length" , max_length=__a , return_attention_mask=__a , return_token_type_ids=__a , add_special_tokens=__a , **__a , ) if voice_preset is not None: __lowerCAmelCase = voice_preset return encoded_text
259
1
'''simple docstring''' import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class _lowerCAmelCase ( unittest.TestCase ): def _a (self ): A_ : Optional[Any] = 10 def _a (self ): A_ : Dict = [1, 2, 3, 4] A_ : List[Any] = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(lowercase , self.block_size , 0 ) , lowercase ) def _a (self ): A_ : List[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] A_ : Tuple = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(lowercase , self.block_size , 0 ) , lowercase ) def _a (self ): A_ : Optional[Any] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] A_ : Any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(lowercase , self.block_size , 0 ) , lowercase ) def _a (self ): A_ : List[str] = """It was the year of Our Lord one thousand seven hundred and seventy-five.\n\nSpiritual revelations were conceded to England at that favoured period, as at this.""" A_, A_ : Dict = process_story(lowercase ) self.assertEqual(lowercase , [] ) def _a (self ): A_ : Optional[int] = """""" A_, A_ : List[str] = process_story(lowercase ) self.assertEqual(lowercase , [] ) self.assertEqual(lowercase , [] ) def _a (self ): A_ : Optional[Any] = ( """It was the year of Our Lord one thousand seven hundred and """ """seventy-five\n\nSpiritual revelations were conceded to England """ """at that favoured period, as at this.\n@highlight\n\nIt was the best of times""" ) A_, A_ : int = process_story(lowercase ) A_ : Optional[Any] = [ """It was the year of Our Lord one thousand seven hundred and seventy-five.""", """Spiritual revelations were conceded to England at that favoured period, as at this.""", ] self.assertEqual(lowercase , lowercase ) A_ : Dict = ["""It was the best of times."""] self.assertEqual(lowercase , lowercase ) def _a (self ): A_ : Optional[int] = torch.tensor([1, 2, 3, 4] ) A_ : Dict = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(lowercase , 0 ).numpy() , expected.numpy() ) def _a (self ): A_ : str = torch.tensor([1, 2, 3, 4, 23, 23, 23] ) A_ : str = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(lowercase , 23 ).numpy() , expected.numpy() ) def _a (self ): A_ : Any = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) A_ : List[str] = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(lowercase , 1 ).numpy() , expected.numpy() ) def _a (self ): A_ : List[Any] = 101 A_ : List[Any] = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]] ) A_ : List[str] = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) A_ : Dict = compute_token_type_ids(lowercase , lowercase ) np.testing.assert_array_equal(lowercase , lowercase )
206
'''simple docstring''' from string import ascii_lowercase, ascii_uppercase def a ( lowerCamelCase__ ): '''simple docstring''' if not sentence: return "" A_ : Optional[int] = dict(zip(lowerCamelCase__ , lowerCamelCase__ ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
206
1
import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Any = LongformerTokenizer UpperCAmelCase__: Union[str, Any] = True UpperCAmelCase__: Optional[int] = LongformerTokenizerFast UpperCAmelCase__: int = True def __A ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A__ : Any = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] A__ : Union[str, Any] = dict(zip(A__ , range(len(A__ ) ) ) ) A__ : str = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] A__ : List[str] = {"""unk_token""": """<unk>"""} A__ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) A__ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(A__ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(A__ ) ) def __A ( self , **A__ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **A__ ) def __A ( self , **A__ ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **A__ ) def __A ( self , A__ ): A__ : Dict = """lower newer""" A__ : Optional[int] = """lower newer""" return input_text, output_text def __A ( self ): A__ : Tuple = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) A__ : str = """lower newer""" A__ : Dict = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] A__ : Union[str, Any] = tokenizer.tokenize(A__ ) # , add_prefix_space=True) self.assertListEqual(A__ , A__ ) A__ : Optional[Any] = tokens + [tokenizer.unk_token] A__ : List[str] = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , A__ ) def __A ( self ): A__ : int = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=A__ ) , [0, 3_1414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=A__ ) , [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2] , ) @slow def __A ( self ): A__ : str = self.tokenizer_class.from_pretrained("""allenai/longformer-base-4096""" ) A__ : Any = tokenizer.encode("""sequence builders""" , add_special_tokens=A__ ) A__ : int = tokenizer.encode("""multi-sequence build""" , add_special_tokens=A__ ) A__ : List[str] = tokenizer.encode( """sequence builders""" , add_special_tokens=A__ , add_prefix_space=A__ ) A__ : List[Any] = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=A__ , add_prefix_space=A__ ) A__ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(A__ ) A__ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(A__ , A__ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def __A ( self ): A__ : Optional[int] = self.get_tokenizer() A__ : List[Any] = """Encode this sequence.""" A__ : List[Any] = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments A__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ , add_prefix_space=A__ ) A__ : int = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(A__ , A__ ) A__ : str = tokenizer.encode(A__ , add_special_tokens=A__ , add_prefix_space=A__ ) A__ : List[Any] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(A__ , A__ ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) A__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) A__ : Dict = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(A__ , A__ ) # Testing spaces after special tokens A__ : Tuple = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(A__ , lstrip=A__ , rstrip=A__ )} ) # mask token has a left space A__ : str = tokenizer.convert_tokens_to_ids(A__ ) A__ : Tuple = """Encode <mask> sequence""" A__ : Optional[int] = """Encode <mask>sequence""" A__ : Dict = tokenizer.encode(A__ ) A__ : Optional[Any] = encoded.index(A__ ) A__ : str = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(A__ , A__ ) A__ : Dict = tokenizer.encode(A__ ) A__ : Dict = encoded.index(A__ ) A__ : int = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(A__ , A__ ) def __A ( self ): pass def __A ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): A__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(A__ , **A__ ) A__ : Tuple = self.tokenizer_class.from_pretrained(A__ , **A__ ) A__ : List[Any] = """A, <mask> AllenNLP sentence.""" A__ : Optional[int] = tokenizer_r.encode_plus(A__ , add_special_tokens=A__ , return_token_type_ids=A__ ) A__ : Dict = tokenizer_p.encode_plus(A__ , add_special_tokens=A__ , return_token_type_ids=A__ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) A__ : Optional[int] = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) A__ : Optional[int] = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( A__ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( A__ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def __A ( self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): A__ : Optional[int] = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=A__ , add_prefix_space=A__ , trim_offsets=A__ ) A__ : Optional[Any] = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) A__ : List[Any] = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , A__ ) self.assertEqual(post_processor_state["""add_prefix_space"""] , A__ ) self.assertEqual(post_processor_state["""trim_offsets"""] , A__ ) def __A ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): A__ : Optional[int] = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` A__ : str = F"""{text_of_1_token} {text_of_1_token}""" A__ : Dict = self.rust_tokenizer_class.from_pretrained( A__ , use_fast=A__ , add_prefix_space=A__ , trim_offsets=A__ ) A__ : List[str] = tokenizer_r(A__ , return_offsets_mapping=A__ , add_special_tokens=A__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(A__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(A__ ) + 1, len(A__ ) + 1 + len(A__ )) , ) A__ : Dict = self.rust_tokenizer_class.from_pretrained( A__ , use_fast=A__ , add_prefix_space=A__ , trim_offsets=A__ ) A__ : Dict = tokenizer_r(A__ , return_offsets_mapping=A__ , add_special_tokens=A__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(A__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(A__ ) + 1, len(A__ ) + 1 + len(A__ )) , ) A__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained( A__ , use_fast=A__ , add_prefix_space=A__ , trim_offsets=A__ ) A__ : Any = tokenizer_r(A__ , return_offsets_mapping=A__ , add_special_tokens=A__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(A__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(A__ ), len(A__ ) + 1 + len(A__ )) , ) A__ : Any = self.rust_tokenizer_class.from_pretrained( A__ , use_fast=A__ , add_prefix_space=A__ , trim_offsets=A__ ) A__ : Dict = tokenizer_r(A__ , return_offsets_mapping=A__ , add_special_tokens=A__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(A__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(A__ ), len(A__ ) + 1 + len(A__ )) , ) A__ : List[str] = F""" {text}""" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) A__ : Any = self.rust_tokenizer_class.from_pretrained( A__ , use_fast=A__ , add_prefix_space=A__ , trim_offsets=A__ ) A__ : Any = tokenizer_r(A__ , return_offsets_mapping=A__ , add_special_tokens=A__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(A__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(A__ ) + 1, 1 + len(A__ ) + 1 + len(A__ )) , ) A__ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained( A__ , use_fast=A__ , add_prefix_space=A__ , trim_offsets=A__ ) A__ : int = tokenizer_r(A__ , return_offsets_mapping=A__ , add_special_tokens=A__ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(A__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(A__ ), 1 + len(A__ ) + 1 + len(A__ )) , ) A__ : Optional[int] = self.rust_tokenizer_class.from_pretrained( A__ , use_fast=A__ , add_prefix_space=A__ , trim_offsets=A__ ) A__ : Tuple = tokenizer_r(A__ , return_offsets_mapping=A__ , add_special_tokens=A__ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(A__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(A__ ), 1 + len(A__ ) + 1 + len(A__ )) , )
141
from typing import Any def UpperCamelCase (lowercase_: list ) -> list[Any]: if not input_list: return [] A__ : Any = [input_list.count(lowercase_ ) for value in input_list] A__ : List[Any] = max(lowercase_ ) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(lowercase_ ) if value == y} ) if __name__ == "__main__": import doctest doctest.testmod()
141
1
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable 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 .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
252
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
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __snake_case = logging.get_logger(__name__) class lowercase ( A__ ): """simple docstring""" _a = ['pixel_values'] def __init__( self , UpperCamelCase_ = True , UpperCamelCase_ = 32 , UpperCamelCase_=PILImageResampling.BILINEAR , UpperCamelCase_ = True , **UpperCamelCase_ , ): '''simple docstring''' UpperCamelCase__ :str = do_resize UpperCamelCase__ :Tuple = do_rescale UpperCamelCase__ :Optional[Any] = size_divisor UpperCamelCase__ :List[Any] = resample super().__init__(**UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = None , **UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ :Any = get_image_size(UpperCamelCase_ ) # Rounds the height and width down to the closest multiple of size_divisor UpperCamelCase__ :str = height // size_divisor * size_divisor UpperCamelCase__ :int = width // size_divisor * size_divisor UpperCamelCase__ :Dict = resize(UpperCamelCase_ , (new_h, new_w) , resample=UpperCamelCase_ , data_format=UpperCamelCase_ , **UpperCamelCase_ ) return image def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = None , **UpperCamelCase_ ): '''simple docstring''' return rescale(image=UpperCamelCase_ , scale=UpperCamelCase_ , data_format=UpperCamelCase_ , **UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_=None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = ChannelDimension.FIRST , **UpperCamelCase_ , ): '''simple docstring''' UpperCamelCase__ :Any = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ :int = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ :Optional[Any] = size_divisor if size_divisor is not None else self.size_divisor UpperCamelCase__ :Union[str, Any] = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('''size_divisor is required for resizing''' ) UpperCamelCase__ :List[Any] = make_list_of_images(UpperCamelCase_ ) if not valid_images(UpperCamelCase_ ): raise ValueError('''Invalid image(s)''' ) # All transformations expect numpy arrays. UpperCamelCase__ :int = [to_numpy_array(UpperCamelCase_ ) for img in images] if do_resize: UpperCamelCase__ :Union[str, Any] = [self.resize(UpperCamelCase_ , size_divisor=UpperCamelCase_ , resample=UpperCamelCase_ ) for image in images] if do_rescale: UpperCamelCase__ :Any = [self.rescale(UpperCamelCase_ , scale=1 / 255 ) for image in images] UpperCamelCase__ :List[str] = [to_channel_dimension_format(UpperCamelCase_ , UpperCamelCase_ ) for image in images] UpperCamelCase__ :Optional[Any] = {'''pixel_values''': images} return BatchFeature(data=UpperCamelCase_ , tensor_type=UpperCamelCase_ )
219
'''simple docstring''' import argparse from collections import defaultdict import yaml __snake_case = '''docs/source/en/_toctree.yml''' def a ( __a ) -> int: '''simple docstring''' UpperCamelCase__ :int = defaultdict(__a ) UpperCamelCase__ :int = [] UpperCamelCase__ :int = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({'''local''': doc['''local'''], '''title''': doc['''title''']} ) else: new_doc_list.append(__a ) UpperCamelCase__ :Union[str, Any] = new_doc_list UpperCamelCase__ :Tuple = [key for key, value in counts.items() if value > 1] UpperCamelCase__ :Union[str, Any] = [] for duplicate_key in duplicates: UpperCamelCase__ :Dict = list({doc['''title'''] for doc in doc_list if doc['''local'''] == duplicate_key} ) if len(__a ) > 1: raise ValueError( f'''{duplicate_key} is present several times in the documentation table of content at ''' '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ''' '''others.''' ) # Only add this once new_doc.append({'''local''': duplicate_key, '''title''': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if '''local''' not in counts or counts[doc['''local''']] == 1] ) UpperCamelCase__ :Union[str, Any] = sorted(__a , key=lambda __a : s["title"].lower() ) # "overview" gets special treatment and is always first if len(__a ) > 1: raise ValueError('''{doc_list} has two \'overview\' docs which is not allowed.''' ) overview_doc.extend(__a ) # Sort return overview_doc def a ( __a=False ) -> Any: '''simple docstring''' with open(__a , encoding='''utf-8''' ) as f: UpperCamelCase__ :Any = yaml.safe_load(f.read() ) # Get to the API doc UpperCamelCase__ :str = 0 while content[api_idx]["title"] != "API": api_idx += 1 UpperCamelCase__ :str = content[api_idx]['''sections'''] # Then to the model doc UpperCamelCase__ :Optional[Any] = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 UpperCamelCase__ :List[Any] = api_doc[scheduler_idx]['''sections'''] UpperCamelCase__ :Union[str, Any] = clean_doc_toc(__a ) UpperCamelCase__ :List[Any] = False if new_scheduler_doc != scheduler_doc: UpperCamelCase__ :Optional[int] = True if overwrite: UpperCamelCase__ :Dict = new_scheduler_doc if diff: if overwrite: UpperCamelCase__ :Any = api_doc with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) def a ( __a=False ) -> Optional[Any]: '''simple docstring''' with open(__a , encoding='''utf-8''' ) as f: UpperCamelCase__ :str = yaml.safe_load(f.read() ) # Get to the API doc UpperCamelCase__ :Optional[Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 UpperCamelCase__ :Any = content[api_idx]['''sections'''] # Then to the model doc UpperCamelCase__ :str = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 UpperCamelCase__ :Any = False UpperCamelCase__ :Union[str, Any] = api_doc[pipeline_idx]['''sections'''] UpperCamelCase__ :Tuple = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: UpperCamelCase__ :Dict = pipeline_doc['''section'''] UpperCamelCase__ :Optional[Any] = clean_doc_toc(__a ) if overwrite: UpperCamelCase__ :Optional[int] = new_sub_pipeline_doc new_pipeline_docs.append(__a ) # sort overall pipeline doc UpperCamelCase__ :Optional[Any] = clean_doc_toc(__a ) if new_pipeline_docs != pipeline_docs: UpperCamelCase__ :int = True if overwrite: UpperCamelCase__ :Union[str, Any] = new_pipeline_docs if diff: if overwrite: UpperCamelCase__ :Dict = api_doc with open(__a , '''w''' , encoding='''utf-8''' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) else: raise ValueError( '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') __snake_case = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
219
1
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class _UpperCAmelCase ( _lowerCAmelCase , unittest.TestCase ): a__ : Union[str, Any] = ShapEPipeline a__ : Union[str, Any] = ["prompt"] a__ : int = ["prompt"] a__ : Optional[int] = [ "num_images_per_prompt", "num_inference_steps", "generator", "latents", "guidance_scale", "frame_size", "output_type", "return_dict", ] a__ : int = False @property def a ( self : Optional[Any] ): return 32 @property def a ( self : Any ): return 32 @property def a ( self : str ): return self.time_input_dim * 4 @property def a ( self : List[str] ): return 8 @property def a ( self : str ): __UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def a ( self : Optional[int] ): torch.manual_seed(0 ) __UpperCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModelWithProjection(_lowercase ) @property def a ( self : List[Any] ): torch.manual_seed(0 ) __UpperCAmelCase = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } __UpperCAmelCase = PriorTransformer(**_lowercase ) return model @property def a ( self : int ): torch.manual_seed(0 ) __UpperCAmelCase = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } __UpperCAmelCase = ShapERenderer(**_lowercase ) return model def a ( self : Dict ): __UpperCAmelCase = self.dummy_prior __UpperCAmelCase = self.dummy_text_encoder __UpperCAmelCase = self.dummy_tokenizer __UpperCAmelCase = self.dummy_renderer __UpperCAmelCase = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=10_24 , prediction_type='''sample''' , use_karras_sigmas=_lowercase , clip_sample=_lowercase , clip_sample_range=1.0 , ) __UpperCAmelCase = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def a ( self : Any , _lowercase : List[str] , _lowercase : List[str]=0 ): if str(_lowercase ).startswith('''mps''' ): __UpperCAmelCase = torch.manual_seed(_lowercase ) else: __UpperCAmelCase = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) __UpperCAmelCase = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def a ( self : Optional[Any] ): __UpperCAmelCase = '''cpu''' __UpperCAmelCase = self.get_dummy_components() __UpperCAmelCase = self.pipeline_class(**_lowercase ) __UpperCAmelCase = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __UpperCAmelCase = pipe(**self.get_dummy_inputs(_lowercase ) ) __UpperCAmelCase = output.images[0] __UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __UpperCAmelCase = np.array( [ 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def a ( self : Union[str, Any] ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def a ( self : Tuple ): __UpperCAmelCase = torch_device == '''cpu''' __UpperCAmelCase = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=_lowercase , relax_max_difference=_lowercase , ) def a ( self : Union[str, Any] ): __UpperCAmelCase = self.get_dummy_components() __UpperCAmelCase = self.pipeline_class(**_lowercase ) __UpperCAmelCase = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __UpperCAmelCase = 1 __UpperCAmelCase = 2 __UpperCAmelCase = self.get_dummy_inputs(_lowercase ) for key in inputs.keys(): if key in self.batch_params: __UpperCAmelCase = batch_size * [inputs[key]] __UpperCAmelCase = pipe(**_lowercase , num_images_per_prompt=_lowercase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class _UpperCAmelCase ( unittest.TestCase ): def a ( self : int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def a ( self : List[Any] ): __UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''' ) __UpperCAmelCase = ShapEPipeline.from_pretrained('''openai/shap-e''' ) __UpperCAmelCase = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __UpperCAmelCase = torch.Generator(device=_lowercase ).manual_seed(0 ) __UpperCAmelCase = pipe( '''a shark''' , generator=_lowercase , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(_lowercase , _lowercase )
332
"""simple docstring""" import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowercase__ ( snake_case_ :ndarray ): return np.dot(snake_case_ , snake_case_ ) class _UpperCAmelCase : def __init__( self : Union[str, Any] , *, _lowercase : float = np.inf , _lowercase : str = "linear" , _lowercase : float = 0.0 , ): __UpperCAmelCase = regularization __UpperCAmelCase = gamma if kernel == "linear": __UpperCAmelCase = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError('''rbf kernel requires gamma''' ) if not isinstance(self.gamma , (float, int) ): raise ValueError('''gamma must be float or int''' ) if not self.gamma > 0: raise ValueError('''gamma must be > 0''' ) __UpperCAmelCase = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: __UpperCAmelCase = F'''Unknown kernel: {kernel}''' raise ValueError(_lowercase ) def a ( self : Dict , _lowercase : ndarray , _lowercase : ndarray ): return np.dot(_lowercase , _lowercase ) def a ( self : Any , _lowercase : ndarray , _lowercase : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def a ( self : Union[str, Any] , _lowercase : list[ndarray] , _lowercase : ndarray ): __UpperCAmelCase = observations __UpperCAmelCase = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((__UpperCAmelCase) , ) = np.shape(_lowercase ) def to_minimize(_lowercase : ndarray ) -> float: __UpperCAmelCase = 0 ((__UpperCAmelCase) , ) = np.shape(_lowercase ) for i in range(_lowercase ): for j in range(_lowercase ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(_lowercase ) __UpperCAmelCase = LinearConstraint(_lowercase , 0 , 0 ) __UpperCAmelCase = Bounds(0 , self.regularization ) __UpperCAmelCase = minimize( _lowercase , np.ones(_lowercase ) , bounds=_lowercase , constraints=[ly_contraint] ).x __UpperCAmelCase = l_star # calculating mean offset of separation plane to points __UpperCAmelCase = 0 for i in range(_lowercase ): for j in range(_lowercase ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) __UpperCAmelCase = s / n def a ( self : List[Any] , _lowercase : ndarray ): __UpperCAmelCase = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , _lowercase ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
332
1
from typing import List import jiwer import jiwer.transforms as tr from packaging import version import datasets from datasets.config import PY_VERSION if PY_VERSION < version.parse('''3.8'''): import importlib_metadata else: import importlib.metadata as importlib_metadata __lowercase = '''''' if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''): class lowerCamelCase_ ( tr.AbstractTransform ): '''simple docstring''' def __init__( self , __lowercase = " ") -> Optional[Any]: __UpperCamelCase :Dict = sentence_delimiter def UpperCamelCase__ ( self , __lowercase) -> str: return list(__lowercase) def UpperCamelCase__ ( self , __lowercase) -> Any: __UpperCamelCase :Union[str, Any] = [] for sent_idx, sentence in enumerate(__lowercase): chars.extend(self.process_string(__lowercase)) if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__lowercase) - 1: chars.append(self.sentence_delimiter) return chars __lowercase = tr.Compose( [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)] ) else: __lowercase = tr.Compose( [ tr.RemoveMultipleSpaces(), tr.Strip(), tr.ReduceToSingleSentence(SENTENCE_DELIMITER), tr.ReduceToListOfListOfChars(), ] ) __lowercase = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' __lowercase = '''\ Character error rate (CER) is a common metric of the performance of an automatic speech recognition system. CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information. Character error rate can be computed as: CER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct characters, N is the number of characters in the reference (N=S+D+C). CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the performance of the ASR system with a CER of 0 being a perfect score. ''' __lowercase = ''' Computes CER score of transcribed segments against references. Args: references: list of references for each speech input. predictions: list of transcribtions to score. concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result. Returns: (float): the character error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> cer = datasets.load_metric("cer") >>> cer_score = cer.compute(predictions=predictions, references=references) >>> print(cer_score) 0.34146341463414637 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase_ ( datasets.Metric ): '''simple docstring''' def UpperCamelCase__ ( self) -> Tuple: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence'''), '''references''': datasets.Value('''string''' , id='''sequence'''), }) , codebase_urls=['''https://github.com/jitsi/jiwer/'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/Word_error_rate''', '''https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates''', ] , ) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase=False) -> Optional[Any]: if concatenate_texts: return jiwer.compute_measures( __lowercase , __lowercase , truth_transform=__lowercase , hypothesis_transform=__lowercase , )["wer"] __UpperCamelCase :int = 0 __UpperCamelCase :Dict = 0 for prediction, reference in zip(__lowercase , __lowercase): __UpperCamelCase :List[Any] = jiwer.compute_measures( __lowercase , __lowercase , truth_transform=__lowercase , hypothesis_transform=__lowercase , ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
364
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration __lowercase = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :int = ['''layers''', '''blocks'''] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __lowercase = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :List[str] = list(s_dict.keys() ) for key in keys: __UpperCamelCase :Dict = key for k, v in WHISPER_MAPPING.items(): if k in key: __UpperCamelCase :str = new_key.replace(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print(f"""{key} -> {new_key}""" ) __UpperCamelCase :Any = s_dict.pop(SCREAMING_SNAKE_CASE ) return s_dict def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase , __UpperCamelCase :List[Any] = emb.weight.shape __UpperCamelCase :Any = nn.Linear(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , bias=SCREAMING_SNAKE_CASE ) __UpperCamelCase :str = emb.weight.data return lin_layer def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) __UpperCamelCase :int = os.path.basename(SCREAMING_SNAKE_CASE ) __UpperCamelCase :Optional[Any] = url.split('''/''' )[-2] __UpperCamelCase :Tuple = os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if os.path.exists(SCREAMING_SNAKE_CASE ) and not os.path.isfile(SCREAMING_SNAKE_CASE ): raise RuntimeError(f"""{download_target} exists and is not a regular file""" ) if os.path.isfile(SCREAMING_SNAKE_CASE ): __UpperCamelCase :List[str] = open(SCREAMING_SNAKE_CASE , '''rb''' ).read() if hashlib.shaaaa(SCREAMING_SNAKE_CASE ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"""{download_target} exists, but the SHA256 checksum does not match; re-downloading the file""" ) with urllib.request.urlopen(SCREAMING_SNAKE_CASE ) as source, open(SCREAMING_SNAKE_CASE , '''wb''' ) as output: with tqdm( total=int(source.info().get('''Content-Length''' ) ) , ncols=80 , unit='''iB''' , unit_scale=SCREAMING_SNAKE_CASE , unit_divisor=1_024 ) as loop: while True: __UpperCamelCase :Optional[Any] = source.read(8_192 ) if not buffer: break output.write(SCREAMING_SNAKE_CASE ) loop.update(len(SCREAMING_SNAKE_CASE ) ) __UpperCamelCase :str = open(SCREAMING_SNAKE_CASE , '''rb''' ).read() if hashlib.shaaaa(SCREAMING_SNAKE_CASE ).hexdigest() != expected_shaaaa: raise RuntimeError( '''Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.''' ) return model_bytes def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' if ".pt" not in checkpoint_path: __UpperCamelCase :Tuple = _download(_MODELS[checkpoint_path] ) else: __UpperCamelCase :Optional[int] = torch.load(SCREAMING_SNAKE_CASE , map_location='''cpu''' ) __UpperCamelCase :Union[str, Any] = original_checkpoint['''dims'''] __UpperCamelCase :List[Any] = original_checkpoint['''model_state_dict'''] __UpperCamelCase :Optional[Any] = state_dict['''decoder.token_embedding.weight'''] remove_ignore_keys_(SCREAMING_SNAKE_CASE ) rename_keys(SCREAMING_SNAKE_CASE ) __UpperCamelCase :Dict = True __UpperCamelCase :Tuple = state_dict['''decoder.layers.0.fc1.weight'''].shape[0] __UpperCamelCase :Dict = WhisperConfig( vocab_size=dimensions['''n_vocab'''] , encoder_ffn_dim=SCREAMING_SNAKE_CASE , decoder_ffn_dim=SCREAMING_SNAKE_CASE , num_mel_bins=dimensions['''n_mels'''] , d_model=dimensions['''n_audio_state'''] , max_target_positions=dimensions['''n_text_ctx'''] , encoder_layers=dimensions['''n_audio_layer'''] , encoder_attention_heads=dimensions['''n_audio_head'''] , decoder_layers=dimensions['''n_text_layer'''] , decoder_attention_heads=dimensions['''n_text_state'''] , max_source_positions=dimensions['''n_audio_ctx'''] , ) __UpperCamelCase :str = WhisperForConditionalGeneration(SCREAMING_SNAKE_CASE ) __UpperCamelCase , __UpperCamelCase :Any = model.model.load_state_dict(SCREAMING_SNAKE_CASE , strict=SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) > 0 and not set(SCREAMING_SNAKE_CASE ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( '''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,''' f""" but all the following weights are missing {missing}""" ) if tie_embeds: __UpperCamelCase :Optional[Any] = make_linear_from_emb(model.model.decoder.embed_tokens ) else: __UpperCamelCase :Union[str, Any] = proj_out_weights model.save_pretrained(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __lowercase = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') __lowercase = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
105
0