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
'''simple docstring''' import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = ["""image_processor""", """tokenizer"""] __lowercase = """BlipImageProcessor""" __lowercase = """AutoTokenizer""" def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" super().__init__(lowerCAmelCase_ , lowerCAmelCase_ ) # add QFormer tokenizer _snake_case = qformer_tokenizer def __call__( self , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = True , lowerCAmelCase_ = False , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = 0 , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = False , lowerCAmelCase_ = False , lowerCAmelCase_ = False , lowerCAmelCase_ = False , lowerCAmelCase_ = False , lowerCAmelCase_ = True , lowerCAmelCase_ = None , **lowerCAmelCase_ , ): """simple docstring""" if images is None and text is None: raise ValueError('You have to specify at least images or text.' ) _snake_case = BatchFeature() if text is not None: _snake_case = self.tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) encoding.update(lowerCAmelCase_ ) _snake_case = self.qformer_tokenizer( text=lowerCAmelCase_ , add_special_tokens=lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ , stride=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , return_overflowing_tokens=lowerCAmelCase_ , return_special_tokens_mask=lowerCAmelCase_ , return_offsets_mapping=lowerCAmelCase_ , return_token_type_ids=lowerCAmelCase_ , return_length=lowerCAmelCase_ , verbose=lowerCAmelCase_ , return_tensors=lowerCAmelCase_ , **lowerCAmelCase_ , ) _snake_case = qformer_text_encoding.pop('input_ids' ) _snake_case = qformer_text_encoding.pop('attention_mask' ) if images is not None: _snake_case = self.image_processor(lowerCAmelCase_ , return_tensors=lowerCAmelCase_ ) encoding.update(lowerCAmelCase_ ) return encoding def lowerCamelCase ( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" return self.tokenizer.batch_decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) def lowerCamelCase ( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" return self.tokenizer.decode(*lowerCAmelCase_ , **lowerCAmelCase_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.tokenizer.model_input_names _snake_case = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def lowerCamelCase ( self , lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" if os.path.isfile(lowerCAmelCase_ ): raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file' ) os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) _snake_case = os.path.join(lowerCAmelCase_ , 'qformer_tokenizer' ) self.qformer_tokenizer.save_pretrained(lowerCAmelCase_ ) return super().save_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) @classmethod def lowerCamelCase ( cls , lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" _snake_case = AutoTokenizer.from_pretrained(lowerCAmelCase_ , subfolder='qformer_tokenizer' ) _snake_case = cls._get_arguments_from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ ) args.append(lowerCAmelCase_ ) return cls(*lowerCAmelCase_ )
42
from __future__ import annotations from random import random class __A : '''simple docstring''' def __init__( self , __lowerCAmelCase = None ): '''simple docstring''' lowerCamelCase__ = value lowerCamelCase__ = random() lowerCamelCase__ = None lowerCamelCase__ = None def __repr__( self ): '''simple docstring''' from pprint import pformat if self.left is None and self.right is None: return F'\'{self.value}: {self.prior:.5}\'' else: return pformat( {F'{self.value}: {self.prior:.5}': (self.left, self.right)} , indent=1 ) def __str__( self ): '''simple docstring''' lowerCamelCase__ = str(self.value ) + ''' ''' lowerCamelCase__ = str(self.left or '''''' ) lowerCamelCase__ = str(self.right or '''''' ) return value + left + right def lowerCAmelCase__(__snake_case ,__snake_case ) -> tuple[Node | None, Node | None]: '''simple docstring''' if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: lowerCamelCase__ , lowerCamelCase__ = split(root.left ,__snake_case ) return left, root else: lowerCamelCase__ , lowerCamelCase__ = split(root.right ,__snake_case ) return root, right def lowerCAmelCase__(__snake_case ,__snake_case ) -> Node | None: '''simple docstring''' if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: lowerCamelCase__ = merge(left.right ,__snake_case ) return left else: lowerCamelCase__ = merge(__snake_case ,right.left ) return right def lowerCAmelCase__(__snake_case ,__snake_case ) -> Node | None: '''simple docstring''' lowerCamelCase__ = Node(__snake_case ) lowerCamelCase__ , lowerCamelCase__ = split(__snake_case ,__snake_case ) return merge(merge(__snake_case ,__snake_case ) ,__snake_case ) def lowerCAmelCase__(__snake_case ,__snake_case ) -> Node | None: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__ = split(__snake_case ,value - 1 ) lowerCamelCase__ , lowerCamelCase__ = split(__snake_case ,__snake_case ) return merge(__snake_case ,__snake_case ) def lowerCAmelCase__(__snake_case ) -> None: '''simple docstring''' if not root: # None return else: inorder(root.left ) print(root.value ,end=''',''' ) inorder(root.right ) def lowerCAmelCase__(__snake_case ,__snake_case ) -> Node | None: '''simple docstring''' for arg in args.split(): if arg[0] == "+": lowerCamelCase__ = insert(__snake_case ,int(arg[1:] ) ) elif arg[0] == "-": lowerCamelCase__ = erase(__snake_case ,int(arg[1:] ) ) else: print('''Unknown command''' ) return root def lowerCAmelCase__() -> None: '''simple docstring''' lowerCamelCase__ = None print( '''enter numbers to create a tree, + value to add value into treap, ''' '''- value to erase all nodes with value. \'q\' to quit. ''' ) lowerCamelCase__ = input() while args != "q": lowerCamelCase__ = interact_treap(__snake_case ,__snake_case ) print(__snake_case ) lowerCamelCase__ = input() print('''good by!''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
209
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase__ = {"configuration_vit_mae": ["VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMAEConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMAEForPreTraining", "ViTMAELayer", "ViTMAEModel", "ViTMAEPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "TFViTMAEForPreTraining", "TFViTMAEModel", "TFViTMAEPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
280
'''simple docstring''' def UpperCamelCase( UpperCAmelCase_ , UpperCAmelCase_ ): while a != 0: UpperCAmelCase , UpperCAmelCase : Tuple = b % a, a return b def UpperCamelCase( UpperCAmelCase_ , UpperCAmelCase_ ): if gcd(UpperCAmelCase_ , UpperCAmelCase_ ) != 1: UpperCAmelCase : List[str] = F"""mod inverse of {a!r} and {m!r} does not exist""" raise ValueError(UpperCAmelCase_ ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Any = 1, 0, a UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : Dict = 0, 1, m while va != 0: UpperCAmelCase : Tuple = ua // va UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : List[Any] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
280
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaTokenizer else: from ...utils.dummy_sentencepiece_objects import TaTokenizer lowerCAmelCase: Dict = TaTokenizer if is_tokenizers_available(): from ..ta.tokenization_ta_fast import TaTokenizerFast else: from ...utils.dummy_tokenizers_objects import TaTokenizerFast lowerCAmelCase: Dict = TaTokenizerFast lowerCAmelCase: str = {'''configuration_mt5''': ['''MT5Config''', '''MT5OnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Dict = [ '''MT5EncoderModel''', '''MT5ForConditionalGeneration''', '''MT5ForQuestionAnswering''', '''MT5Model''', '''MT5PreTrainedModel''', '''MT5Stack''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[str] = ['''TFMT5EncoderModel''', '''TFMT5ForConditionalGeneration''', '''TFMT5Model'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Dict = ['''FlaxMT5EncoderModel''', '''FlaxMT5ForConditionalGeneration''', '''FlaxMT5Model'''] if TYPE_CHECKING: from .configuration_mta import MTaConfig, MTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mta import ( MTaEncoderModel, MTaForConditionalGeneration, MTaForQuestionAnswering, MTaModel, MTaPreTrainedModel, MTaStack, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel else: import sys lowerCAmelCase: Any = _LazyModule( __name__, globals()['__file__'], _import_structure, extra_objects={'MT5Tokenizer': MTaTokenizer, 'MT5TokenizerFast': MTaTokenizerFast}, module_spec=__spec__, )
297
from __future__ import annotations def __lowerCamelCase ( UpperCAmelCase_ : dict , UpperCAmelCase_ : str ): """simple docstring""" a , a :Optional[Any] = set(UpperCAmelCase_ ), [start] while stack: a :Optional[int] = stack.pop() explored.add(UpperCAmelCase_ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(UpperCAmelCase_ ) return explored snake_case : Optional[int] = { '''A''': ['''B''', '''C''', '''D'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F'''], '''D''': ['''B''', '''D'''], '''E''': ['''B''', '''F'''], '''F''': ['''C''', '''E''', '''G'''], '''G''': ['''F'''], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, '''A'''))
94
0
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A = logging.get_logger(__name__) A = {'''vocab_file''': '''spiece.model'''} A = { '''vocab_file''': { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/spiece.model''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/spiece.model''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/spiece.model''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model''', } } A = { '''albert-base-v1''': 512, '''albert-large-v1''': 512, '''albert-xlarge-v1''': 512, '''albert-xxlarge-v1''': 512, '''albert-base-v2''': 512, '''albert-large-v2''': 512, '''albert-xlarge-v2''': 512, '''albert-xxlarge-v2''': 512, } A = '''▁''' class __lowercase ( _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _UpperCAmelCase , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=False , _UpperCAmelCase="[CLS]" , _UpperCAmelCase="[SEP]" , _UpperCAmelCase="<unk>" , _UpperCAmelCase="[SEP]" , _UpperCAmelCase="<pad>" , _UpperCAmelCase="[CLS]" , _UpperCAmelCase="[MASK]" , _UpperCAmelCase = None , **_UpperCAmelCase , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __a : int = ( AddedToken(_UpperCAmelCase , lstrip=_UpperCAmelCase , rstrip=_UpperCAmelCase , normalized=_UpperCAmelCase ) if isinstance(_UpperCAmelCase , _UpperCAmelCase ) else mask_token ) __a : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( 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 , sp_model_kwargs=self.sp_model_kwargs , **_UpperCAmelCase , ) __a : Tuple = do_lower_case __a : Optional[Any] = remove_space __a : Optional[Any] = keep_accents __a : Union[str, Any] = vocab_file __a : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_UpperCAmelCase ) @property def _lowerCamelCase ( self ): return len(self.sp_model ) def _lowerCamelCase ( self ): __a : Any = {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 ): __a : str = self.__dict__.copy() __a : Tuple = None return state def __setstate__( self , _UpperCAmelCase ): __a : Any = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __a : Optional[Any] = {} __a : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowerCamelCase ( self , _UpperCAmelCase ): if self.remove_space: __a : Any = ''' '''.join(inputs.strip().split() ) else: __a : Tuple = inputs __a : Union[str, Any] = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: __a : List[str] = unicodedata.normalize('''NFKD''' , _UpperCAmelCase ) __a : Optional[int] = ''''''.join([c for c in outputs if not unicodedata.combining(_UpperCAmelCase )] ) if self.do_lower_case: __a : Optional[Any] = outputs.lower() return outputs def _lowerCamelCase ( self , _UpperCAmelCase ): __a : int = self.preprocess_text(_UpperCAmelCase ) __a : Tuple = self.sp_model.encode(_UpperCAmelCase , out_type=_UpperCAmelCase ) __a : int = [] for piece in pieces: if len(_UpperCAmelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): __a : List[str] = self.sp_model.EncodeAsPieces(piece[:-1].replace(_UpperCAmelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __a : Tuple = cur_pieces[1:] else: __a : Optional[Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_UpperCAmelCase ) else: new_pieces.append(_UpperCAmelCase ) return new_pieces def _lowerCamelCase ( self , _UpperCAmelCase ): return self.sp_model.PieceToId(_UpperCAmelCase ) def _lowerCamelCase ( self , _UpperCAmelCase ): return self.sp_model.IdToPiece(_UpperCAmelCase ) def _lowerCamelCase ( self , _UpperCAmelCase ): __a : List[str] = [] __a : str = '''''' __a : 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 __a : Tuple = True __a : Tuple = [] else: current_sub_tokens.append(_UpperCAmelCase ) __a : Optional[int] = False out_string += self.sp_model.decode(_UpperCAmelCase ) return out_string.strip() def _lowerCamelCase ( self , _UpperCAmelCase , _UpperCAmelCase = None ): __a : int = [self.sep_token_id] __a : Union[str, 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 ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCAmelCase , token_ids_a=_UpperCAmelCase , already_has_special_tokens=_UpperCAmelCase ) if token_ids_a is not None: return [1] + ([0] * len(_UpperCAmelCase )) + [1] + ([0] * len(_UpperCAmelCase )) + [1] return [1] + ([0] * len(_UpperCAmelCase )) + [1] def _lowerCamelCase ( self , _UpperCAmelCase , _UpperCAmelCase = None ): __a : Union[str, Any] = [self.sep_token_id] __a : 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 ): if not os.path.isdir(_UpperCAmelCase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __a : List[str] = 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: __a : Any = self.sp_model.serialized_model_proto() fi.write(_UpperCAmelCase ) return (out_vocab_file,)
188
"""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 A = '''src/transformers''' A = '''docs/source/en/tasks''' def __A ( a_ :List[Any] , a_ :List[Any] , a_ :List[str]) -> List[str]: with open(a_ , '''r''' , encoding='''utf-8''' , newline='''\n''') as f: __a : List[str] = f.readlines() # Find the start prompt. __a : Optional[Any] = 0 while not lines[start_index].startswith(a_): start_index += 1 start_index += 1 __a : int = start_index while not lines[end_index].startswith(a_): end_index += 1 end_index -= 1 while len(lines[start_index]) <= 1: start_index += 1 while len(lines[end_index]) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index]), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. A = direct_transformers_import(TRANSFORMERS_PATH) A = { '''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`). A = { '''summarization.md''': ('''nllb''',), '''translation.md''': ('''nllb''',), } def __A ( a_ :Optional[Any]) -> Any: __a : List[Any] = TASK_GUIDE_TO_MODELS[task_guide] __a : List[Any] = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(a_ , set()) __a : 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 __A ( a_ :Optional[int] , a_ :Dict=False) -> Any: __a , __a , __a , __a : Any = _find_text_in_file( filename=os.path.join(a_ , a_) , start_prompt='''<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->''' , end_prompt='''<!--End of the generated tip-->''' , ) __a : Optional[Any] = get_model_list_for_task(a_) if current_list != new_list: if overwrite: with open(os.path.join(a_ , a_) , '''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__": A = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') A = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
188
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class _lowerCamelCase : '''simple docstring''' A_ : Dict = MBartConfig A_ : Optional[int] = {} A_ : Union[str, Any] = """gelu""" def __init__( self : List[Any] , _A : Union[str, Any] , _A : List[Any]=13 , _A : Optional[int]=7 , _A : Dict=True , _A : Any=False , _A : Dict=99 , _A : List[str]=32 , _A : List[str]=2 , _A : Optional[Any]=4 , _A : Dict=37 , _A : Any=0.1 , _A : Optional[Any]=0.1 , _A : str=20 , _A : Dict=2 , _A : str=1 , _A : Tuple=0 , ) -> int: __magic_name__ : List[str] = parent __magic_name__ : Optional[int] = batch_size __magic_name__ : Optional[int] = seq_length __magic_name__ : Optional[Any] = is_training __magic_name__ : int = use_labels __magic_name__ : List[str] = vocab_size __magic_name__ : Optional[int] = hidden_size __magic_name__ : Union[str, Any] = num_hidden_layers __magic_name__ : Tuple = num_attention_heads __magic_name__ : Dict = intermediate_size __magic_name__ : Optional[int] = hidden_dropout_prob __magic_name__ : Tuple = attention_probs_dropout_prob __magic_name__ : Tuple = max_position_embeddings __magic_name__ : Union[str, Any] = eos_token_id __magic_name__ : str = pad_token_id __magic_name__ : int = bos_token_id def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: __magic_name__ : List[str] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __magic_name__ : Optional[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __magic_name__ : str = tf.concat([input_ids, eos_tensor] , axis=1 ) __magic_name__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : Optional[int] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __magic_name__ : Union[str, Any] = prepare_mbart_inputs_dict(__a , __a , __a ) return config, inputs_dict def __lowerCAmelCase ( self : Optional[Any] , _A : Optional[int] , _A : List[str] ) -> Dict: __magic_name__ : Any = TFMBartModel(config=__a ).get_decoder() __magic_name__ : List[str] = inputs_dict['input_ids'] __magic_name__ : str = input_ids[:1, :] __magic_name__ : str = inputs_dict['attention_mask'][:1, :] __magic_name__ : Optional[int] = inputs_dict['head_mask'] __magic_name__ : Optional[Any] = 1 # first forward pass __magic_name__ : int = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a ) __magic_name__ , __magic_name__ : Any = outputs.to_tuple() __magic_name__ : Dict = past_key_values[1] def lowerCamelCase ( lowerCAmelCase : Dict , lowerCAmelCase : Dict , lowerCAmelCase : str , lowerCAmelCase : Any=None , lowerCAmelCase : int=None , lowerCAmelCase : Union[str, Any]=None , lowerCAmelCase : List[str]=None , lowerCAmelCase : Optional[int]=None , ): """simple docstring""" if attention_mask is None: __magic_name__ : Dict = tf.cast(tf.math.not_equal(_SCREAMING_SNAKE_CASE , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: __magic_name__ : Optional[int] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: __magic_name__ : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __magic_name__ : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __magic_name__ : str = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _lowerCamelCase ( _lowercase , _lowercase , unittest.TestCase ): '''simple docstring''' A_ : List[str] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () A_ : Optional[int] = (TFMBartForConditionalGeneration,) if is_tf_available() else () A_ : Dict = ( { """conversational""": TFMBartForConditionalGeneration, """feature-extraction""": TFMBartModel, """summarization""": TFMBartForConditionalGeneration, """text2text-generation""": TFMBartForConditionalGeneration, """translation""": TFMBartForConditionalGeneration, } if is_tf_available() else {} ) A_ : int = True A_ : Union[str, Any] = False A_ : int = False def __lowerCAmelCase ( self : Tuple , _A : Optional[Any] , _A : Tuple , _A : List[str] , _A : Union[str, Any] , _A : Any ) -> Any: if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def __lowerCAmelCase ( self : str ) -> List[Any]: __magic_name__ : Dict = TFMBartModelTester(self ) __magic_name__ : str = ConfigTester(self , config_class=__a ) def __lowerCAmelCase ( self : Optional[int] ) -> Optional[int]: self.config_tester.run_common_tests() def __lowerCAmelCase ( self : List[Any] ) -> Union[str, Any]: __magic_name__ : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) @require_sentencepiece @require_tokenizers @require_tf class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' A_ : Tuple = [ """ UN Chief Says There Is No Military Solution in Syria""", ] A_ : List[Any] = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", ] A_ : Optional[int] = """facebook/mbart-large-en-ro""" @cached_property def __lowerCAmelCase ( self : List[str] ) -> Optional[int]: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __lowerCAmelCase ( self : List[Any] ) -> int: __magic_name__ : List[str] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __lowerCAmelCase ( self : str , **_A : Tuple ) -> str: __magic_name__ : Optional[int] = self.translate_src_text(**__a ) self.assertListEqual(self.expected_text , __a ) def __lowerCAmelCase ( self : Any , **_A : Tuple ) -> Optional[int]: __magic_name__ : List[Any] = self.tokenizer(self.src_text , **__a , return_tensors='tf' ) __magic_name__ : Optional[int] = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) __magic_name__ : Tuple = self.tokenizer.batch_decode(__a , skip_special_tokens=__a ) return generated_words @slow def __lowerCAmelCase ( self : Optional[int] ) -> int: self._assert_generated_batch_equal_expected()
331
"""simple docstring""" import unittest from transformers import BertGenerationConfig, 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 BertGenerationDecoder, BertGenerationEncoder class _lowerCamelCase : def __init__(self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=99 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=50 , __a=0.02 , __a=True , __a=None , ) -> Union[str, Any]: UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = seq_length UpperCamelCase = is_training UpperCamelCase = use_input_mask UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = intermediate_size UpperCamelCase = hidden_act UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = initializer_range UpperCamelCase = use_labels UpperCamelCase = scope def snake_case_ (self ) -> Union[str, Any]: UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase = None if self.use_input_mask: UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase = self.get_config() return config, input_ids, input_mask, token_labels def snake_case_ (self ) -> List[str]: return BertGenerationConfig( 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 , is_decoder=__a , initializer_range=self.initializer_range , ) def snake_case_ (self ) -> List[str]: ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) = self.prepare_config_and_inputs() UpperCamelCase = True UpperCamelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def snake_case_ (self , __a , __a , __a , __a , **__a , ) -> Dict: UpperCamelCase = BertGenerationEncoder(config=__a ) model.to(__a ) model.eval() UpperCamelCase = model(__a , attention_mask=__a ) UpperCamelCase = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case_ (self , __a , __a , __a , __a , __a , __a , **__a , ) -> str: UpperCamelCase = True UpperCamelCase = BertGenerationEncoder(config=__a ) model.to(__a ) model.eval() UpperCamelCase = model( __a , attention_mask=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , ) UpperCamelCase = model( __a , attention_mask=__a , encoder_hidden_states=__a , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case_ (self , __a , __a , __a , __a , __a , __a , **__a , ) -> Optional[int]: UpperCamelCase = True UpperCamelCase = True UpperCamelCase = BertGenerationDecoder(config=__a ).to(__a ).eval() # first forward pass UpperCamelCase = model( __a , attention_mask=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , use_cache=__a , ) UpperCamelCase = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and UpperCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase = torch.cat([input_mask, next_mask] , dim=-1 ) UpperCamelCase = model( __a , attention_mask=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , output_hidden_states=__a , )["hidden_states"][0] UpperCamelCase = model( __a , attention_mask=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , past_key_values=__a , output_hidden_states=__a , )["hidden_states"][0] # select random slice UpperCamelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase = 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 snake_case_ (self , __a , __a , __a , __a , *__a , ) -> Optional[Any]: UpperCamelCase = BertGenerationDecoder(__a ) model.to(__a ) model.eval() UpperCamelCase = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case_ (self ) -> Dict: UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _lowerCamelCase ( _lowercase , _lowercase , _lowercase , unittest.TestCase ): UpperCAmelCase_ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () UpperCAmelCase_ = (BertGenerationDecoder,) if is_torch_available() else () UpperCAmelCase_ = ( {"feature-extraction": BertGenerationEncoder, "text-generation": BertGenerationDecoder} if is_torch_available() else {} ) def snake_case_ (self ) -> Any: UpperCamelCase = BertGenerationEncoderTester(self ) UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37 ) def snake_case_ (self ) -> Tuple: self.config_tester.run_common_tests() def snake_case_ (self ) -> List[str]: UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def snake_case_ (self ) -> Any: UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs() UpperCamelCase = "bert" self.model_tester.create_and_check_model(__a , __a , __a , __a ) def snake_case_ (self ) -> Optional[Any]: UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__a ) def snake_case_ (self ) -> List[str]: UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*__a ) def snake_case_ (self ) -> Union[str, Any]: # This regression test was failing with PyTorch < 1.3 ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() UpperCamelCase = None self.model_tester.create_and_check_model_as_decoder( __a , __a , __a , __a , __a , __a , ) def snake_case_ (self ) -> str: UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*__a ) @slow def snake_case_ (self ) -> List[str]: UpperCamelCase = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) self.assertIsNotNone(__a ) @require_torch class _lowerCamelCase ( unittest.TestCase ): @slow def snake_case_ (self ) -> int: UpperCamelCase = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) UpperCamelCase = torch.tensor([[1_01, 75_92, 10_10, 20_26, 38_99, 20_03, 1_01_40, 1_02]] ) with torch.no_grad(): UpperCamelCase = model(__a )[0] UpperCamelCase = torch.Size([1, 8, 10_24] ) self.assertEqual(output.shape , __a ) UpperCamelCase = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=1e-4 ) ) @require_torch class _lowerCamelCase ( unittest.TestCase ): @slow def snake_case_ (self ) -> Optional[Any]: UpperCamelCase = BertGenerationDecoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) UpperCamelCase = torch.tensor([[1_01, 75_92, 10_10, 20_26, 38_99, 20_03, 1_01_40, 1_02]] ) with torch.no_grad(): UpperCamelCase = model(__a )[0] UpperCamelCase = torch.Size([1, 8, 5_03_58] ) self.assertEqual(output.shape , __a ) UpperCamelCase = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=1e-4 ) )
153
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a__ : Dict = {'configuration_opt': ['OPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OPTConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ 'OPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'OPTForCausalLM', 'OPTModel', 'OPTPreTrainedModel', 'OPTForSequenceClassification', 'OPTForQuestionAnswering', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = ['TFOPTForCausalLM', 'TFOPTModel', 'TFOPTPreTrainedModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ '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__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
366
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a__ : List[str] = logging.get_logger(__name__) # General docstring a__ : Tuple = '''MobileNetV1Config''' # Base docstring a__ : Optional[Any] = '''google/mobilenet_v1_1.0_224''' a__ : Tuple = [1, 1_024, 7, 7] # Image classification docstring a__ : Optional[int] = '''google/mobilenet_v1_1.0_224''' a__ : int = '''tabby, tabby cat''' a__ : List[Any] = [ '''google/mobilenet_v1_1.0_224''', '''google/mobilenet_v1_0.75_192''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def UpperCAmelCase_( a__ , a__ , a__=None ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = {} if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[str] = model.mobilenet_va else: SCREAMING_SNAKE_CASE : Union[str, Any] = model SCREAMING_SNAKE_CASE : Optional[int] = '''MobilenetV1/Conv2d_0/''' SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.convolution.weight SCREAMING_SNAKE_CASE : Tuple = backbone.conv_stem.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = backbone.conv_stem.normalization.weight SCREAMING_SNAKE_CASE : Union[str, Any] = backbone.conv_stem.normalization.running_mean SCREAMING_SNAKE_CASE : Any = backbone.conv_stem.normalization.running_var for i in range(13 ): SCREAMING_SNAKE_CASE : Dict = i + 1 SCREAMING_SNAKE_CASE : Union[str, Any] = i * 2 SCREAMING_SNAKE_CASE : Any = backbone.layer[pt_index] SCREAMING_SNAKE_CASE : Optional[Any] = F"""MobilenetV1/Conv2d_{tf_index}_depthwise/""" SCREAMING_SNAKE_CASE : Any = pointer.convolution.weight SCREAMING_SNAKE_CASE : Tuple = pointer.normalization.bias SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : List[Any] = pointer.normalization.running_var SCREAMING_SNAKE_CASE : List[Any] = backbone.layer[pt_index + 1] SCREAMING_SNAKE_CASE : Any = F"""MobilenetV1/Conv2d_{tf_index}_pointwise/""" SCREAMING_SNAKE_CASE : Dict = pointer.convolution.weight SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.bias SCREAMING_SNAKE_CASE : Optional[Any] = pointer.normalization.weight SCREAMING_SNAKE_CASE : int = pointer.normalization.running_mean SCREAMING_SNAKE_CASE : str = pointer.normalization.running_var if isinstance(a__ , a__ ): SCREAMING_SNAKE_CASE : List[Any] = '''MobilenetV1/Logits/Conv2d_1c_1x1/''' SCREAMING_SNAKE_CASE : List[str] = model.classifier.weight SCREAMING_SNAKE_CASE : List[str] = model.classifier.bias return tf_to_pt_map def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" try: import numpy as np import tensorflow as tf except ImportError: logger.error( '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ''' '''https://www.tensorflow.org/install/ for installation instructions.''' ) raise # Load weights from TF model SCREAMING_SNAKE_CASE : Optional[Any] = tf.train.list_variables(a__ ) SCREAMING_SNAKE_CASE : List[Any] = {} for name, shape in init_vars: logger.info(F"""Loading TF weight {name} with shape {shape}""" ) SCREAMING_SNAKE_CASE : Tuple = tf.train.load_variable(a__ , a__ ) SCREAMING_SNAKE_CASE : Dict = array # Build TF to PyTorch weights loading map SCREAMING_SNAKE_CASE : int = _build_tf_to_pytorch_map(a__ , a__ , a__ ) for name, pointer in tf_to_pt_map.items(): logger.info(F"""Importing {name}""" ) if name not in tf_weights: logger.info(F"""{name} not in tf pre-trained weights, skipping""" ) continue SCREAMING_SNAKE_CASE : Union[str, Any] = tf_weights[name] if "depthwise_weights" in name: logger.info('''Transposing depthwise''' ) SCREAMING_SNAKE_CASE : Tuple = np.transpose(a__ , (2, 3, 0, 1) ) elif "weights" in name: logger.info('''Transposing''' ) if len(pointer.shape ) == 2: # copying into linear layer SCREAMING_SNAKE_CASE : Union[str, Any] = array.squeeze().transpose() else: SCREAMING_SNAKE_CASE : Optional[int] = np.transpose(a__ , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""" ) logger.info(F"""Initialize PyTorch weight {name} {array.shape}""" ) SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(a__ ) tf_weights.pop(a__ , a__ ) tf_weights.pop(name + '''/RMSProp''' , a__ ) tf_weights.pop(name + '''/RMSProp_1''' , a__ ) tf_weights.pop(name + '''/ExponentialMovingAverage''' , a__ ) logger.info(F"""Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}""" ) return model def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = features.shape[-2:] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = conv_layer.stride SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = conv_layer.kernel_size if in_height % stride_height == 0: SCREAMING_SNAKE_CASE : List[str] = max(kernel_height - stride_height , 0 ) else: SCREAMING_SNAKE_CASE : str = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: SCREAMING_SNAKE_CASE : int = max(kernel_width - stride_width , 0 ) else: SCREAMING_SNAKE_CASE : Tuple = max(kernel_width - (in_width % stride_width) , 0 ) SCREAMING_SNAKE_CASE : List[str] = pad_along_width // 2 SCREAMING_SNAKE_CASE : Any = pad_along_width - pad_left SCREAMING_SNAKE_CASE : str = pad_along_height // 2 SCREAMING_SNAKE_CASE : Optional[int] = pad_along_height - pad_top SCREAMING_SNAKE_CASE : List[Any] = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(a__ , a__ , '''constant''' , 0.0 ) class a_ ( nn.Module ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = 1 , _lowerCamelCase = 1 , _lowerCamelCase = False , _lowerCamelCase = True , _lowerCamelCase = True , ) ->None: super().__init__() SCREAMING_SNAKE_CASE : Any = config if in_channels % groups != 0: raise ValueError(F"""Input channels ({in_channels}) are not divisible by {groups} groups.""" ) if out_channels % groups != 0: raise ValueError(F"""Output channels ({out_channels}) are not divisible by {groups} groups.""" ) SCREAMING_SNAKE_CASE : Any = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) SCREAMING_SNAKE_CASE : List[str] = nn.Convad( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=_lowerCamelCase , stride=_lowerCamelCase , padding=_lowerCamelCase , groups=_lowerCamelCase , bias=_lowerCamelCase , padding_mode='''zeros''' , ) if use_normalization: SCREAMING_SNAKE_CASE : List[Any] = nn.BatchNormad( num_features=_lowerCamelCase , eps=config.layer_norm_eps , momentum=0.9_9_9_7 , affine=_lowerCamelCase , track_running_stats=_lowerCamelCase , ) else: SCREAMING_SNAKE_CASE : Dict = None if use_activation: if isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : Any = ACTaFN[use_activation] elif isinstance(config.hidden_act , _lowerCamelCase ): SCREAMING_SNAKE_CASE : List[str] = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE : List[Any] = config.hidden_act else: SCREAMING_SNAKE_CASE : Optional[Any] = None def __lowerCAmelCase ( self , _lowerCamelCase ) ->torch.Tensor: if self.config.tf_padding: SCREAMING_SNAKE_CASE : List[Any] = apply_tf_padding(_lowerCamelCase , self.convolution ) SCREAMING_SNAKE_CASE : Dict = self.convolution(_lowerCamelCase ) if self.normalization is not None: SCREAMING_SNAKE_CASE : int = self.normalization(_lowerCamelCase ) if self.activation is not None: SCREAMING_SNAKE_CASE : List[Any] = self.activation(_lowerCamelCase ) return features class a_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = MobileNetVaConfig __SCREAMING_SNAKE_CASE : List[Any] = load_tf_weights_in_mobilenet_va __SCREAMING_SNAKE_CASE : int = 'mobilenet_v1' __SCREAMING_SNAKE_CASE : int = 'pixel_values' __SCREAMING_SNAKE_CASE : List[str] = False def __lowerCAmelCase ( self , _lowerCamelCase ) ->None: if isinstance(_lowerCamelCase , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(_lowerCamelCase , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) a__ : str = r''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Union[str, Any] = r''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( 'The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase = True ) ->Dict: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = config SCREAMING_SNAKE_CASE : Dict = 32 SCREAMING_SNAKE_CASE : Optional[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) SCREAMING_SNAKE_CASE : str = MobileNetVaConvLayer( _lowerCamelCase , in_channels=config.num_channels , out_channels=_lowerCamelCase , kernel_size=3 , stride=2 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] SCREAMING_SNAKE_CASE : Any = nn.ModuleList() for i in range(13 ): SCREAMING_SNAKE_CASE : int = out_channels if strides[i] == 2 or i == 0: depth *= 2 SCREAMING_SNAKE_CASE : Tuple = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=3 , stride=strides[i] , groups=_lowerCamelCase , ) ) self.layer.append( MobileNetVaConvLayer( _lowerCamelCase , in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=1 , ) ) SCREAMING_SNAKE_CASE : int = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def __lowerCAmelCase ( self , _lowerCamelCase ) ->List[str]: raise NotImplementedError @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('''You have to specify pixel_values''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.conv_stem(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): SCREAMING_SNAKE_CASE : Optional[int] = layer_module(_lowerCamelCase ) if output_hidden_states: SCREAMING_SNAKE_CASE : List[str] = all_hidden_states + (hidden_states,) SCREAMING_SNAKE_CASE : List[str] = hidden_states if self.pooler is not None: SCREAMING_SNAKE_CASE : Tuple = torch.flatten(self.pooler(_lowerCamelCase ) , start_dim=1 ) else: SCREAMING_SNAKE_CASE : List[Any] = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=_lowerCamelCase , pooler_output=_lowerCamelCase , hidden_states=_lowerCamelCase , ) @add_start_docstrings( '\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , a__ , ) class a_ ( a__ ): """simple docstring""" def __init__( self , _lowerCamelCase ) ->None: super().__init__(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = config.num_labels SCREAMING_SNAKE_CASE : str = MobileNetVaModel(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head SCREAMING_SNAKE_CASE : Optional[int] = nn.Dropout(config.classifier_dropout_prob , inplace=_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = nn.Linear(_lowerCamelCase , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(_lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __lowerCAmelCase ( self , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ) ->Union[tuple, ImageClassifierOutputWithNoAttention]: SCREAMING_SNAKE_CASE : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Dict = self.mobilenet_va(_lowerCamelCase , output_hidden_states=_lowerCamelCase , return_dict=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = outputs.pooler_output if return_dict else outputs[1] SCREAMING_SNAKE_CASE : Tuple = self.classifier(self.dropout(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE : int = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE : Any = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE : Optional[int] = '''single_label_classification''' else: SCREAMING_SNAKE_CASE : Dict = '''multi_label_classification''' if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE : Any = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE : Dict = loss_fct(_lowerCamelCase , _lowerCamelCase ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE : str = CrossEntropyLoss() SCREAMING_SNAKE_CASE : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE : List[Any] = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE : List[Any] = loss_fct(_lowerCamelCase , _lowerCamelCase ) if not return_dict: SCREAMING_SNAKE_CASE : Optional[Any] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=_lowerCamelCase , logits=_lowerCamelCase , hidden_states=outputs.hidden_states , )
19
0
'''simple docstring''' import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { 'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json', 'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json', } class lowerCAmelCase_ ( lowerCamelCase_ ): '''simple docstring''' lowerCAmelCase_ : Dict = """encodec""" def __init__( self : Any , _UpperCAmelCase : List[Any]=[1.5, 3.0, 6.0, 12.0, 24.0] , _UpperCAmelCase : Tuple=2_40_00 , _UpperCAmelCase : Dict=1 , _UpperCAmelCase : List[str]=False , _UpperCAmelCase : List[str]=None , _UpperCAmelCase : int=None , _UpperCAmelCase : Union[str, Any]=1_28 , _UpperCAmelCase : Union[str, Any]=32 , _UpperCAmelCase : List[Any]=1 , _UpperCAmelCase : Dict=[8, 5, 4, 2] , _UpperCAmelCase : Union[str, Any]="weight_norm" , _UpperCAmelCase : int=7 , _UpperCAmelCase : Optional[Any]=7 , _UpperCAmelCase : str=3 , _UpperCAmelCase : Optional[int]=2 , _UpperCAmelCase : Dict=True , _UpperCAmelCase : List[str]="reflect" , _UpperCAmelCase : Any=2 , _UpperCAmelCase : Optional[Any]=2 , _UpperCAmelCase : List[Any]=1.0 , _UpperCAmelCase : Union[str, Any]=10_24 , _UpperCAmelCase : Any=None , _UpperCAmelCase : int=True , **_UpperCAmelCase : Optional[Any] , ): """simple docstring""" UpperCAmelCase__ = target_bandwidths UpperCAmelCase__ = sampling_rate UpperCAmelCase__ = audio_channels UpperCAmelCase__ = normalize UpperCAmelCase__ = chunk_length_s UpperCAmelCase__ = overlap UpperCAmelCase__ = hidden_size UpperCAmelCase__ = num_filters UpperCAmelCase__ = num_residual_layers UpperCAmelCase__ = upsampling_ratios UpperCAmelCase__ = norm_type UpperCAmelCase__ = kernel_size UpperCAmelCase__ = last_kernel_size UpperCAmelCase__ = residual_kernel_size UpperCAmelCase__ = dilation_growth_rate UpperCAmelCase__ = use_causal_conv UpperCAmelCase__ = pad_mode UpperCAmelCase__ = compress UpperCAmelCase__ = num_lstm_layers UpperCAmelCase__ = trim_right_ratio UpperCAmelCase__ = codebook_size UpperCAmelCase__ = codebook_dim if codebook_dim is not None else hidden_size UpperCAmelCase__ = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( f'''self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}''' ) super().__init__(**_UpperCAmelCase ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" UpperCAmelCase__ = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" return int(10_00 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
346
'''simple docstring''' import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase_ = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' UpperCAmelCase_ = '\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' UpperCAmelCase_ = '\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' UpperCAmelCase_ = '\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' UpperCAmelCase_ = 'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" ) ), """references""": datasets.Value("""string""" ), } ) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : List[str]=[1, 10, 1_00] , _UpperCAmelCase : Optional[Any]=4 , _UpperCAmelCase : Any=3.0 ): """simple docstring""" if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""" ) with ThreadPoolExecutor(max_workers=_UpperCAmelCase ) as executor: UpperCAmelCase__ = [] UpperCAmelCase__ = Counter() UpperCAmelCase__ = 0 UpperCAmelCase__ = defaultdict(_UpperCAmelCase ) for task_id, (candidates, test_case) in enumerate(zip(_UpperCAmelCase , _UpperCAmelCase ) ): for candidate in candidates: UpperCAmelCase__ = candidate + """\n""" + test_case UpperCAmelCase__ = (test_program, timeout, task_id, completion_id[task_id]) UpperCAmelCase__ = executor.submit(_UpperCAmelCase , *_UpperCAmelCase ) futures.append(_UpperCAmelCase ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(_UpperCAmelCase ): UpperCAmelCase__ = future.result() results[result["task_id"]].append((result["""completion_id"""], result) ) UpperCAmelCase__ , UpperCAmelCase__ = [], [] for result in results.values(): result.sort() UpperCAmelCase__ = [r[1]["""passed"""] for r in result] total.append(len(_UpperCAmelCase ) ) correct.append(sum(_UpperCAmelCase ) ) UpperCAmelCase__ = np.array(_UpperCAmelCase ) UpperCAmelCase__ = np.array(_UpperCAmelCase ) UpperCAmelCase__ = k UpperCAmelCase__ = {f'''pass@{k}''': estimate_pass_at_k(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] ): '''simple docstring''' def estimator(SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): UpperCAmelCase__ = itertools.repeat(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) else: assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = iter(SCREAMING_SNAKE_CASE__ ) return np.array([estimator(int(SCREAMING_SNAKE_CASE__ ) , int(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) for n, c in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )] )
346
1
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCamelCase : def __init__(self : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[Any]=2 , __SCREAMING_SNAKE_CASE : Union[str, Any]=8 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : List[str]=True , __SCREAMING_SNAKE_CASE : List[Any]=True , __SCREAMING_SNAKE_CASE : List[str]=9_9 , __SCREAMING_SNAKE_CASE : Dict=1_6 , __SCREAMING_SNAKE_CASE : Any=5 , __SCREAMING_SNAKE_CASE : Tuple=2 , __SCREAMING_SNAKE_CASE : List[str]=3_6 , __SCREAMING_SNAKE_CASE : Any="gelu" , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.0 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.0 , __SCREAMING_SNAKE_CASE : Dict=5_1_2 , __SCREAMING_SNAKE_CASE : List[Any]=1_6 , __SCREAMING_SNAKE_CASE : int=2 , __SCREAMING_SNAKE_CASE : Optional[int]=0.0_2 , __SCREAMING_SNAKE_CASE : Tuple=3 , __SCREAMING_SNAKE_CASE : Optional[Any]=4 , __SCREAMING_SNAKE_CASE : Tuple=None , ): A = parent A = batch_size A = seq_length A = is_training A = use_input_mask A = use_token_type_ids A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = type_sequence_label_size A = initializer_range A = num_labels A = num_choices A = scope def SCREAMING_SNAKE_CASE__ (self : Tuple): A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) A = None if self.use_input_mask: A = random_attention_mask([self.batch_size, self.seq_length]) A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) A = None A = None A = None if self.use_labels: A = ids_tensor([self.batch_size] , self.type_sequence_label_size) A = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) A = ids_tensor([self.batch_size] , self.num_choices) A = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ (self : List[str]): return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__ (self : Optional[Any]): A = self.get_config() A = 3_0_0 return config def SCREAMING_SNAKE_CASE__ (self : Tuple): ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = self.prepare_config_and_inputs() A = True A = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) A = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE__ (self : Dict , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Any): A = MraModel(config=__SCREAMING_SNAKE_CASE) model.to(__SCREAMING_SNAKE_CASE) model.eval() A = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE) A = model(__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE) A = model(__SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ (self : Dict , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Dict , ): A = True A = MraModel(__SCREAMING_SNAKE_CASE) model.to(__SCREAMING_SNAKE_CASE) model.eval() A = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , encoder_attention_mask=__SCREAMING_SNAKE_CASE , ) A = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , ) A = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ (self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int]): A = MraForMaskedLM(config=__SCREAMING_SNAKE_CASE) model.to(__SCREAMING_SNAKE_CASE) model.eval() A = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ (self : Optional[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : List[str]): A = MraForQuestionAnswering(config=__SCREAMING_SNAKE_CASE) model.to(__SCREAMING_SNAKE_CASE) model.eval() A = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , start_positions=__SCREAMING_SNAKE_CASE , end_positions=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE__ (self : Any , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Any): A = self.num_labels A = MraForSequenceClassification(__SCREAMING_SNAKE_CASE) model.to(__SCREAMING_SNAKE_CASE) model.eval() A = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ (self : Dict , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Any , __SCREAMING_SNAKE_CASE : int): A = self.num_labels A = MraForTokenClassification(config=__SCREAMING_SNAKE_CASE) model.to(__SCREAMING_SNAKE_CASE) model.eval() A = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE__ (self : Dict , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[Any]): A = self.num_choices A = MraForMultipleChoice(config=__SCREAMING_SNAKE_CASE) model.to(__SCREAMING_SNAKE_CASE) model.eval() A = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() A = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() A = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() A = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE__ (self : Optional[int]): A = self.prepare_config_and_inputs() ( ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ( A ) , ) = config_and_inputs A = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class __UpperCamelCase ( _A , unittest.TestCase ): SCREAMING_SNAKE_CASE = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = () def SCREAMING_SNAKE_CASE__ (self : int): A = MraModelTester(self) A = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , hidden_size=3_7) def SCREAMING_SNAKE_CASE__ (self : Optional[int]): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ (self : List[str]): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Tuple): A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A = type self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Tuple): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : str): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Any): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Any): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Union[str, Any]): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE) @slow def SCREAMING_SNAKE_CASE__ (self : Optional[int]): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = MraModel.from_pretrained(__SCREAMING_SNAKE_CASE) self.assertIsNotNone(__SCREAMING_SNAKE_CASE) @unittest.skip(reason="MRA does not output attentions") def SCREAMING_SNAKE_CASE__ (self : str): return @require_torch class __UpperCamelCase ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ (self : List[Any]): A = MraModel.from_pretrained("uw-madison/mra-base-512-4") A = torch.arange(2_5_6).unsqueeze(0) with torch.no_grad(): A = model(__SCREAMING_SNAKE_CASE)[0] A = torch.Size((1, 2_5_6, 7_6_8)) self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE) A = torch.tensor( [[[-0.0_1_4_0, 0.0_8_3_0, -0.0_3_8_1], [0.1_5_4_6, 0.1_4_0_2, 0.0_2_2_0], [0.1_1_6_2, 0.0_8_5_1, 0.0_1_6_5]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4)) @slow def SCREAMING_SNAKE_CASE__ (self : Tuple): A = MraForMaskedLM.from_pretrained("uw-madison/mra-base-512-4") A = torch.arange(2_5_6).unsqueeze(0) with torch.no_grad(): A = model(__SCREAMING_SNAKE_CASE)[0] A = 5_0_2_6_5 A = torch.Size((1, 2_5_6, vocab_size)) self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE) A = torch.tensor( [[[9.2_5_9_5, -3.6_0_3_8, 1_1.8_8_1_9], [9.3_8_6_9, -3.2_6_9_3, 1_1.0_9_5_6], [1_1.8_5_2_4, -3.4_9_3_8, 1_3.1_2_1_0]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4)) @slow def SCREAMING_SNAKE_CASE__ (self : Union[str, Any]): A = MraForMaskedLM.from_pretrained("uw-madison/mra-base-4096-8-d3") A = torch.arange(4_0_9_6).unsqueeze(0) with torch.no_grad(): A = model(__SCREAMING_SNAKE_CASE)[0] A = 5_0_2_6_5 A = torch.Size((1, 4_0_9_6, vocab_size)) self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE) A = torch.tensor( [[[5.4_7_8_9, -2.3_5_6_4, 7.5_0_6_4], [7.9_0_6_7, -1.3_3_6_9, 9.9_6_6_8], [9.0_7_1_2, -1.8_1_0_6, 7.0_3_8_0]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4))
57
"""simple docstring""" from __future__ import annotations class __UpperCamelCase : def __init__(self : Optional[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str): A , A = text, pattern A , A = len(__SCREAMING_SNAKE_CASE), len(__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Union[str, Any] , __SCREAMING_SNAKE_CASE : str): for i in range(self.patLen - 1 , -1 , -1): if char == self.pattern[i]: return i return -1 def SCREAMING_SNAKE_CASE__ (self : str , __SCREAMING_SNAKE_CASE : int): 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 SCREAMING_SNAKE_CASE__ (self : List[Any]): # searches pattern in text and returns index positions A = [] for i in range(self.textLen - self.patLen + 1): A = self.mismatch_in_text(__SCREAMING_SNAKE_CASE) if mismatch_index == -1: positions.append(__SCREAMING_SNAKE_CASE) else: A = self.match_in_pattern(self.text[mismatch_index]) A = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions __A : int = 'ABAABA' __A : Optional[Any] = 'AB' __A : Any = BoyerMooreSearch(text, pattern) __A : Any = bms.bad_character_heuristic() if len(positions) == 0: print('No match found') else: print('Pattern found in following positions: ') print(positions)
57
1
def lowerCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase )-> str: '''simple docstring''' if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) UpperCAmelCase : List[str] =str(bin(__lowerCAmelCase ) )[2:] # remove the leading "0b" UpperCAmelCase : Any =str(bin(__lowerCAmelCase ) )[2:] # remove the leading "0b" UpperCAmelCase : Optional[int] =max(len(__lowerCAmelCase ) , len(__lowerCAmelCase ) ) return "0b" + "".join( str(int(char_a != char_b ) ) for char_a, char_b in zip(a_binary.zfill(__lowerCAmelCase ) , b_binary.zfill(__lowerCAmelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
348
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __snake_case = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''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 __snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
348
1
"""simple docstring""" import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin a_ : List[str] = get_tests_dir('fixtures/test_sentencepiece.model') a_ : List[str] = get_tests_dir('fixtures/test_sentencepiece_bpe.model') a_ : str = 'pt' if is_torch_available() else 'tf' @require_sentencepiece @require_tokenizers class _snake_case ( A__ , unittest.TestCase ): _lowercase : List[Any] = CamembertTokenizer _lowercase : int = CamembertTokenizerFast _lowercase : str = True _lowercase : Tuple = True def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE = CamembertTokenizer(__snake_case) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__snake_case) , __snake_case) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__snake_case) , __snake_case) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '<s>NOTUSED') self.assertEqual(vocab_keys[1] , '<pad>') self.assertEqual(vocab_keys[-1] , '<mask>') self.assertEqual(len(__snake_case) , 1004) def SCREAMING_SNAKE_CASE__ ( self) -> Any: self.assertEqual(self.get_tokenizer().vocab_size , 1005) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = CamembertTokenizer(__snake_case) tokenizer.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = CamembertTokenizerFast.from_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE = tokenizer.encode(__snake_case) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(__snake_case) self.assertListEqual(__snake_case , __snake_case) SCREAMING_SNAKE_CASE = tokenizer.encode(__snake_case , add_special_tokens=__snake_case) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(__snake_case , add_special_tokens=__snake_case) self.assertListEqual(__snake_case , __snake_case) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(__snake_case) SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(__snake_case) self.assertListEqual(__snake_case , __snake_case) def SCREAMING_SNAKE_CASE__ ( self) -> Any: if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE = tokenizer.tokenize(__snake_case) SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(__snake_case) self.assertListEqual(__snake_case , __snake_case) SCREAMING_SNAKE_CASE = tokenizer.encode(__snake_case , add_special_tokens=__snake_case) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(__snake_case , add_special_tokens=__snake_case) self.assertListEqual(__snake_case , __snake_case) SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = tokenizer.encode(__snake_case) SCREAMING_SNAKE_CASE = rust_tokenizer.encode(__snake_case) self.assertListEqual(__snake_case , __snake_case) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: # fmt: off SCREAMING_SNAKE_CASE = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=__snake_case , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=__snake_case , )
353
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Optional[int] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = 1 / 255 , a = True , a = None , a = None , a = True , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = resample SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_normalize SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else OPENAI_CLIP_MEAN SCREAMING_SNAKE_CASE = image_std if image_std is not None else OPENAI_CLIP_STD SCREAMING_SNAKE_CASE = do_convert_rgb def SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}''') SCREAMING_SNAKE_CASE = (size['height'], size['width']) return resize(a , size=a , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> Optional[Any]: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb SCREAMING_SNAKE_CASE = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) SCREAMING_SNAKE_CASE = make_list_of_images(a) if not valid_images(a): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # PIL RGBA images are converted to RGB if do_convert_rgb: SCREAMING_SNAKE_CASE = [convert_to_rgb(a) for image in images] # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_resize: SCREAMING_SNAKE_CASE = [self.resize(image=a , size=a , resample=a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_normalize: SCREAMING_SNAKE_CASE = [self.normalize(image=a , mean=a , std=a) for image in images] SCREAMING_SNAKE_CASE = [to_channel_dimension_format(a , a) for image in images] SCREAMING_SNAKE_CASE = BatchFeature(data={'pixel_values': images} , tensor_type=a) return encoded_outputs
327
0
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) class snake_case_ ( __A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = ["input_ids", "attention_mask"] def __init__( self : List[Any] , _UpperCamelCase : str="</s>" , _UpperCamelCase : List[Any]="<unk>" , _UpperCamelCase : Optional[int]="<pad>" , _UpperCamelCase : Optional[int]=1_2_5 , _UpperCamelCase : Dict=None , **_UpperCamelCase : Tuple , ) ->None: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: snake_case_ = [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 snake_case_ = 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 ByT5Tokenizer. In this case the additional_special_tokens must include the''' ''' extra_ids tokens''' ) snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else pad_token snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else eos_token snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else unk_token super().__init__( eos_token=_UpperCamelCase , unk_token=_UpperCamelCase , pad_token=_UpperCamelCase , extra_ids=_UpperCamelCase , additional_special_tokens=_UpperCamelCase , **_UpperCamelCase , ) snake_case_ = extra_ids snake_case_ = 2**8 # utf is 8 bits # define special tokens dict snake_case_ = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } snake_case_ = len(self.special_tokens_encoder ) snake_case_ = len(_UpperCamelCase ) for i, token in enumerate(_UpperCamelCase ): snake_case_ = self.vocab_size + i - n snake_case_ = {v: k for k, v in self.special_tokens_encoder.items()} @property def snake_case__( self : Optional[int] ) ->List[str]: return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def snake_case__( self : Tuple , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None , _UpperCamelCase : bool = False ) ->List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCamelCase , token_ids_a=_UpperCamelCase , already_has_special_tokens=_UpperCamelCase ) # 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 snake_case__( self : Union[str, Any] , _UpperCamelCase : List[int] ) ->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 snake_case__( self : Optional[Any] , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None ) ->List[int]: snake_case_ = [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 snake_case__( self : Optional[Any] , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None ) ->List[int]: snake_case_ = self._add_eos_if_not_present(_UpperCamelCase ) if token_ids_a is None: return token_ids_a else: snake_case_ = self._add_eos_if_not_present(_UpperCamelCase ) return token_ids_a + token_ids_a def snake_case__( self : Optional[int] , _UpperCamelCase : str ) ->List[str]: snake_case_ = [chr(_UpperCamelCase ) for i in text.encode('''utf-8''' )] return tokens def snake_case__( self : List[str] , _UpperCamelCase : Union[str, Any] ) ->Optional[Any]: if token in self.special_tokens_encoder: snake_case_ = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: snake_case_ = self.added_tokens_encoder[token] elif len(_UpperCamelCase ) != 1: snake_case_ = self.unk_token_id else: snake_case_ = ord(_UpperCamelCase ) + self._num_special_tokens return token_id def snake_case__( self : int , _UpperCamelCase : Tuple ) ->Union[str, Any]: if index in self.special_tokens_decoder: snake_case_ = self.special_tokens_decoder[index] else: snake_case_ = chr(index - self._num_special_tokens ) return token def snake_case__( self : int , _UpperCamelCase : List[Any] ) ->str: snake_case_ = B'''''' for token in tokens: if token in self.special_tokens_decoder: snake_case_ = self.special_tokens_decoder[token].encode('''utf-8''' ) elif token in self.added_tokens_decoder: snake_case_ = self.special_tokens_decoder[token].encode('''utf-8''' ) elif token in self.special_tokens_encoder: snake_case_ = token.encode('''utf-8''' ) elif token in self.added_tokens_encoder: snake_case_ = token.encode('''utf-8''' ) else: snake_case_ = bytes([ord(_UpperCamelCase )] ) bstring += tok_string snake_case_ = bstring.decode('''utf-8''' , errors='''ignore''' ) return string def snake_case__( self : Dict , _UpperCamelCase : str , _UpperCamelCase : Optional[str] = None ) ->Tuple[str]: return ()
8
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = {'''vocab_file''': '''spiece.model'''} lowerCAmelCase_ = { '''vocab_file''': { '''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model''', '''google/bigbird-roberta-large''': ( '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model''' ), '''google/bigbird-base-trivia-itc''': ( '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model''' ), } } lowerCAmelCase_ = { '''google/bigbird-roberta-base''': 40_96, '''google/bigbird-roberta-large''': 40_96, '''google/bigbird-base-trivia-itc''': 40_96, } class snake_case_ ( __A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE : List[Any] = ["input_ids", "attention_mask"] SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self : List[str] , _UpperCamelCase : List[str] , _UpperCamelCase : Dict="<unk>" , _UpperCamelCase : List[str]="<s>" , _UpperCamelCase : Tuple="</s>" , _UpperCamelCase : Any="<pad>" , _UpperCamelCase : Any="[SEP]" , _UpperCamelCase : Optional[Any]="[MASK]" , _UpperCamelCase : Any="[CLS]" , _UpperCamelCase : Optional[Dict[str, Any]] = None , **_UpperCamelCase : Dict , ) ->None: snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else bos_token snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else eos_token snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else unk_token snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else pad_token snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else cls_token snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else sep_token # Mask token behave like a normal word, i.e. include the space before it snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else mask_token snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_UpperCamelCase , eos_token=_UpperCamelCase , unk_token=_UpperCamelCase , pad_token=_UpperCamelCase , sep_token=_UpperCamelCase , mask_token=_UpperCamelCase , cls_token=_UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_UpperCamelCase , ) snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_UpperCamelCase ) @property def snake_case__( self : str ) ->List[Any]: return self.sp_model.get_piece_size() def snake_case__( self : int ) ->Union[str, Any]: snake_case_ = {self.convert_ids_to_tokens(_UpperCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Tuple ) ->Any: snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : str , _UpperCamelCase : List[Any] ) ->List[str]: snake_case_ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def snake_case__( self : Optional[int] , _UpperCamelCase : str ) ->List[str]: return self.sp_model.encode(_UpperCamelCase , out_type=_UpperCamelCase ) def snake_case__( self : str , _UpperCamelCase : List[str] ) ->Tuple: return self.sp_model.piece_to_id(_UpperCamelCase ) def snake_case__( self : Union[str, Any] , _UpperCamelCase : str ) ->List[Any]: snake_case_ = self.sp_model.IdToPiece(_UpperCamelCase ) return token def snake_case__( self : Dict , _UpperCamelCase : Optional[int] ) ->List[str]: snake_case_ = [] snake_case_ = '''''' snake_case_ = 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 snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(_UpperCamelCase ) snake_case_ = False out_string += self.sp_model.decode(_UpperCamelCase ) return out_string.strip() def snake_case__( self : int , _UpperCamelCase : List[int] , _UpperCamelCase : bool = False , _UpperCamelCase : bool = None , _UpperCamelCase : bool = True , **_UpperCamelCase : List[str] , ) ->str: snake_case_ = kwargs.pop('''use_source_tokenizer''' , _UpperCamelCase ) snake_case_ = self.convert_ids_to_tokens(_UpperCamelCase , skip_special_tokens=_UpperCamelCase ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 snake_case_ = [] snake_case_ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_UpperCamelCase ) ) snake_case_ = [] sub_texts.append(_UpperCamelCase ) else: current_sub_text.append(_UpperCamelCase ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_UpperCamelCase ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: snake_case_ = re.sub(R''' (\[(MASK|SEP)\])''' , R'''\1''' , ''' '''.join(_UpperCamelCase ) ) else: snake_case_ = ''''''.join(_UpperCamelCase ) snake_case_ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: snake_case_ = self.clean_up_tokenization(_UpperCamelCase ) return clean_text else: return text def snake_case__( self : List[Any] , _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 snake_case_ = 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: snake_case_ = self.sp_model.serialized_model_proto() fi.write(_UpperCamelCase ) return (out_vocab_file,) def snake_case__( self : Tuple , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None ) ->List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case_ = [self.cls_token_id] snake_case_ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def snake_case__( self : List[str] , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None , _UpperCamelCase : bool = False ) ->List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCamelCase , token_ids_a=_UpperCamelCase , already_has_special_tokens=_UpperCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCamelCase )) + [1] return [1] + ([0] * len(_UpperCamelCase )) + [1] + ([0] * len(_UpperCamelCase )) + [1] def snake_case__( self : List[Any] , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None ) ->List[int]: snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
8
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_camembert import CamembertTokenizer else: __UpperCAmelCase = None __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} __UpperCAmelCase = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', }, 'tokenizer_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/tokenizer.json', }, } __UpperCAmelCase = { 'camembert-base': 5_12, } __UpperCAmelCase = '▁' class UpperCamelCase__ ( lowercase__ ): """simple docstring""" UpperCAmelCase_ =VOCAB_FILES_NAMES UpperCAmelCase_ =PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ =['input_ids', 'attention_mask'] UpperCAmelCase_ =CamembertTokenizer def __init__( self , _A=None , _A=None , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=["<s>NOTUSED", "</s>NOTUSED"] , **_A , ) -> Union[str, Any]: # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else mask_token super().__init__( _UpperCamelCase , tokenizer_file=_UpperCamelCase , bos_token=_UpperCamelCase , eos_token=_UpperCamelCase , sep_token=_UpperCamelCase , cls_token=_UpperCamelCase , unk_token=_UpperCamelCase , pad_token=_UpperCamelCase , mask_token=_UpperCamelCase , additional_special_tokens=_UpperCamelCase , **_UpperCamelCase , ) SCREAMING_SNAKE_CASE_ = vocab_file SCREAMING_SNAKE_CASE_ = False if not self.vocab_file else True def _UpperCamelCase ( self , _A , _A = None ) -> List[str]: 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 , _A , _A = None ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = [self.sep_token_id] SCREAMING_SNAKE_CASE_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _UpperCamelCase ( self , _A , _A = None ) -> List[str]: if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(_UpperCamelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE_ = os.path.join( _UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCamelCase ): copyfile(self.vocab_file , _UpperCamelCase ) return (out_vocab_file,)
358
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 UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @slow def _UpperCamelCase ( self ) -> List[str]: SCREAMING_SNAKE_CASE_ = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('''google/mt5-small''' ) SCREAMING_SNAKE_CASE_ = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids SCREAMING_SNAKE_CASE_ = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids SCREAMING_SNAKE_CASE_ = shift_tokens_right(_A , model.config.pad_token_id , model.config.decoder_start_token_id ) SCREAMING_SNAKE_CASE_ = model(_A , decoder_input_ids=_A ).logits SCREAMING_SNAKE_CASE_ = optax.softmax_cross_entropy(_A , onehot(_A , logits.shape[-1] ) ).mean() SCREAMING_SNAKE_CASE_ = -(labels.shape[-1] * loss.item()) SCREAMING_SNAKE_CASE_ = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
257
0
"""simple docstring""" from math import sqrt def UpperCamelCase_ ( lowerCAmelCase__ : int ) -> int: """simple docstring""" lowerCAmelCase_ : Union[str, Any] = 0 for i in range(1 , int(sqrt(lowerCAmelCase__ ) + 1 ) ): if n % i == 0 and i != sqrt(lowerCAmelCase__ ): total += i + n // i elif i == sqrt(lowerCAmelCase__ ): total += i return total - n def UpperCamelCase_ ( lowerCAmelCase__ : int = 1_0000 ) -> int: """simple docstring""" lowerCAmelCase_ : Union[str, Any] = sum( i for i in range(1 , lowerCAmelCase__ ) if sum_of_divisors(sum_of_divisors(lowerCAmelCase__ ) ) == i and sum_of_divisors(lowerCAmelCase__ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
224
"""simple docstring""" import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE__ ( self : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] ): self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) for a, b in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertAlmostEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , delta=SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE__ ( self : int ): lowerCAmelCase_ : int = GradientAccumulator() accumulator([tf.constant([1.0, 2.0] )] ) accumulator([tf.constant([-2.0, 1.0] )] ) accumulator([tf.constant([-1.0, 2.0] )] ) with self.assertRaises(SCREAMING_SNAKE_CASE_ ): accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] ) self.assertEqual(accumulator.step , 3 ) self.assertEqual(len(accumulator.gradients ) , 1 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1E-2 ) def SCREAMING_SNAKE_CASE__ ( self : str ): lowerCAmelCase_ : Optional[int] = None ops.enable_eager_execution_internal() lowerCAmelCase_ : str = tf.config.list_physical_devices('CPU' ) if len(SCREAMING_SNAKE_CASE_ ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) lowerCAmelCase_ : Dict = tf.config.list_logical_devices(device_type='CPU' ) lowerCAmelCase_ : Optional[int] = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): lowerCAmelCase_ : Union[str, Any] = GradientAccumulator() lowerCAmelCase_ : int = tf.Variable([4.0, 3.0] ) lowerCAmelCase_ ,lowerCAmelCase_ : Optional[int] = create_optimizer(5E-5 , 1_0 , 5 ) lowerCAmelCase_ : Union[str, Any] = tf.Variable([0.0, 0.0] , trainable=SCREAMING_SNAKE_CASE_ ) def accumulate_on_replica(SCREAMING_SNAKE_CASE_ : Optional[int] ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): with strategy.scope(): lowerCAmelCase_ : Tuple = strategy.experimental_local_results(SCREAMING_SNAKE_CASE_ ) local_variables[0].assign(SCREAMING_SNAKE_CASE_ ) local_variables[1].assign(SCREAMING_SNAKE_CASE_ ) strategy.run(SCREAMING_SNAKE_CASE_ , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(SCREAMING_SNAKE_CASE_ ) def _check_local_values(SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ): lowerCAmelCase_ : List[Any] = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , SCREAMING_SNAKE_CASE_ , tol=1E-2 ) self.assertListAlmostEqual(values[1].value() , SCREAMING_SNAKE_CASE_ , tol=1E-2 ) accumulate([1.0, 2.0] , [-1.0, 1.0] ) accumulate([3.0, -1.0] , [-1.0, -1.0] ) accumulate([-2.0, 2.0] , [3.0, -2.0] ) self.assertEqual(accumulator.step , 3 ) _check_local_values([2.0, 3.0] , [1.0, -2.0] ) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1E-2 ) accumulator.reset() self.assertEqual(accumulator.step , 0 ) _check_local_values([0.0, 0.0] , [0.0, 0.0] )
224
1
import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: Dict , __lowerCamelCase: Union[str, Any] , __lowerCamelCase: Optional[Any] , __lowerCamelCase: Any ): '''simple docstring''' lowercase_ = BigBirdConfig.from_json_file(__lowerCamelCase ) print(F'Building PyTorch model from configuration: {config}' ) if is_trivia_qa: lowercase_ = BigBirdForQuestionAnswering(__lowerCamelCase ) else: lowercase_ = BigBirdForPreTraining(__lowerCamelCase ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(__lowerCamelCase , __lowerCamelCase , is_trivia_qa=__lowerCamelCase ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--big_bird_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This 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_trivia_qa""", action="""store_true""", help="""Whether to convert a model with a trivia_qa head.""" ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
355
from typing import Callable, Dict, Optional, Tuple import torch from torch import nn from torch.distributions import ( AffineTransform, Distribution, Independent, NegativeBinomial, Normal, StudentT, TransformedDistribution, ) class __lowerCamelCase ( snake_case_ ): """simple docstring""" def __init__( self , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=0 ) -> Optional[int]: '''simple docstring''' lowercase_ = 1.0 if scale is None else scale lowercase_ = 0.0 if loc is None else loc super().__init__(UpperCAmelCase , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=UpperCAmelCase )] ) @property def A__ ( self ) -> int: '''simple docstring''' return self.base_dist.mean * self.scale + self.loc @property def A__ ( self ) -> str: '''simple docstring''' return self.base_dist.variance * self.scale**2 @property def A__ ( self ) -> List[str]: '''simple docstring''' return self.variance.sqrt() class __lowerCamelCase ( nn.Module ): """simple docstring""" def __init__( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , **UpperCAmelCase ) -> None: '''simple docstring''' super().__init__(**UpperCAmelCase ) lowercase_ = args_dim lowercase_ = nn.ModuleList([nn.Linear(UpperCAmelCase , UpperCAmelCase ) for dim in args_dim.values()] ) lowercase_ = domain_map def A__ ( self , UpperCAmelCase ) -> Tuple[torch.Tensor]: '''simple docstring''' lowercase_ = [proj(UpperCAmelCase ) for proj in self.proj] return self.domain_map(*UpperCAmelCase ) class __lowerCamelCase ( nn.Module ): """simple docstring""" def __init__( self , UpperCAmelCase ) -> Dict: '''simple docstring''' super().__init__() lowercase_ = function def A__ ( self , UpperCAmelCase , *UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' return self.function(UpperCAmelCase , *UpperCAmelCase ) class __lowerCamelCase : """simple docstring""" lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 def __init__( self , UpperCAmelCase = 1 ) -> None: '''simple docstring''' lowercase_ = dim lowercase_ = {k: dim * self.args_dim[k] for k in self.args_dim} def A__ ( self , UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' if self.dim == 1: return self.distribution_class(*UpperCAmelCase ) else: return Independent(self.distribution_class(*UpperCAmelCase ) , 1 ) def A__ ( self , UpperCAmelCase , UpperCAmelCase = None , UpperCAmelCase = None , ) -> Distribution: '''simple docstring''' lowercase_ = self._base_distribution(UpperCAmelCase ) if loc is None and scale is None: return distr else: return AffineTransformed(UpperCAmelCase , loc=UpperCAmelCase , scale=UpperCAmelCase , event_dim=self.event_dim ) @property def A__ ( self ) -> Tuple: '''simple docstring''' return () if self.dim == 1 else (self.dim,) @property def A__ ( self ) -> int: '''simple docstring''' return len(self.event_shape ) @property def A__ ( self ) -> float: '''simple docstring''' return 0.0 def A__ ( self , UpperCAmelCase ) -> nn.Module: '''simple docstring''' return ParameterProjection( in_features=UpperCAmelCase , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , ) def A__ ( self , *UpperCAmelCase ) -> Any: '''simple docstring''' raise NotImplementedError() @staticmethod def A__ ( UpperCAmelCase ) -> torch.Tensor: '''simple docstring''' return (x + torch.sqrt(torch.square(UpperCAmelCase ) + 4.0 )) / 2.0 class __lowerCamelCase ( snake_case_ ): """simple docstring""" lowerCAmelCase__ = {"df": 1, "loc": 1, "scale": 1} lowerCAmelCase__ = StudentT @classmethod def A__ ( cls , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Dict: '''simple docstring''' lowercase_ = cls.squareplus(UpperCAmelCase ).clamp_min(torch.finfo(scale.dtype ).eps ) lowercase_ = 2.0 + cls.squareplus(UpperCAmelCase ) return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 ) class __lowerCamelCase ( snake_case_ ): """simple docstring""" lowerCAmelCase__ = {"loc": 1, "scale": 1} lowerCAmelCase__ = Normal @classmethod def A__ ( cls , UpperCAmelCase , UpperCAmelCase ) -> int: '''simple docstring''' lowercase_ = cls.squareplus(UpperCAmelCase ).clamp_min(torch.finfo(scale.dtype ).eps ) return loc.squeeze(-1 ), scale.squeeze(-1 ) class __lowerCamelCase ( snake_case_ ): """simple docstring""" lowerCAmelCase__ = {"total_count": 1, "logits": 1} lowerCAmelCase__ = NegativeBinomial @classmethod def A__ ( cls , UpperCAmelCase , UpperCAmelCase ) -> Optional[int]: '''simple docstring''' lowercase_ = cls.squareplus(UpperCAmelCase ) return total_count.squeeze(-1 ), logits.squeeze(-1 ) def A__ ( self , UpperCAmelCase ) -> Distribution: '''simple docstring''' lowercase_ , lowercase_ = distr_args if self.dim == 1: return self.distribution_class(total_count=UpperCAmelCase , logits=UpperCAmelCase ) else: return Independent(self.distribution_class(total_count=UpperCAmelCase , logits=UpperCAmelCase ) , 1 ) def A__ ( self , UpperCAmelCase , UpperCAmelCase = None , UpperCAmelCase = None ) -> Distribution: '''simple docstring''' lowercase_ , lowercase_ = distr_args if scale is not None: # See scaling property of Gamma. logits += scale.log() return self._base_distribution((total_count, logits) )
297
0
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase_ ( UpperCamelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase__ : Optional[int] = TransfoXLTokenizer UpperCamelCase__ : Union[str, Any] = False UpperCamelCase__ : int = False def _A ( self ): '''simple docstring''' super().setUp() __SCREAMING_SNAKE_CASE = [ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __SCREAMING_SNAKE_CASE = 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 _A ( self , **_A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **_A ) def _A ( self , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = '<unk> UNwanted , running' __SCREAMING_SNAKE_CASE = '<unk> unwanted, running' return input_text, output_text def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=_A ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(_A , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [0, 4, 8, 7] ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TransfoXLTokenizer(lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TransfoXLTokenizer(lower_case=_A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TransfoXLTokenizer(lower_case=_A ) __SCREAMING_SNAKE_CASE = 'Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __SCREAMING_SNAKE_CASE = [ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(_A ) , _A ) self.assertEqual(tokenizer.convert_tokens_to_string(_A ) , _A ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = len(_A ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(_A ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
257
from __future__ import annotations import unittest from transformers import AutoTokenizer, MBartConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel @require_tf class UpperCAmelCase_ : '''simple docstring''' UpperCamelCase__ : int = MBartConfig UpperCamelCase__ : Optional[Any] = {} UpperCamelCase__ : Union[str, Any] = '''gelu''' def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=False , _A=99 , _A=32 , _A=2 , _A=4 , _A=37 , _A=0.1 , _A=0.1 , _A=20 , _A=2 , _A=1 , _A=0 , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = pad_token_id __SCREAMING_SNAKE_CASE = bos_token_id def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __SCREAMING_SNAKE_CASE = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __SCREAMING_SNAKE_CASE = tf.concat([input_ids, eos_tensor] , axis=1 ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __SCREAMING_SNAKE_CASE = prepare_mbart_inputs_dict(_A , _A , _A ) return config, inputs_dict def _A ( self , _A , _A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TFMBartModel(config=_A ).get_decoder() __SCREAMING_SNAKE_CASE = inputs_dict['input_ids'] __SCREAMING_SNAKE_CASE = input_ids[:1, :] __SCREAMING_SNAKE_CASE = inputs_dict['attention_mask'][:1, :] __SCREAMING_SNAKE_CASE = inputs_dict['head_mask'] __SCREAMING_SNAKE_CASE = 1 # first forward pass __SCREAMING_SNAKE_CASE = model(_A , attention_mask=_A , head_mask=_A , use_cache=_A ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() __SCREAMING_SNAKE_CASE = past_key_values[1] def __lowercase ( a__ , a__ , a__ , a__=None , a__=None , a__=None , a__=None , a__=None , ) -> str: if attention_mask is None: __SCREAMING_SNAKE_CASE = tf.cast(tf.math.not_equal(a__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: __SCREAMING_SNAKE_CASE = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: __SCREAMING_SNAKE_CASE = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __SCREAMING_SNAKE_CASE = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __SCREAMING_SNAKE_CASE = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase__ : Any = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else () UpperCamelCase__ : int = (TFMBartForConditionalGeneration,) if is_tf_available() else () UpperCamelCase__ : Optional[Any] = ( { '''conversational''': TFMBartForConditionalGeneration, '''feature-extraction''': TFMBartModel, '''summarization''': TFMBartForConditionalGeneration, '''text2text-generation''': TFMBartForConditionalGeneration, '''translation''': TFMBartForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase__ : List[str] = True UpperCamelCase__ : Tuple = False UpperCamelCase__ : Union[str, Any] = False def _A ( self , _A , _A , _A , _A , _A ): '''simple docstring''' if pipeline_test_casse_name != "FeatureExtractionPipelineTests": # Exception encountered when calling layer '...' return True return False def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TFMBartModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=_A ) def _A ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_A ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase__ : Any = [ ''' UN Chief Says There Is No Military Solution in Syria''', ] UpperCamelCase__ : str = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', ] UpperCamelCase__ : List[str] = '''facebook/mbart-large-en-ro''' @cached_property def _A ( self ): '''simple docstring''' return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _A ( self , **_A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.translate_src_text(**_A ) self.assertListEqual(self.expected_text , _A ) def _A ( self , **_A ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , **_A , return_tensors='tf' ) __SCREAMING_SNAKE_CASE = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 ) __SCREAMING_SNAKE_CASE = self.tokenizer.batch_decode(_A , skip_special_tokens=_A ) return generated_words @slow def _A ( self ): '''simple docstring''' self._assert_generated_batch_equal_expected()
257
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class a ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase ): snake_case_ = IFInpaintingPipeline snake_case_ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} snake_case_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS snake_case_ = PipelineTesterMixin.required_optional_params - {"latents"} def A_ ( self : str ): return self._get_dummy_components() def A_ ( self : Dict , lowercase_ : str , lowercase_ : Optional[int]=0 ): if str(lowercase_ ).startswith('''mps''' ): snake_case_ = torch.manual_seed(lowercase_ ) else: snake_case_ = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) snake_case_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowercase_ ) ).to(lowercase_ ) snake_case_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowercase_ ) ).to(lowercase_ ) snake_case_ = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def A_ ( self : Optional[Any] ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def A_ ( self : Any ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def A_ ( self : Dict ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def A_ ( self : Dict ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def A_ ( self : Any ): self._test_save_load_local() def A_ ( self : Optional[Any] ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
72
'''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 a : Optional[int] = logging.get_logger(__name__) a : Optional[Any] = {'vocab_file': 'spiece.model'} a : Tuple = { 'vocab_file': { 'bert_for_seq_generation': ( 'https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model' ), } } a : Dict = {'bert_for_seq_generation': 512} class a ( _lowerCamelCase ): 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 , lowercase_ : str , lowercase_ : Optional[Any]="<s>" , lowercase_ : Any="</s>" , lowercase_ : Optional[Any]="<unk>" , lowercase_ : List[Any]="<pad>" , lowercase_ : List[str]="<::::>" , lowercase_ : Optional[Dict[str, Any]] = None , **lowercase_ : Optional[int] , ): snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , pad_token=lowercase_ , sep_token=lowercase_ , sp_model_kwargs=self.sp_model_kwargs , **lowercase_ , ) snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase_ ) @property def A_ ( self : int ): return self.sp_model.get_piece_size() def A_ ( self : Union[str, Any] ): snake_case_ = {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 : Optional[int] ): snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Any , lowercase_ : Optional[int] ): snake_case_ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A_ ( self : Any , lowercase_ : str ): return self.sp_model.encode(lowercase_ , out_type=lowercase_ ) def A_ ( self : Optional[int] , lowercase_ : Union[str, Any] ): return self.sp_model.piece_to_id(lowercase_ ) def A_ ( self : Dict , lowercase_ : str ): snake_case_ = self.sp_model.IdToPiece(lowercase_ ) return token def A_ ( self : Optional[int] , lowercase_ : List[Any] ): snake_case_ = [] snake_case_ = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(lowercase_ ) + token snake_case_ = [] else: current_sub_tokens.append(lowercase_ ) out_string += self.sp_model.decode(lowercase_ ) return out_string.strip() def A_ ( self : List[str] , lowercase_ : str , lowercase_ : Optional[str] = None ): if not os.path.isdir(lowercase_ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return snake_case_ = 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: snake_case_ = self.sp_model.serialized_model_proto() fi.write(lowercase_ ) return (out_vocab_file,)
72
1
"""simple docstring""" from typing import Any class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = data SCREAMING_SNAKE_CASE_ : int = None class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = None def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = self.head while temp is not None: print(temp.data , end=''' ''') SCREAMING_SNAKE_CASE_ : Optional[Any] = temp.next print() def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowercase_ : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = Node(lowercase_) SCREAMING_SNAKE_CASE_ : int = self.head SCREAMING_SNAKE_CASE_ : List[str] = new_node def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : Union[str, Any] , lowercase_ : Tuple): '''simple docstring''' if node_data_a == node_data_a: return else: SCREAMING_SNAKE_CASE_ : List[Any] = self.head while node_a is not None and node_a.data != node_data_a: SCREAMING_SNAKE_CASE_ : List[Any] = node_a.next SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.head while node_a is not None and node_a.data != node_data_a: SCREAMING_SNAKE_CASE_ : Union[str, Any] = node_a.next if node_a is None or node_a is None: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = node_a.data, node_a.data if __name__ == "__main__": UpperCAmelCase_ : Optional[Any] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print("""After swapping""") ll.print_list()
91
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class a_ (unittest.TestCase ): def __UpperCamelCase ( self ): _lowerCAmelCase : Dict = """laion/clap-htsat-unfused""" _lowerCAmelCase : int = tempfile.mkdtemp() def __UpperCamelCase ( self , **snake_case_ ): return RobertaTokenizer.from_pretrained(self.checkpoint , **snake_case_ ) def __UpperCamelCase ( self , **snake_case_ ): return ClapFeatureExtractor.from_pretrained(self.checkpoint , **snake_case_ ) def __UpperCamelCase ( self ): shutil.rmtree(self.tmpdirname ) def __UpperCamelCase ( self ): _lowerCAmelCase : Optional[int] = self.get_tokenizer() _lowerCAmelCase : List[Any] = self.get_feature_extractor() _lowerCAmelCase : Union[str, Any] = ClapProcessor(tokenizer=snake_case_ , feature_extractor=snake_case_ ) processor.save_pretrained(self.tmpdirname ) _lowerCAmelCase : Any = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , snake_case_ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , snake_case_ ) def __UpperCamelCase ( self ): _lowerCAmelCase : Union[str, Any] = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) _lowerCAmelCase : Union[str, Any] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _lowerCAmelCase : int = self.get_feature_extractor(do_normalize=snake_case_ , padding_value=1.0 ) _lowerCAmelCase : Dict = ClapProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=snake_case_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , snake_case_ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , snake_case_ ) def __UpperCamelCase ( self ): _lowerCAmelCase : int = self.get_feature_extractor() _lowerCAmelCase : Optional[int] = self.get_tokenizer() _lowerCAmelCase : List[Any] = ClapProcessor(tokenizer=snake_case_ , feature_extractor=snake_case_ ) _lowerCAmelCase : Union[str, Any] = floats_list((3, 1_0_0_0) ) _lowerCAmelCase : List[str] = feature_extractor(snake_case_ , return_tensors="""np""" ) _lowerCAmelCase : Optional[Any] = processor(audios=snake_case_ , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __UpperCamelCase ( self ): _lowerCAmelCase : int = self.get_feature_extractor() _lowerCAmelCase : List[str] = self.get_tokenizer() _lowerCAmelCase : Tuple = ClapProcessor(tokenizer=snake_case_ , feature_extractor=snake_case_ ) _lowerCAmelCase : Union[str, Any] = """This is a test string""" _lowerCAmelCase : Union[str, Any] = processor(text=snake_case_ ) _lowerCAmelCase : Optional[int] = tokenizer(snake_case_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __UpperCamelCase ( self ): _lowerCAmelCase : Dict = self.get_feature_extractor() _lowerCAmelCase : Any = self.get_tokenizer() _lowerCAmelCase : List[Any] = ClapProcessor(tokenizer=snake_case_ , feature_extractor=snake_case_ ) _lowerCAmelCase : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _lowerCAmelCase : List[Any] = processor.batch_decode(snake_case_ ) _lowerCAmelCase : Dict = tokenizer.batch_decode(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) def __UpperCamelCase ( self ): _lowerCAmelCase : Union[str, Any] = self.get_feature_extractor() _lowerCAmelCase : Dict = self.get_tokenizer() _lowerCAmelCase : Optional[Any] = ClapProcessor(tokenizer=snake_case_ , feature_extractor=snake_case_ ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="""`processor` and `feature_extractor` model input names do not match""" , )
309
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase : Optional[int] = logging.get_logger(__name__) _lowerCamelCase : str = { '''facebook/xlm-roberta-xl''': '''https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json''', '''facebook/xlm-roberta-xxl''': '''https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json''', # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class lowerCamelCase (__lowerCamelCase ): """simple docstring""" UpperCAmelCase_ = "xlm-roberta-xl" def __init__( self : Union[str, Any], _UpperCAmelCase : Optional[int]=2_5_0_8_8_0, _UpperCAmelCase : Tuple=2_5_6_0, _UpperCAmelCase : str=3_6, _UpperCAmelCase : str=3_2, _UpperCAmelCase : List[Any]=1_0_2_4_0, _UpperCAmelCase : Optional[int]="gelu", _UpperCAmelCase : Optional[Any]=0.1, _UpperCAmelCase : Any=0.1, _UpperCAmelCase : str=5_1_4, _UpperCAmelCase : Optional[int]=1, _UpperCAmelCase : Tuple=0.02, _UpperCAmelCase : Optional[Any]=1E-05, _UpperCAmelCase : str=1, _UpperCAmelCase : Optional[int]=0, _UpperCAmelCase : int=2, _UpperCAmelCase : Optional[int]="absolute", _UpperCAmelCase : Optional[int]=True, _UpperCAmelCase : Optional[Any]=None, **_UpperCAmelCase : Optional[Any], ) -> Optional[int]: """simple docstring""" super().__init__(pad_token_id=_UpperCAmelCase, bos_token_id=_UpperCAmelCase, eos_token_id=_UpperCAmelCase, **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_size SCREAMING_SNAKE_CASE__ : Any = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : str = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : int = position_embedding_type SCREAMING_SNAKE_CASE__ : Any = use_cache SCREAMING_SNAKE_CASE__ : List[str] = classifier_dropout class lowerCamelCase (__lowerCamelCase ): """simple docstring""" @property def A_ ( self : Any ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : Union[str, Any] = {0: "batch", 1: "choice", 2: "sequence"} else: SCREAMING_SNAKE_CASE__ : List[str] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
191
import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( "split_dict" , [ SplitDict(), SplitDict({"train": SplitInfo(name="train" , num_bytes=13_37 , num_examples=42 , dataset_name="my_dataset" )} ), SplitDict({"train": SplitInfo(name="train" , num_bytes=13_37 , num_examples=42 )} ), SplitDict({"train": SplitInfo()} ), ] , ) def _a ( SCREAMING_SNAKE_CASE__ : SplitDict ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = split_dict._to_yaml_list() assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = SplitDict._from_yaml_list(SCREAMING_SNAKE_CASE__ ) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump SCREAMING_SNAKE_CASE__ : str = None # the split name of split_dict takes over the name of the split info object SCREAMING_SNAKE_CASE__ : Union[str, Any] = split_name assert split_dict == reloaded @pytest.mark.parametrize( "split_info" , [SplitInfo(), SplitInfo(dataset_name=SCREAMING_SNAKE_CASE__ ), SplitInfo(dataset_name="my_dataset" )] ) def _a ( SCREAMING_SNAKE_CASE__ : Any ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = asdict(SplitDict({"train": split_info} ) ) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
191
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available snake_case_ : Optional[Any] = { 'configuration_longt5': ['LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongT5Config', 'LongT5OnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : str = [ 'LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongT5EncoderModel', 'LongT5ForConditionalGeneration', 'LongT5Model', 'LongT5PreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Dict = [ 'FlaxLongT5ForConditionalGeneration', 'FlaxLongT5Model', 'FlaxLongT5PreTrainedModel', ] if TYPE_CHECKING: from .configuration_longta import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongTaConfig, LongTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longta import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongTaEncoderModel, LongTaForConditionalGeneration, LongTaModel, LongTaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_longta import ( FlaxLongTaForConditionalGeneration, FlaxLongTaModel, FlaxLongTaPreTrainedModel, ) else: import sys snake_case_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
83
'''simple docstring''' from math import pi def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): return 2 * pi * radius * (angle / 3_6_0) if __name__ == "__main__": print(arc_length(90, 10))
83
1
from math import ceil, sqrt def __UpperCamelCase ( lowerCAmelCase__ : int = 1_0_0_0_0_0_0 ): __a : Union[str, Any] = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: __a : List[str] = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: __a : Optional[Any] = 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() = }""")
90
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. lowercase__ =10 def __UpperCamelCase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : int ): for i in range(lowerCAmelCase__ , lowerCAmelCase__ ): if array[i] == target: return i return -1 def __UpperCamelCase ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : int ): __a : List[Any] = 0 __a : Union[str, Any] = len(lowerCAmelCase__ ) while left <= right: if right - left < precision: return lin_search(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __a : str = (left + right) // 3 + 1 __a : List[Any] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: __a : List[str] = one_third - 1 elif array[two_third] < target: __a : List[str] = two_third + 1 else: __a : Dict = one_third + 1 __a : Any = two_third - 1 else: return -1 def __UpperCamelCase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : int ): if left < right: if right - left < precision: return lin_search(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __a : Union[str, Any] = (left + right) // 3 + 1 __a : Optional[Any] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(lowerCAmelCase__ , one_third - 1 , lowerCAmelCase__ , lowerCAmelCase__ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , lowerCAmelCase__ , lowerCAmelCase__ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() lowercase__ =input('Enter numbers separated by comma:\n').strip() lowercase__ =[int(item.strip()) for item in user_input.split(',')] assert collection == sorted(collection), F"List must be ordered.\n{collection}." lowercase__ =int(input('Enter the number to be found in the list:\n').strip()) lowercase__ =ite_ternary_search(collection, target) lowercase__ =rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(F"""Iterative search: {target} found at positions: {resulta}""") print(F"""Recursive search: {target} found at positions: {resulta}""") else: print('Not found')
90
1
from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar __UpperCAmelCase = TypeVar('T') class lowerCamelCase (Generic[T] ): '''simple docstring''' def __init__( self , _UpperCamelCase , _UpperCamelCase ) -> None: UpperCAmelCase_ : Any | T = None UpperCAmelCase_ : int = len(_UpperCamelCase ) UpperCAmelCase_ : list[T] = [any_type for _ in range(self.N )] + arr UpperCAmelCase_ : Optional[int] = fnc self.build() def __UpperCAmelCase ( self ) -> None: for p in range(self.N - 1 , 0 , -1 ): UpperCAmelCase_ : str = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase ) -> None: p += self.N UpperCAmelCase_ : List[str] = v while p > 1: UpperCAmelCase_ : Optional[Any] = p // 2 UpperCAmelCase_ : Union[str, Any] = self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase ) -> T | None: # noqa: E741 UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = l + self.N, r + self.N UpperCAmelCase_ : T | None = None while l <= r: if l % 2 == 1: UpperCAmelCase_ : List[str] = self.st[l] if res is None else self.fn(_UpperCamelCase , self.st[l] ) if r % 2 == 0: UpperCAmelCase_ : Dict = self.st[r] if res is None else self.fn(_UpperCamelCase , self.st[r] ) UpperCAmelCase_ , UpperCAmelCase_ : str = (l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce __UpperCAmelCase = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12] __UpperCAmelCase = { 0: 7, 1: 2, 2: 6, 3: -14, 4: 5, 5: 4, 6: 7, 7: -10, 8: 9, 9: 10, 10: 12, 11: 1, } __UpperCAmelCase = SegmentTree(test_array, min) __UpperCAmelCase = SegmentTree(test_array, max) __UpperCAmelCase = SegmentTree(test_array, lambda a, b: a + b) def lowercase__ ( ): '''simple docstring''' for i in range(len(__snake_case ) ): for j in range(__snake_case , len(__snake_case ) ): UpperCAmelCase_ : Dict = reduce(__snake_case , test_array[i : j + 1] ) UpperCAmelCase_ : Dict = reduce(__snake_case , test_array[i : j + 1] ) UpperCAmelCase_ : str = reduce(lambda __snake_case , __snake_case : a + b , test_array[i : j + 1] ) assert min_range == min_segment_tree.query(__snake_case , __snake_case ) assert max_range == max_segment_tree.query(__snake_case , __snake_case ) assert sum_range == sum_segment_tree.query(__snake_case , __snake_case ) test_all_segments() for index, value in test_updates.items(): __UpperCAmelCase = value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
29
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def __UpperCamelCase ( _A ): lowerCAmelCase_ = 384 lowerCAmelCase_ = 7 if "tiny" in model_name: lowerCAmelCase_ = 96 lowerCAmelCase_ = (2, 2, 6, 2) lowerCAmelCase_ = (3, 6, 12, 24) elif "small" in model_name: lowerCAmelCase_ = 96 lowerCAmelCase_ = (2, 2, 18, 2) lowerCAmelCase_ = (3, 6, 12, 24) elif "base" in model_name: lowerCAmelCase_ = 128 lowerCAmelCase_ = (2, 2, 18, 2) lowerCAmelCase_ = (4, 8, 16, 32) lowerCAmelCase_ = 12 lowerCAmelCase_ = 512 elif "large" in model_name: lowerCAmelCase_ = 192 lowerCAmelCase_ = (2, 2, 18, 2) lowerCAmelCase_ = (6, 12, 24, 48) lowerCAmelCase_ = 12 lowerCAmelCase_ = 768 # set label information lowerCAmelCase_ = 150 lowerCAmelCase_ = '''huggingface/label-files''' lowerCAmelCase_ = '''ade20k-id2label.json''' lowerCAmelCase_ = json.load(open(hf_hub_download(_A , _A , repo_type='''dataset''' ) , '''r''' ) ) lowerCAmelCase_ = {int(_A ): v for k, v in idalabel.items()} lowerCAmelCase_ = {v: k for k, v in idalabel.items()} lowerCAmelCase_ = SwinConfig( embed_dim=_A , depths=_A , num_heads=_A , window_size=_A , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) lowerCAmelCase_ = UperNetConfig( backbone_config=_A , auxiliary_in_channels=_A , num_labels=_A , idalabel=_A , labelaid=_A , ) return config def __UpperCamelCase ( _A ): lowerCAmelCase_ = [] # fmt: off # stem rename_keys.append(('''backbone.patch_embed.projection.weight''', '''backbone.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''backbone.patch_embed.projection.bias''', '''backbone.embeddings.patch_embeddings.projection.bias''') ) rename_keys.append(('''backbone.patch_embed.norm.weight''', '''backbone.embeddings.norm.weight''') ) rename_keys.append(('''backbone.patch_embed.norm.bias''', '''backbone.embeddings.norm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm1.weight", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm1.bias", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight", f"backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias", f"backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm2.weight", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm2.bias", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight", f"backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias", f"backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight", f"backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight") ) rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias", f"backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias") ) if i < 3: rename_keys.append((f"backbone.stages.{i}.downsample.reduction.weight", f"backbone.encoder.layers.{i}.downsample.reduction.weight") ) rename_keys.append((f"backbone.stages.{i}.downsample.norm.weight", f"backbone.encoder.layers.{i}.downsample.norm.weight") ) rename_keys.append((f"backbone.stages.{i}.downsample.norm.bias", f"backbone.encoder.layers.{i}.downsample.norm.bias") ) rename_keys.append((f"backbone.norm{i}.weight", f"backbone.hidden_states_norms.stage{i+1}.weight") ) rename_keys.append((f"backbone.norm{i}.bias", f"backbone.hidden_states_norms.stage{i+1}.bias") ) # decode head rename_keys.extend( [ ('''decode_head.conv_seg.weight''', '''decode_head.classifier.weight'''), ('''decode_head.conv_seg.bias''', '''decode_head.classifier.bias'''), ('''auxiliary_head.conv_seg.weight''', '''auxiliary_head.classifier.weight'''), ('''auxiliary_head.conv_seg.bias''', '''auxiliary_head.classifier.bias'''), ] ) # fmt: on return rename_keys def __UpperCamelCase ( _A , _A , _A ): lowerCAmelCase_ = dct.pop(_A ) lowerCAmelCase_ = val def __UpperCamelCase ( _A , _A ): lowerCAmelCase_ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): lowerCAmelCase_ = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) lowerCAmelCase_ = state_dict.pop(f"backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight" ) lowerCAmelCase_ = state_dict.pop(f"backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict lowerCAmelCase_ = in_proj_weight[:dim, :] lowerCAmelCase_ = in_proj_bias[: dim] lowerCAmelCase_ = in_proj_weight[ dim : dim * 2, : ] lowerCAmelCase_ = in_proj_bias[ dim : dim * 2 ] lowerCAmelCase_ = in_proj_weight[ -dim :, : ] lowerCAmelCase_ = in_proj_bias[-dim :] # fmt: on def __UpperCamelCase ( _A ): lowerCAmelCase_ , lowerCAmelCase_ = x.shape lowerCAmelCase_ = x.reshape(_A , 4 , in_channel // 4 ) lowerCAmelCase_ = x[:, [0, 2, 1, 3], :].transpose(1 , 2 ).reshape(_A , _A ) return x def __UpperCamelCase ( _A ): lowerCAmelCase_ , lowerCAmelCase_ = x.shape lowerCAmelCase_ = x.reshape(_A , in_channel // 4 , 4 ) lowerCAmelCase_ = x[:, :, [0, 2, 1, 3]].transpose(1 , 2 ).reshape(_A , _A ) return x def __UpperCamelCase ( _A ): lowerCAmelCase_ = x.shape[0] lowerCAmelCase_ = x.reshape(4 , in_channel // 4 ) lowerCAmelCase_ = x[[0, 2, 1, 3], :].transpose(0 , 1 ).reshape(_A ) return x def __UpperCamelCase ( _A ): lowerCAmelCase_ = x.shape[0] lowerCAmelCase_ = x.reshape(in_channel // 4 , 4 ) lowerCAmelCase_ = x[:, [0, 2, 1, 3]].transpose(0 , 1 ).reshape(_A ) return x def __UpperCamelCase ( _A , _A , _A ): lowerCAmelCase_ = { '''upernet-swin-tiny''': '''https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth''', '''upernet-swin-small''': '''https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth''', '''upernet-swin-base''': '''https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth''', '''upernet-swin-large''': '''https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth''', } lowerCAmelCase_ = model_name_to_url[model_name] lowerCAmelCase_ = torch.hub.load_state_dict_from_url(_A , map_location='''cpu''' , file_name=_A )[ '''state_dict''' ] for name, param in state_dict.items(): print(_A , param.shape ) lowerCAmelCase_ = get_upernet_config(_A ) lowerCAmelCase_ = UperNetForSemanticSegmentation(_A ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): lowerCAmelCase_ = state_dict.pop(_A ) if "bn" in key: lowerCAmelCase_ = key.replace('''bn''' , '''batch_norm''' ) lowerCAmelCase_ = val # rename keys lowerCAmelCase_ = create_rename_keys(_A ) for src, dest in rename_keys: rename_key(_A , _A , _A ) read_in_q_k_v(_A , config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: lowerCAmelCase_ = reverse_correct_unfold_reduction_order(_A ) if "norm" in key: lowerCAmelCase_ = reverse_correct_unfold_norm_order(_A ) model.load_state_dict(_A ) # verify on image lowerCAmelCase_ = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg''' lowerCAmelCase_ = Image.open(requests.get(_A , stream=_A ).raw ).convert('''RGB''' ) lowerCAmelCase_ = SegformerImageProcessor() lowerCAmelCase_ = processor(_A , return_tensors='''pt''' ).pixel_values with torch.no_grad(): lowerCAmelCase_ = model(_A ) lowerCAmelCase_ = outputs.logits print(logits.shape ) print('''First values of logits:''' , logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": lowerCAmelCase_ = torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ) elif model_name == "upernet-swin-small": lowerCAmelCase_ = torch.tensor( [[-7.1_9_2_1, -7.1_9_2_1, -6.9_5_3_2], [-7.1_9_2_1, -7.1_9_2_1, -6.9_5_3_2], [-7.0_9_0_8, -7.0_9_0_8, -6.8_5_3_4]] ) elif model_name == "upernet-swin-base": lowerCAmelCase_ = torch.tensor( [[-6.5_8_5_1, -6.5_8_5_1, -6.4_3_3_0], [-6.5_8_5_1, -6.5_8_5_1, -6.4_3_3_0], [-6.4_7_6_3, -6.4_7_6_3, -6.3_2_5_4]] ) elif model_name == "upernet-swin-large": lowerCAmelCase_ = torch.tensor( [[-7.5_2_9_7, -7.5_2_9_7, -7.3_8_0_2], [-7.5_2_9_7, -7.5_2_9_7, -7.3_8_0_2], [-7.4_0_4_4, -7.4_0_4_4, -7.2_5_8_6]] ) print('''Logits:''' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , _A , atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_A ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(_A ) if push_to_hub: print(f"Pushing model and processor for {model_name} to hub" ) model.push_to_hub(f"openmmlab/{model_name}" ) processor.push_to_hub(f"openmmlab/{model_name}" ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''upernet-swin-tiny''', type=str, choices=[f"upernet-swin-{size}" for size in ['''tiny''', '''small''', '''base''', '''large''']], help='''Name of the Swin + UperNet model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) _A = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
278
0
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { "Visual-Attention-Network/van-base": ( "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json" ), } class snake_case__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" lowerCamelCase = """van""" def __init__( self : Optional[Any] , UpperCamelCase__ : List[str]=224 , UpperCamelCase__ : List[Any]=3 , UpperCamelCase__ : List[str]=[7, 3, 3, 3] , UpperCamelCase__ : Tuple=[4, 2, 2, 2] , UpperCamelCase__ : Union[str, Any]=[64, 128, 320, 512] , UpperCamelCase__ : Dict=[3, 3, 12, 3] , UpperCamelCase__ : List[Any]=[8, 8, 4, 4] , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : Tuple=1e-6 , UpperCamelCase__ : int=1e-2 , UpperCamelCase__ : Any=0.0 , UpperCamelCase__ : int=0.0 , **UpperCamelCase__ : Optional[int] , ) -> Tuple: """simple docstring""" super().__init__(**UpperCamelCase__ ) snake_case : Optional[int] = image_size snake_case : Union[str, Any] = num_channels snake_case : Dict = patch_sizes snake_case : List[str] = strides snake_case : str = hidden_sizes snake_case : Any = depths snake_case : str = mlp_ratios snake_case : Any = hidden_act snake_case : Optional[int] = initializer_range snake_case : Dict = layer_norm_eps snake_case : str = layer_scale_init_value snake_case : Tuple = drop_path_rate snake_case : Optional[int] = dropout_rate
371
'''simple docstring''' def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ ) -> list: '''simple docstring''' snake_case : Any = len(SCREAMING_SNAKE_CASE__ ) for i in range(1 , SCREAMING_SNAKE_CASE__ ): snake_case : Optional[int] = collection[i] snake_case : str = 0 snake_case : List[Any] = i - 1 while low <= high: snake_case : List[Any] = (low + high) // 2 if val < collection[mid]: snake_case : List[str] = mid - 1 else: snake_case : Optional[int] = mid + 1 for j in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , -1 ): snake_case : Dict = collection[j - 1] snake_case : Union[str, Any] = val return collection if __name__ == "__main__": lowercase__ = input("Enter numbers separated by a comma:\n").strip() lowercase__ = [int(item) for item in user_input.split(",")] print(binary_insertion_sort(unsorted))
83
0
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _UpperCamelCase : Any = 16 _UpperCamelCase : Tuple = 32 def a_ ( _lowerCAmelCase : Accelerator , _lowerCAmelCase : int = 16 , _lowerCAmelCase : str = "bert-base-cased" ): '''simple docstring''' lowercase__ : int = AutoTokenizer.from_pretrained(_lowerCAmelCase ) lowercase__ : Dict = load_dataset('glue' , 'mrpc' ) def tokenize_function(_lowerCAmelCase : Optional[Any] ): # max_length=None => use the model max length (it's actually the default) lowercase__ : int = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_lowerCAmelCase , max_length=_lowerCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowercase__ : List[str] = datasets.map( _lowerCAmelCase , batched=_lowerCAmelCase , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=_lowerCAmelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowercase__ : str = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_lowerCAmelCase : Optional[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(_lowerCAmelCase , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(_lowerCAmelCase , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. lowercase__ : List[Any] = DataLoader( tokenized_datasets['train'] , shuffle=_lowerCAmelCase , collate_fn=_lowerCAmelCase , batch_size=_lowerCAmelCase ) lowercase__ : Optional[int] = DataLoader( tokenized_datasets['validation'] , shuffle=_lowerCAmelCase , collate_fn=_lowerCAmelCase , batch_size=_lowerCAmelCase ) return train_dataloader, eval_dataloader def a_ ( _lowerCAmelCase : int , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Optional[Any] ): '''simple docstring''' model.eval() lowercase__ : List[str] = 0 for step, batch in enumerate(_lowerCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowercase__ : int = model(**_lowerCAmelCase ) lowercase__ : List[Any] = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times lowercase__ , lowercase__ : Dict = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(_lowerCAmelCase ) - 1: lowercase__ : str = predictions[: len(eval_dataloader.dataset ) - samples_seen] lowercase__ : Optional[Any] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=_lowerCAmelCase , references=_lowerCAmelCase , ) lowercase__ : Any = metric.compute() return eval_metric["accuracy"] def a_ ( _lowerCAmelCase : Any , _lowerCAmelCase : int ): '''simple docstring''' lowercase__ : Tuple = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowercase__ : str = config['lr'] lowercase__ : Any = int(config['num_epochs'] ) lowercase__ : Optional[Any] = int(config['seed'] ) lowercase__ : str = int(config['batch_size'] ) lowercase__ : Optional[int] = args.model_name_or_path set_seed(_lowerCAmelCase ) lowercase__ , lowercase__ : List[str] = get_dataloaders(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowercase__ : Dict = AutoModelForSequenceClassification.from_pretrained(_lowerCAmelCase , return_dict=_lowerCAmelCase ) # Instantiate optimizer lowercase__ : Dict = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowercase__ : Optional[Any] = optimizer_cls(params=model.parameters() , lr=_lowerCAmelCase ) if accelerator.state.deepspeed_plugin is not None: lowercase__ : Dict = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: lowercase__ : List[str] = 1 lowercase__ : int = (len(_lowerCAmelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowercase__ : List[Any] = get_linear_schedule_with_warmup( optimizer=_lowerCAmelCase , num_warmup_steps=0 , num_training_steps=_lowerCAmelCase , ) else: lowercase__ : Union[str, Any] = DummyScheduler(_lowerCAmelCase , total_num_steps=_lowerCAmelCase , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ : Dict = accelerator.prepare( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # We need to keep track of how many total steps we have iterated over lowercase__ : int = 0 # We also need to keep track of the stating epoch so files are named properly lowercase__ : Union[str, Any] = 0 lowercase__ : str = evaluate.load('glue' , 'mrpc' ) lowercase__ : Any = num_epochs if args.partial_train_epoch is not None: lowercase__ : int = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) lowercase__ : List[Any] = args.resume_from_checkpoint.split('epoch_' )[1] lowercase__ : List[str] = '' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break lowercase__ : str = int(_lowerCAmelCase ) + 1 lowercase__ : str = evaluation_loop(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) accelerator.print('resumed checkpoint performance:' , _lowerCAmelCase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:' , lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:' , optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir , f"""state_{starting_epoch-1}.json""" ) , 'r' ) as f: lowercase__ : Optional[Any] = json.load(_lowerCAmelCase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model lowercase__ : Optional[Any] = {} for epoch in range(_lowerCAmelCase , _lowerCAmelCase ): model.train() for step, batch in enumerate(_lowerCAmelCase ): lowercase__ : Optional[int] = model(**_lowerCAmelCase ) lowercase__ : Tuple = outputs.loss lowercase__ : Any = loss / gradient_accumulation_steps accelerator.backward(_lowerCAmelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 lowercase__ : Optional[Any] = f"""epoch_{epoch}""" lowercase__ : Optional[int] = os.path.join(args.output_dir , _lowerCAmelCase ) accelerator.save_state(_lowerCAmelCase ) lowercase__ : Union[str, Any] = evaluation_loop(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) lowercase__ : int = accuracy lowercase__ : int = lr_scheduler.get_lr()[0] lowercase__ : Dict = optimizer.param_groups[0]['lr'] lowercase__ : str = epoch lowercase__ : int = overall_step accelerator.print(f"""epoch {epoch}:""" , _lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , f"""state_{epoch}.json""" ) , 'w' ) as f: json.dump(_lowerCAmelCase , _lowerCAmelCase ) def a_ ( ): '''simple docstring''' lowercase__ : List[Any] = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=_lowerCAmelCase , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=_lowerCAmelCase , ) parser.add_argument( '--output_dir' , type=_lowerCAmelCase , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--resume_from_checkpoint' , type=_lowerCAmelCase , default=_lowerCAmelCase , help='If the training should continue from a checkpoint folder.' , ) parser.add_argument( '--partial_train_epoch' , type=_lowerCAmelCase , default=_lowerCAmelCase , help='If passed, the training will stop after this number of epochs.' , ) parser.add_argument( '--num_epochs' , type=_lowerCAmelCase , default=2 , help='Number of train epochs.' , ) lowercase__ : Optional[int] = parser.parse_args() lowercase__ : List[str] = {'lr': 2E-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(_lowerCAmelCase , _lowerCAmelCase ) if __name__ == "__main__": main()
77
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _UpperCamelCase : Any = logging.getLogger(__name__) _UpperCamelCase : Optional[Any] = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) _UpperCamelCase : Any = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCAmelCase_ : lowerCamelCase__ : Optional[str] = field( default=_a , metadata={ "help": ( "The model checkpoint for weights initialization. Leave None if you want to train a model from" " scratch." ) } , ) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(_a)} , ) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "Pretrained config name or path if not the same as model_name"}) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class UpperCAmelCase_ : lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "The input training data file (a text file)."}) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={ "help": ( "The input training data files (multiple files in glob format). " "Very often splitting large files to smaller files can prevent tokenizer going out of memory" ) } , ) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "An optional input train ref data file for whole word mask in Chinese."} , ) lowerCamelCase__ : Optional[str] = field( default=_a , metadata={"help": "An optional input eval ref data file for whole word mask in Chinese."} , ) lowerCamelCase__ : bool = field( default=_a , metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."} , ) lowerCamelCase__ : bool = field( default=_a , metadata={"help": "Train with masked-language modeling loss instead of language modeling."}) lowerCamelCase__ : bool = field(default=_a , metadata={"help": "Whether ot not to use whole word mask."}) lowerCamelCase__ : float = field( default=0.15 , metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}) lowerCamelCase__ : float = field( default=1 / 6 , metadata={ "help": ( "Ratio of length of a span of masked tokens to surrounding context length for permutation language" " modeling." ) } , ) lowerCamelCase__ : int = field( default=5 , metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."}) lowerCamelCase__ : int = field( default=-1 , metadata={ "help": ( "Optional input sequence length after tokenization." "The training dataset will be truncated in block of this size for training." "Default to the model max input length for single sentence inputs (take into account special tokens)." ) } , ) lowerCamelCase__ : bool = field( default=_a , metadata={"help": "Overwrite the cached training and evaluation sets"}) def a_ ( _lowerCAmelCase : DataTrainingArguments , _lowerCAmelCase : PreTrainedTokenizer , _lowerCAmelCase : bool = False , _lowerCAmelCase : Optional[str] = None , ): '''simple docstring''' def _dataset(_lowerCAmelCase : Any , _lowerCAmelCase : Any=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError('You need to set world whole masking and mlm to True for Chinese Whole Word Mask' ) return LineByLineWithRefDataset( tokenizer=_lowerCAmelCase , file_path=_lowerCAmelCase , block_size=args.block_size , ref_path=_lowerCAmelCase , ) return LineByLineTextDataset(tokenizer=_lowerCAmelCase , file_path=_lowerCAmelCase , block_size=args.block_size ) else: return TextDataset( tokenizer=_lowerCAmelCase , file_path=_lowerCAmelCase , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=_lowerCAmelCase , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(_lowerCAmelCase ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def a_ ( ): '''simple docstring''' lowercase__ : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowercase__ , lowercase__ , lowercase__ : List[Any] = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( 'Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file ' 'or remove the --do_eval argument.' ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ' --overwrite_output_dir to overcome.' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , _lowerCAmelCase ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: lowercase__ : List[Any] = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: lowercase__ : Any = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: lowercase__ : Union[str, Any] = CONFIG_MAPPING[model_args.model_type]() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.tokenizer_name: lowercase__ : Dict = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: lowercase__ : int = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( 'You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another' ' script, save it,and load it from here, using --tokenizer_name' ) if model_args.model_name_or_path: lowercase__ : Optional[Any] = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_lowerCAmelCase , cache_dir=model_args.cache_dir , ) else: logger.info('Training new model from scratch' ) lowercase__ : int = AutoModelWithLMHead.from_config(_lowerCAmelCase ) model.resize_token_embeddings(len(_lowerCAmelCase ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( 'BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the' '--mlm flag (masked language modeling).' ) if data_args.block_size <= 0: lowercase__ : List[str] = tokenizer.max_len # Our input block size will be the max possible for the model else: lowercase__ : int = min(data_args.block_size , tokenizer.max_len ) # Get datasets lowercase__ : Tuple = ( get_dataset(_lowerCAmelCase , tokenizer=_lowerCAmelCase , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) lowercase__ : Optional[Any] = ( get_dataset(_lowerCAmelCase , tokenizer=_lowerCAmelCase , evaluate=_lowerCAmelCase , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": lowercase__ : List[Any] = DataCollatorForPermutationLanguageModeling( tokenizer=_lowerCAmelCase , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: lowercase__ : List[str] = DataCollatorForWholeWordMask( tokenizer=_lowerCAmelCase , mlm_probability=data_args.mlm_probability ) else: lowercase__ : str = DataCollatorForLanguageModeling( tokenizer=_lowerCAmelCase , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer lowercase__ : Optional[int] = Trainer( model=_lowerCAmelCase , args=_lowerCAmelCase , data_collator=_lowerCAmelCase , train_dataset=_lowerCAmelCase , eval_dataset=_lowerCAmelCase , prediction_loss_only=_lowerCAmelCase , ) # Training if training_args.do_train: lowercase__ : List[str] = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=_lowerCAmelCase ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowercase__ : List[Any] = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) lowercase__ : Dict = trainer.evaluate() lowercase__ : List[Any] = math.exp(eval_output['eval_loss'] ) lowercase__ : int = {'perplexity': perplexity} lowercase__ : int = os.path.join(training_args.output_dir , 'eval_results_lm.txt' ) if trainer.is_world_master(): with open(_lowerCAmelCase , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , _lowerCAmelCase , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) results.update(_lowerCAmelCase ) return results def a_ ( _lowerCAmelCase : Optional[Any] ): '''simple docstring''' main() if __name__ == "__main__": main()
77
1
'''simple docstring''' import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def UpperCAmelCase_ ( ): with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(__lowerCamelCase ): requests.request("GET" ,"https://huggingface.co" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("GET" ,"https://huggingface.co" ,timeout=1.0 ) @pytest.mark.integration def UpperCAmelCase_ ( ): with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("GET" ,"https://huggingface.co" ) def UpperCAmelCase_ ( ): with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(__lowerCamelCase ): http_head("https://huggingface.co" )
371
'''simple docstring''' import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig lowerCAmelCase : Any ={ '''facebook/maskformer-swin-base-ade''': ( '''https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json''' ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } lowerCAmelCase : int =logging.get_logger(__name__) class a_ ( _lowerCAmelCase ): __A = "maskformer" __A = {"hidden_size": "mask_feature_size"} __A = ["resnet", "swin"] __A = ["detr"] def __init__( self : List[Any] , lowercase : int = 256 , lowercase : int = 256 , lowercase : float = 0.1 , lowercase : bool = False , lowercase : Optional[Dict] = None , lowercase : Optional[Dict] = None , lowercase : float = 0.02 , lowercase : float = 1.0 , lowercase : float = 1.0 , lowercase : float = 1.0 , lowercase : float = 20.0 , lowercase : Optional[bool] = None , **lowercase : Any , ): """simple docstring""" if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k lowercase_ :Any = SwinConfig( image_size=384 , in_channels=3 , patch_size=4 , embed_dim=128 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=["stage1", "stage2", "stage3", "stage4"] , ) if isinstance(lowercase , lowercase ): lowercase_ :Optional[int] = backbone_config.pop("model_type" ) lowercase_ :Optional[int] = CONFIG_MAPPING[backbone_model_type] lowercase_ :int = config_class.from_dict(lowercase ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. ' F'Supported model types: {",".join(self.backbones_supported )}' ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 lowercase_ :Optional[Any] = DetrConfig() else: # verify that the decoder is supported lowercase_ :Tuple = ( decoder_config.pop("model_type" ) if isinstance(lowercase , lowercase ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( F'Transformer Decoder {decoder_type} not supported, please use one of' F' {",".join(self.decoders_supported )}' ) if isinstance(lowercase , lowercase ): lowercase_ :str = CONFIG_MAPPING[decoder_type] lowercase_ :List[str] = config_class.from_dict(lowercase ) lowercase_ :str = backbone_config lowercase_ :Union[str, Any] = decoder_config # main feature dimension for the model lowercase_ :Any = fpn_feature_size lowercase_ :Optional[int] = mask_feature_size # initializer lowercase_ :List[Any] = init_std lowercase_ :Union[str, Any] = init_xavier_std # Hungarian matcher && loss lowercase_ :List[str] = cross_entropy_weight lowercase_ :int = dice_weight lowercase_ :List[str] = mask_weight lowercase_ :Optional[Any] = use_auxiliary_loss lowercase_ :str = no_object_weight lowercase_ :int = output_auxiliary_logits lowercase_ :Optional[Any] = self.decoder_config.encoder_attention_heads lowercase_ :int = self.decoder_config.num_hidden_layers super().__init__(**lowercase ) @classmethod def lowercase__ ( cls : Tuple , lowercase : PretrainedConfig , lowercase : PretrainedConfig , **lowercase : Union[str, Any] ): """simple docstring""" return cls( backbone_config=lowercase , decoder_config=lowercase , **lowercase , ) def lowercase__ ( self : Optional[Any] ): """simple docstring""" lowercase_ :str = copy.deepcopy(self.__dict__ ) lowercase_ :int = self.backbone_config.to_dict() lowercase_ :List[Any] = self.decoder_config.to_dict() lowercase_ :Optional[Any] = self.__class__.model_type return output
147
0
'''simple docstring''' def _lowerCAmelCase ( _UpperCamelCase : dict ) -> bool: """simple docstring""" _SCREAMING_SNAKE_CASE =set() # To detect a back edge, keep track of vertices currently in the recursion stack _SCREAMING_SNAKE_CASE =set() return any( node not in visited and depth_first_search(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) for node in graph ) def _lowerCAmelCase ( _UpperCamelCase : dict , _UpperCamelCase : int , _UpperCamelCase : set , _UpperCamelCase : set ) -> bool: """simple docstring""" visited.add(_UpperCamelCase ) rec_stk.add(_UpperCamelCase ) for node in graph[vertex]: if node not in visited: if depth_first_search(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(_UpperCamelCase ) return False if __name__ == "__main__": from doctest import testmod testmod()
47
'''simple docstring''' import numpy as np from PIL import Image def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape _SCREAMING_SNAKE_CASE =np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix _SCREAMING_SNAKE_CASE =np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr def _lowerCAmelCase ( _UpperCamelCase : np.ndarray , _UpperCamelCase : int , _UpperCamelCase : int ) -> np.ndarray: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # compute the shape of the output matrix _SCREAMING_SNAKE_CASE =(arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape _SCREAMING_SNAKE_CASE =np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix _SCREAMING_SNAKE_CASE =int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image lowerCamelCase : Optional[Any] = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
47
1
"""simple docstring""" from typing import Any class snake_case : def __init__( self : Any , UpperCamelCase__ : Any)-> Dict: '''simple docstring''' __lowerCAmelCase: Tuple = data __lowerCAmelCase: Any = None def __repr__( self : str)-> str: '''simple docstring''' return f"Node({self.data})" class snake_case : def __init__( self : Optional[Any])-> List[Any]: '''simple docstring''' __lowerCAmelCase: Union[str, Any] = None def __iter__( self : Optional[Any])-> Any: '''simple docstring''' __lowerCAmelCase: List[str] = self.head while node: yield node.data __lowerCAmelCase: List[str] = node.next def __len__( self : List[str])-> int: '''simple docstring''' return sum(1 for _ in self) def __repr__( self : List[Any])-> str: '''simple docstring''' return "->".join([str(UpperCamelCase__) for item in self]) def __getitem__( self : Any , UpperCamelCase__ : 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 : List[Any] , UpperCamelCase__ : int , UpperCamelCase__ : Any)-> None: '''simple docstring''' if not 0 <= index < len(self): raise ValueError("list index out of range.") __lowerCAmelCase: List[str] = self.head for _ in range(UpperCamelCase__): __lowerCAmelCase: Optional[int] = current.next __lowerCAmelCase: List[Any] = data def lowercase_ ( self : Union[str, Any] , UpperCamelCase__ : Any)-> None: '''simple docstring''' self.insert_nth(len(self) , UpperCamelCase__) def lowercase_ ( self : str , UpperCamelCase__ : Any)-> None: '''simple docstring''' self.insert_nth(0 , UpperCamelCase__) def lowercase_ ( self : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Any)-> None: '''simple docstring''' if not 0 <= index <= len(self): raise IndexError("list index out of range") __lowerCAmelCase: Union[str, Any] = Node(UpperCamelCase__) if self.head is None: __lowerCAmelCase: Optional[Any] = new_node elif index == 0: __lowerCAmelCase: int = self.head # link new_node to head __lowerCAmelCase: Optional[Any] = new_node else: __lowerCAmelCase: Union[str, Any] = self.head for _ in range(index - 1): __lowerCAmelCase: Dict = temp.next __lowerCAmelCase: int = temp.next __lowerCAmelCase: Any = new_node def lowercase_ ( self : Tuple)-> None: # print every node data '''simple docstring''' print(self) def lowercase_ ( self : Tuple)-> Any: '''simple docstring''' return self.delete_nth(0) def lowercase_ ( self : Dict)-> Any: # delete from tail '''simple docstring''' return self.delete_nth(len(self) - 1) def lowercase_ ( self : Optional[Any] , UpperCamelCase__ : int = 0)-> Any: '''simple docstring''' if not 0 <= index <= len(self) - 1: # test if index is valid raise IndexError("List index out of range.") __lowerCAmelCase: List[Any] = self.head # default first node if index == 0: __lowerCAmelCase: Union[str, Any] = self.head.next else: __lowerCAmelCase: Optional[int] = self.head for _ in range(index - 1): __lowerCAmelCase: Any = temp.next __lowerCAmelCase: Union[str, Any] = temp.next __lowerCAmelCase: int = temp.next.next return delete_node.data def lowercase_ ( self : str)-> bool: '''simple docstring''' return self.head is None def lowercase_ ( self : Any)-> None: '''simple docstring''' __lowerCAmelCase: List[str] = None __lowerCAmelCase: int = self.head while current: # Store the current node's next node. __lowerCAmelCase: Tuple = current.next # Make the current node's next point backwards __lowerCAmelCase: Optional[int] = prev # Make the previous node be the current node __lowerCAmelCase: List[str] = current # Make the current node the next node (to progress iteration) __lowerCAmelCase: List[Any] = next_node # Return prev in order to put the head at the end __lowerCAmelCase: Dict = prev def a__ ( ) -> None: __lowerCAmelCase: Optional[Any] = LinkedList() assert linked_list.is_empty() is True assert str(__SCREAMING_SNAKE_CASE ) == "" 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(1_0 ): assert len(__SCREAMING_SNAKE_CASE ) == i linked_list.insert_nth(__SCREAMING_SNAKE_CASE , i + 1 ) assert str(__SCREAMING_SNAKE_CASE ) == "->".join(str(__SCREAMING_SNAKE_CASE ) for i in range(1 , 1_1 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(1_1 ) assert str(__SCREAMING_SNAKE_CASE ) == "->".join(str(__SCREAMING_SNAKE_CASE ) for i in range(0 , 1_2 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 1_0 assert linked_list.delete_tail() == 1_1 assert len(__SCREAMING_SNAKE_CASE ) == 9 assert str(__SCREAMING_SNAKE_CASE ) == "->".join(str(__SCREAMING_SNAKE_CASE ) for i in range(1 , 1_0 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): __lowerCAmelCase: str = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(__SCREAMING_SNAKE_CASE ) == "->".join(str(__SCREAMING_SNAKE_CASE ) for i in range(-8 , 1 ) ) def a__ ( ) -> None: __lowerCAmelCase: Union[str, Any] = [ -9, 1_0_0, Node(7_7_3_4_5_1_1_2 ), "dlrow olleH", 7, 5_5_5_5, 0, -192.5_5555, "Hello, world!", 77.9, Node(1_0 ), None, None, 12.20, ] __lowerCAmelCase: int = LinkedList() for i in test_input: linked_list.insert_tail(__SCREAMING_SNAKE_CASE ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(__SCREAMING_SNAKE_CASE ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head __lowerCAmelCase: Union[str, Any] = linked_list.delete_head() assert result == -9 assert ( str(__SCREAMING_SNAKE_CASE ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail __lowerCAmelCase: List[str] = linked_list.delete_tail() assert result == 12.2 assert ( str(__SCREAMING_SNAKE_CASE ) == "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 __lowerCAmelCase: List[str] = linked_list.delete_nth(1_0 ) assert result is None assert ( str(__SCREAMING_SNAKE_CASE ) == "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(__SCREAMING_SNAKE_CASE ) == "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(__SCREAMING_SNAKE_CASE ) assert ( str(__SCREAMING_SNAKE_CASE ) == "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(__SCREAMING_SNAKE_CASE ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def a__ ( ) -> str: from doctest import testmod testmod() __lowerCAmelCase: Optional[int] = 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(__SCREAMING_SNAKE_CASE ) print("\nReading/changing Node data using indexing:" ) print(F"Element at Position 1: {linked_list[1]}" ) __lowerCAmelCase: Tuple = input("Enter New Value: " ).strip() print("New list:" ) print(__SCREAMING_SNAKE_CASE ) print(F"length of linked_list is : {len(__SCREAMING_SNAKE_CASE )}" ) if __name__ == "__main__": main()
358
"""simple docstring""" from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 1_0**-1_0 ) -> float: __lowerCAmelCase: Union[str, Any] = a while True: __lowerCAmelCase: Optional[int] = Decimal(__SCREAMING_SNAKE_CASE ) - ( Decimal(eval(__SCREAMING_SNAKE_CASE ) ) / Decimal(eval(str(diff(__SCREAMING_SNAKE_CASE ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__SCREAMING_SNAKE_CASE ) ) < precision: # noqa: S307 return float(__SCREAMING_SNAKE_CASE ) # 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)}''')
108
0
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path lowerCamelCase_ : Optional[Any] = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) lowerCamelCase_ : str = [ord(letter) for letter in string.ascii_lowercase] lowerCamelCase_ : Tuple = {ord(char) for char in VALID_CHARS} lowerCamelCase_ : List[str] = ["""the""", """be""", """to""", """of""", """and""", """in""", """that""", """have"""] def _A ( lowercase , lowercase ): """simple docstring""" a ="" a =42 a =42 a =42 for keychar, cipherchar in zip(cycle(snake_case__ ) , snake_case__ ): a =cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(snake_case__ ) return decoded def _A ( lowercase ): """simple docstring""" a =[] for key in product(snake_case__ , repeat=3 ): a =try_key(snake_case__ , snake_case__ ) if encoded is not None: possibles.append(snake_case__ ) return possibles def _A ( lowercase , lowercase ): """simple docstring""" return [possible for possible in possibles if common_word in possible.lower()] def _A ( lowercase = "p059_cipher.txt" ): """simple docstring""" a =42 a =42 a =42 a =42 a =Path(snake_case__ ).parent.joinpath(snake_case__ ).read_text(encoding='''utf-8''' ) a =[int(snake_case__ ) for number in data.strip().split(''',''' )] a =filter_valid_chars(snake_case__ ) for common_word in COMMON_WORDS: a =filter_common_word(snake_case__ , snake_case__ ) if len(snake_case__ ) == 1: break a =possibles[0] return sum(ord(snake_case__ ) for char in decoded_text ) if __name__ == "__main__": print(F'{solution() = }')
81
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## A_ = 16 A_ = 32 def UpperCAmelCase__ (snake_case__ : Accelerator , snake_case__ : int = 16 ): """simple docstring""" _snake_case : Optional[Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _snake_case : Any = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(snake_case__ : Any ): # max_length=None => use the model max length (it's actually the default) _snake_case : Any = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _snake_case : List[Any] = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _snake_case : int = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(snake_case__ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. _snake_case : Optional[int] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _snake_case : str = 16 elif accelerator.mixed_precision != "no": _snake_case : Optional[int] = 8 else: _snake_case : Optional[int] = None return tokenizer.pad( snake_case__ , padding="""longest""" , max_length=snake_case__ , pad_to_multiple_of=snake_case__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _snake_case : Optional[int] = DataLoader( tokenized_datasets["""train"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) _snake_case : Dict = DataLoader( tokenized_datasets["""validation"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders A_ = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any ): """simple docstring""" if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , snake_case__ ) == "1": _snake_case : List[Any] = 2 # Initialize accelerator _snake_case : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _snake_case : Tuple = config["""lr"""] _snake_case : str = int(config["""num_epochs"""] ) _snake_case : Union[str, Any] = int(config["""seed"""] ) _snake_case : Union[str, Any] = int(config["""batch_size"""] ) _snake_case : List[str] = evaluate.load("""glue""" , """mrpc""" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case__ ) def inner_training_loop(snake_case__ : Union[str, Any] ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _snake_case : List[Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=snake_case__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _snake_case : Tuple = model.to(accelerator.device ) # Instantiate optimizer _snake_case : str = AdamW(params=model.parameters() , lr=snake_case__ ) _snake_case , _snake_case : Optional[int] = get_dataloaders(snake_case__ , snake_case__ ) # Instantiate scheduler _snake_case : str = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=1_00 , num_training_steps=(len(snake_case__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : List[str] = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Now we train the model for epoch in range(snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _snake_case : int = model(**snake_case__ ) _snake_case : str = outputs.loss accelerator.backward(snake_case__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _snake_case : int = model(**snake_case__ ) _snake_case : Optional[Any] = outputs.logits.argmax(dim=-1 ) _snake_case , _snake_case : Tuple = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) _snake_case : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , snake_case__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=snake_case__ , default=snake_case__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) _snake_case : Dict = parser.parse_args() _snake_case : int = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
64
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) lowerCamelCase = {"""configuration_beit""": ["""BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BeitConfig""", """BeitOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = ["""BeitFeatureExtractor"""] lowerCamelCase = ["""BeitImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ """BEIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BeitForImageClassification""", """BeitForMaskedImageModeling""", """BeitForSemanticSegmentation""", """BeitModel""", """BeitPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ """FlaxBeitForImageClassification""", """FlaxBeitForMaskedImageModeling""", """FlaxBeitModel""", """FlaxBeitPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
353
def lowerCamelCase_ ( _a = 4_000_000 ): """simple docstring""" lowerCAmelCase__ : str = [] lowerCAmelCase__ , lowerCAmelCase__ : Optional[Any] = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(_a ) lowerCAmelCase__ , lowerCAmelCase__ : Union[str, Any] = b, a + b return sum(_a ) if __name__ == "__main__": print(f'''{solution() = }''')
211
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def a_ ( _A ) -> str: """simple docstring""" snake_case__ = [2, 2, 6, 2] if "tiny" in model_name else [2, 2, 18, 2] snake_case__ = True if "large" in model_name or "huge" in model_name else False snake_case__ = True if "large" in model_name or "huge" in model_name else False snake_case__ = True if "large" in model_name or "huge" in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: snake_case__ = [3, 3, 3, 3] snake_case__ = [5, 5, 5, 5] elif "fl4" in model_name: snake_case__ = [4, 4, 4, 4] snake_case__ = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: snake_case__ = [3, 3, 3, 3] if "lrf" in model_name: snake_case__ = [3, 3, 3, 3] else: snake_case__ = [2, 2, 2, 2] if "tiny" in model_name: snake_case__ = 96 elif "small" in model_name: snake_case__ = 96 elif "base" in model_name: snake_case__ = 128 elif "large" in model_name: snake_case__ = 192 elif "xlarge" in model_name: snake_case__ = 256 elif "huge" in model_name: snake_case__ = 352 # set label information snake_case__ = "huggingface/label-files" if "large" in model_name or "huge" in model_name: snake_case__ = "imagenet-22k-id2label.json" else: snake_case__ = "imagenet-1k-id2label.json" snake_case__ = json.load(open(hf_hub_download(__snake_case , __snake_case , repo_type='dataset' ) , 'r' ) ) snake_case__ = {int(__snake_case ): v for k, v in idalabel.items()} snake_case__ = {v: k for k, v in idalabel.items()} snake_case__ = FocalNetConfig( embed_dim=__snake_case , depths=__snake_case , focal_levels=__snake_case , focal_windows=__snake_case , use_conv_embed=__snake_case , idalabel=__snake_case , labelaid=__snake_case , use_post_layernorm=__snake_case , use_layerscale=__snake_case , ) return config def a_ ( _A ) -> List[Any]: """simple docstring""" if "patch_embed.proj" in name: snake_case__ = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: snake_case__ = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: snake_case__ = "encoder." + name if "encoder.layers" in name: snake_case__ = name.replace('encoder.layers' , 'encoder.stages' ) if "downsample.proj" in name: snake_case__ = name.replace('downsample.proj' , 'downsample.projection' ) if "blocks" in name: snake_case__ = name.replace('blocks' , 'layers' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: snake_case__ = name.replace('modulation.f' , 'modulation.projection_in' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: snake_case__ = name.replace('modulation.h' , 'modulation.projection_context' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: snake_case__ = name.replace('modulation.proj' , 'modulation.projection_out' ) if name == "norm.weight": snake_case__ = "layernorm.weight" if name == "norm.bias": snake_case__ = "layernorm.bias" if "head" in name: snake_case__ = name.replace('head' , 'classifier' ) else: snake_case__ = "focalnet." + name return name def a_ ( _A , _A , _A=False ) -> Dict: """simple docstring""" # fmt: off snake_case__ = { "focalnet-tiny": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth", "focalnet-tiny-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth", "focalnet-small": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth", "focalnet-small-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth", "focalnet-base": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth", "focalnet-base-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth", "focalnet-large-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth", "focalnet-large-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth", "focalnet-xlarge-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth", "focalnet-xlarge-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth", } # fmt: on snake_case__ = model_name_to_url[model_name] print('Checkpoint URL: ' , __snake_case ) snake_case__ = torch.hub.load_state_dict_from_url(__snake_case , map_location='cpu' )["model"] # rename keys for key in state_dict.copy().keys(): snake_case__ = state_dict.pop(__snake_case ) snake_case__ = val snake_case__ = get_focalnet_config(__snake_case ) snake_case__ = FocalNetForImageClassification(__snake_case ) model.eval() # load state dict model.load_state_dict(__snake_case ) # verify conversion snake_case__ = "http://images.cocodataset.org/val2017/000000039769.jpg" snake_case__ = BitImageProcessor( do_resize=__snake_case , size={'shortest_edge': 256} , resample=PILImageResampling.BILINEAR , do_center_crop=__snake_case , crop_size=224 , do_normalize=__snake_case , image_mean=__snake_case , image_std=__snake_case , ) snake_case__ = Image.open(requests.get(__snake_case , stream=__snake_case ).raw ) snake_case__ = processor(images=__snake_case , return_tensors='pt' ) snake_case__ = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) snake_case__ = image_transforms(__snake_case ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , __snake_case , atol=1e-4 ) snake_case__ = model(**__snake_case ) snake_case__ = outputs.logits.argmax(-1 ).item() print('Predicted class:' , model.config.idalabel[predicted_class_idx] ) print('First values of logits:' , outputs.logits[0, :3] ) if model_name == "focalnet-tiny": snake_case__ = torch.tensor([0.2166, -0.4368, 0.2191] ) elif model_name == "focalnet-tiny-lrf": snake_case__ = torch.tensor([1.1669, 0.0125, -0.1695] ) elif model_name == "focalnet-small": snake_case__ = torch.tensor([0.4917, -0.0430, 0.1341] ) elif model_name == "focalnet-small-lrf": snake_case__ = torch.tensor([-0.2588, -0.5342, -0.2331] ) elif model_name == "focalnet-base": snake_case__ = torch.tensor([-0.1655, -0.4090, -0.1730] ) elif model_name == "focalnet-base-lrf": snake_case__ = torch.tensor([0.5306, -0.0483, -0.3928] ) assert torch.allclose(outputs.logits[0, :3] , __snake_case , atol=1e-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f'''Saving model and processor of {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(__snake_case ) processor.save_pretrained(__snake_case ) if push_to_hub: print(f'''Pushing model and processor of {model_name} to the hub...''' ) model.push_to_hub(f'''{model_name}''' ) processor.push_to_hub(f'''{model_name}''' ) if __name__ == "__main__": __UpperCamelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""focalnet-tiny""", type=str, help="""Name of the FocalNet model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to push the model and processor to the hub.""", ) __UpperCamelCase : Optional[int] = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
307
"""simple docstring""" import argparse import torch from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert from transformers.utils import logging logging.set_verbosity_info() def __magic_name__ ( __snake_case : Optional[Any] , __snake_case : Dict , __snake_case : Any ) -> Any: # Initialise PyTorch model lowercase : Union[str, Any] = RemBertConfig.from_json_file(__snake_case ) print("Building PyTorch model from configuration: {}".format(str(__snake_case ) ) ) lowercase : str = RemBertModel(__snake_case ) # Load weights from tf checkpoint load_tf_weights_in_rembert(__snake_case , __snake_case , __snake_case ) # Save pytorch-model print("Save PyTorch model to {}".format(__snake_case ) ) torch.save(model.state_dict() , __snake_case ) if __name__ == "__main__": _A : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--rembert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained RemBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) _A : List[str] = parser.parse_args() convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)
202
0
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer _snake_case = logging.get_logger(__name__) _snake_case = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} _snake_case = { '''vocab_file''': { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json''' ), }, } _snake_case = { '''vocab_file''': { '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json''' ), }, } _snake_case = { '''vocab_file''': { '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json''' ), }, } _snake_case = { '''facebook/dpr-ctx_encoder-single-nq-base''': 512, '''facebook/dpr-ctx_encoder-multiset-base''': 512, } _snake_case = { '''facebook/dpr-question_encoder-single-nq-base''': 512, '''facebook/dpr-question_encoder-multiset-base''': 512, } _snake_case = { '''facebook/dpr-reader-single-nq-base''': 512, '''facebook/dpr-reader-multiset-base''': 512, } _snake_case = { '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True}, } _snake_case = { '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True}, } _snake_case = { '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True}, } class lowerCAmelCase ( a__ ): __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION __lowerCamelCase = DPRContextEncoderTokenizer class lowerCAmelCase ( a__ ): __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION __lowerCamelCase = DPRQuestionEncoderTokenizer _snake_case = collections.namedtuple( """DPRSpanPrediction""", ["""span_score""", """relevance_score""", """doc_id""", """start_index""", """end_index""", """text"""] ) _snake_case = collections.namedtuple("""DPRReaderOutput""", ["""start_logits""", """end_logits""", """relevance_logits"""]) _snake_case = r''' Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `\'tf\'`: Return TensorFlow `tf.constant` objects. - `\'pt\'`: Return PyTorch `torch.Tensor` objects. - `\'np\'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer\'s default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Return: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. ''' @add_start_docstrings(a__ ) class lowerCAmelCase : def __call__( self :List[str] , _lowercase :Tuple , _lowercase :List[str] = None , _lowercase :List[Any] = None , _lowercase :int = False , _lowercase :Dict = False , _lowercase :str = None , _lowercase :List[Any] = None , _lowercase :str = None , **_lowercase :List[Any] , ): '''simple docstring''' if titles is None and texts is None: return super().__call__( _lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=_lowerCamelCase , return_tensors=_lowerCamelCase , return_attention_mask=_lowerCamelCase , **_lowerCamelCase , ) elif titles is None or texts is None: lowercase__ = titles if texts is None else texts return super().__call__( _lowerCamelCase , _lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , max_length=_lowerCamelCase , return_tensors=_lowerCamelCase , return_attention_mask=_lowerCamelCase , **_lowerCamelCase , ) lowercase__ = titles if not isinstance(_lowerCamelCase , _lowerCamelCase ) else [titles] lowercase__ = texts if not isinstance(_lowerCamelCase , _lowerCamelCase ) else [texts] lowercase__ = len(_lowerCamelCase ) lowercase__ = questions if not isinstance(_lowerCamelCase , _lowerCamelCase ) else [questions] * n_passages assert len(_lowerCamelCase ) == len( _lowerCamelCase ), f'''There should be as many titles than texts but got {len(_lowerCamelCase )} titles and {len(_lowerCamelCase )} texts.''' lowercase__ = super().__call__(_lowerCamelCase , _lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase )['''input_ids'''] lowercase__ = super().__call__(_lowerCamelCase , add_special_tokens=_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase )['''input_ids'''] lowercase__ = { '''input_ids''': [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_lowerCamelCase , _lowerCamelCase ) ] } if return_attention_mask is not False: lowercase__ = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) lowercase__ = attention_mask return self.pad(_lowerCamelCase , padding=_lowerCamelCase , max_length=_lowerCamelCase , return_tensors=_lowerCamelCase ) def UpperCAmelCase ( self :Optional[Any] , _lowercase :List[str] , _lowercase :List[Any] , _lowercase :Tuple = 16 , _lowercase :Dict = 64 , _lowercase :Any = 4 , ): '''simple docstring''' lowercase__ = reader_input['''input_ids'''] lowercase__ = reader_output[:3] lowercase__ = len(_lowerCamelCase ) lowercase__ = sorted(range(_lowerCamelCase ) , reverse=_lowerCamelCase , key=relevance_logits.__getitem__ ) lowercase__ = [] for doc_id in sorted_docs: lowercase__ = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence lowercase__ = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: lowercase__ = sequence_ids.index(self.pad_token_id ) else: lowercase__ = len(_lowerCamelCase ) lowercase__ = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_lowerCamelCase , top_spans=_lowerCamelCase , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_lowerCamelCase , start_index=_lowerCamelCase , end_index=_lowerCamelCase , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_lowerCamelCase ) >= num_spans: break return nbest_spans_predictions[:num_spans] def UpperCAmelCase ( self :Optional[Any] , _lowercase :List[Any] , _lowercase :Optional[int] , _lowercase :List[str] , _lowercase :int , ): '''simple docstring''' lowercase__ = [] for start_index, start_score in enumerate(_lowerCamelCase ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) lowercase__ = sorted(_lowerCamelCase , key=lambda _lowercase : x[1] , reverse=_lowerCamelCase ) lowercase__ = [] for (start_index, end_index), score in scores: assert start_index <= end_index, f'''Wrong span indices: [{start_index}:{end_index}]''' lowercase__ = end_index - start_index + 1 assert length <= max_answer_length, f'''Span is too long: {length} > {max_answer_length}''' if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_lowerCamelCase ) == top_spans: break return chosen_span_intervals @add_end_docstrings(a__ ) class lowerCAmelCase ( a__ , a__ ): __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = READER_PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = READER_PRETRAINED_INIT_CONFIGURATION __lowerCamelCase = ['input_ids', 'attention_mask'] __lowerCamelCase = DPRReaderTokenizer
369
from __future__ import annotations from collections import deque class lowerCAmelCase : def __init__( self :List[Any] , _lowercase :list[str] ): '''simple docstring''' lowercase__ = [] self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []} ) for keyword in keywords: self.add_keyword(_lowercase ) self.set_fail_transitions() def UpperCAmelCase ( self :str , _lowercase :int , _lowercase :str ): '''simple docstring''' for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def UpperCAmelCase ( self :List[str] , _lowercase :str ): '''simple docstring''' lowercase__ = 0 for character in keyword: lowercase__ = self.find_next_state(_lowercase , _lowercase ) 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 ) lowercase__ = len(self.adlist ) - 1 else: lowercase__ = next_state self.adlist[current_state]["output"].append(_lowercase ) def UpperCAmelCase ( self :int ): '''simple docstring''' lowercase__ = deque() for node in self.adlist[0]["next_states"]: q.append(_lowercase ) lowercase__ = 0 while q: lowercase__ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(_lowercase ) lowercase__ = self.adlist[r]["fail_state"] while ( self.find_next_state(_lowercase , self.adlist[child]["value"] ) is None and state != 0 ): lowercase__ = self.adlist[state]["fail_state"] lowercase__ = self.find_next_state( _lowercase , self.adlist[child]["value"] ) if self.adlist[child]["fail_state"] is None: lowercase__ = 0 lowercase__ = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] ) def UpperCAmelCase ( self :Optional[Any] , _lowercase :str ): '''simple docstring''' lowercase__ = {} # returns a dict with keywords and list of its occurrences lowercase__ = 0 for i in range(len(_lowercase ) ): while ( self.find_next_state(_lowercase , string[i] ) is None and current_state != 0 ): lowercase__ = self.adlist[current_state]["fail_state"] lowercase__ = self.find_next_state(_lowercase , string[i] ) if next_state is None: lowercase__ = 0 else: lowercase__ = next_state for key in self.adlist[current_state]["output"]: if key not in result: lowercase__ = [] result[key].append(i - len(_lowercase ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
201
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase_ = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['EncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['TFEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = ['FlaxEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
16
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __A : '''simple docstring''' lowerCAmelCase : List[str] lowerCAmelCase : Optional[str] = None # Automatically constructed lowerCAmelCase : ClassVar[str] = "dict" lowerCAmelCase : ClassVar[Any] = None lowerCAmelCase : str = field(default="Translation" ,init=A_ ,repr=A_ ) def __call__( self : List[str] ) -> Any: """simple docstring""" return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def UpperCAmelCase ( self : List[str] ) -> Union["FeatureType", Dict[str, "FeatureType"]]: """simple docstring""" from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __A : '''simple docstring''' lowerCAmelCase : Optional[List] = None lowerCAmelCase : Optional[int] = None lowerCAmelCase : Optional[str] = None # Automatically constructed lowerCAmelCase : ClassVar[str] = "dict" lowerCAmelCase : ClassVar[Any] = None lowerCAmelCase : str = field(default="TranslationVariableLanguages" ,init=A_ ,repr=A_ ) def UpperCAmelCase ( self : List[Any] ) -> Optional[int]: """simple docstring""" lowercase__ : Optional[int] = sorted(set(self.languages ) ) if self.languages else None lowercase__ : Dict = len(self.languages ) if self.languages else None def __call__( self : List[Any] ) -> List[Any]: """simple docstring""" return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def UpperCAmelCase ( self : Dict ,_snake_case : Tuple ) -> int: """simple docstring""" lowercase__ : List[Any] = set(self.languages ) if self.languages and set(_snake_case ) - lang_set: raise ValueError( f"""Some languages in example ({", ".join(sorted(set(_snake_case ) - lang_set ) )}) are not in valid set ({", ".join(_snake_case )}).""" ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. lowercase__ : str = [] for lang, text in translation_dict.items(): if isinstance(_snake_case ,_snake_case ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. lowercase__ , lowercase__ : Optional[Any] = zip(*sorted(_snake_case ) ) return {"language": languages, "translation": translations} def UpperCAmelCase ( self : List[Any] ) -> Union["FeatureType", Dict[str, "FeatureType"]]: """simple docstring""" from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
16
1
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class lowerCamelCase (SCREAMING_SNAKE_CASE__ ): """simple docstring""" lowerCamelCase__ = 42 lowerCamelCase__ = 42 class lowerCamelCase (nn.Module ): """simple docstring""" lowerCamelCase__ = 42 lowerCamelCase__ = (1_6, 3_2, 9_6, 2_5_6) lowerCamelCase__ = jnp.floataa def __A ( self : Optional[int] ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) SCREAMING_SNAKE_CASE_ = [] for i in range(len(self.block_out_channels ) - 1 ): SCREAMING_SNAKE_CASE_ = self.block_out_channels[i] SCREAMING_SNAKE_CASE_ = self.block_out_channels[i + 1] SCREAMING_SNAKE_CASE_ = nn.Conv( __magic_name__ , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(__magic_name__ ) SCREAMING_SNAKE_CASE_ = nn.Conv( __magic_name__ , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(__magic_name__ ) SCREAMING_SNAKE_CASE_ = blocks SCREAMING_SNAKE_CASE_ = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : List[str] , __magic_name__ : Any ) -> List[Any]: SCREAMING_SNAKE_CASE_ = self.conv_in(__magic_name__ ) SCREAMING_SNAKE_CASE_ = nn.silu(__magic_name__ ) for block in self.blocks: SCREAMING_SNAKE_CASE_ = block(__magic_name__ ) SCREAMING_SNAKE_CASE_ = nn.silu(__magic_name__ ) SCREAMING_SNAKE_CASE_ = self.conv_out(__magic_name__ ) return embedding @flax_register_to_config class lowerCamelCase (nn.Module , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): """simple docstring""" lowerCamelCase__ = 3_2 lowerCamelCase__ = 4 lowerCamelCase__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) lowerCamelCase__ = False lowerCamelCase__ = (3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0) lowerCamelCase__ = 2 lowerCamelCase__ = 8 lowerCamelCase__ = None lowerCamelCase__ = 1_2_8_0 lowerCamelCase__ = 0.0 lowerCamelCase__ = False lowerCamelCase__ = jnp.floataa lowerCamelCase__ = True lowerCamelCase__ = 0 lowerCamelCase__ = "rgb" lowerCamelCase__ = (1_6, 3_2, 9_6, 2_5_6) def __A ( self : Optional[int] , __magic_name__ : jax.random.KeyArray ) -> FrozenDict: # init input tensors SCREAMING_SNAKE_CASE_ = (1, self.in_channels, self.sample_size, self.sample_size) SCREAMING_SNAKE_CASE_ = jnp.zeros(__magic_name__ , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE_ = jnp.ones((1,) , dtype=jnp.intaa ) SCREAMING_SNAKE_CASE_ = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE_ = (1, 3, self.sample_size * 8, self.sample_size * 8) SCREAMING_SNAKE_CASE_ = jnp.zeros(__magic_name__ , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = jax.random.split(__magic_name__ ) SCREAMING_SNAKE_CASE_ = {"params": params_rng, "dropout": dropout_rng} return self.init(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ )["params"] def __A ( self : str ) -> str: SCREAMING_SNAKE_CASE_ = self.block_out_channels SCREAMING_SNAKE_CASE_ = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. SCREAMING_SNAKE_CASE_ = self.num_attention_heads or self.attention_head_dim # input SCREAMING_SNAKE_CASE_ = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time SCREAMING_SNAKE_CASE_ = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) SCREAMING_SNAKE_CASE_ = FlaxTimestepEmbedding(__magic_name__ , dtype=self.dtype ) SCREAMING_SNAKE_CASE_ = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) SCREAMING_SNAKE_CASE_ = self.only_cross_attention if isinstance(__magic_name__ , __magic_name__ ): SCREAMING_SNAKE_CASE_ = (only_cross_attention,) * len(self.down_block_types ) if isinstance(__magic_name__ , __magic_name__ ): SCREAMING_SNAKE_CASE_ = (num_attention_heads,) * len(self.down_block_types ) # down SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = block_out_channels[0] SCREAMING_SNAKE_CASE_ = nn.Conv( __magic_name__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__magic_name__ ) for i, down_block_type in enumerate(self.down_block_types ): SCREAMING_SNAKE_CASE_ = output_channel SCREAMING_SNAKE_CASE_ = block_out_channels[i] SCREAMING_SNAKE_CASE_ = i == len(__magic_name__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": SCREAMING_SNAKE_CASE_ = FlaxCrossAttnDownBlockaD( in_channels=__magic_name__ , out_channels=__magic_name__ , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: SCREAMING_SNAKE_CASE_ = FlaxDownBlockaD( in_channels=__magic_name__ , out_channels=__magic_name__ , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(__magic_name__ ) for _ in range(self.layers_per_block ): SCREAMING_SNAKE_CASE_ = nn.Conv( __magic_name__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__magic_name__ ) if not is_final_block: SCREAMING_SNAKE_CASE_ = nn.Conv( __magic_name__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__magic_name__ ) SCREAMING_SNAKE_CASE_ = down_blocks SCREAMING_SNAKE_CASE_ = controlnet_down_blocks # mid SCREAMING_SNAKE_CASE_ = block_out_channels[-1] SCREAMING_SNAKE_CASE_ = FlaxUNetMidBlockaDCrossAttn( in_channels=__magic_name__ , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) SCREAMING_SNAKE_CASE_ = nn.Conv( __magic_name__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Dict , __magic_name__ : int , __magic_name__ : str , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[int] , __magic_name__ : float = 1.0 , __magic_name__ : bool = True , __magic_name__ : bool = False , ) -> Union[FlaxControlNetOutput, Tuple]: SCREAMING_SNAKE_CASE_ = self.controlnet_conditioning_channel_order if channel_order == "bgr": SCREAMING_SNAKE_CASE_ = jnp.flip(__magic_name__ , axis=1 ) # 1. time if not isinstance(__magic_name__ , jnp.ndarray ): SCREAMING_SNAKE_CASE_ = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(__magic_name__ , jnp.ndarray ) and len(timesteps.shape ) == 0: SCREAMING_SNAKE_CASE_ = timesteps.astype(dtype=jnp.floataa ) SCREAMING_SNAKE_CASE_ = jnp.expand_dims(__magic_name__ , 0 ) SCREAMING_SNAKE_CASE_ = self.time_proj(__magic_name__ ) SCREAMING_SNAKE_CASE_ = self.time_embedding(__magic_name__ ) # 2. pre-process SCREAMING_SNAKE_CASE_ = jnp.transpose(__magic_name__ , (0, 2, 3, 1) ) SCREAMING_SNAKE_CASE_ = self.conv_in(__magic_name__ ) SCREAMING_SNAKE_CASE_ = jnp.transpose(__magic_name__ , (0, 2, 3, 1) ) SCREAMING_SNAKE_CASE_ = self.controlnet_cond_embedding(__magic_name__ ) sample += controlnet_cond # 3. down SCREAMING_SNAKE_CASE_ = (sample,) for down_block in self.down_blocks: if isinstance(__magic_name__ , __magic_name__ ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = down_block(__magic_name__ , __magic_name__ , __magic_name__ , deterministic=not train ) else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = down_block(__magic_name__ , __magic_name__ , deterministic=not train ) down_block_res_samples += res_samples # 4. mid SCREAMING_SNAKE_CASE_ = self.mid_block(__magic_name__ , __magic_name__ , __magic_name__ , deterministic=not train ) # 5. contronet blocks SCREAMING_SNAKE_CASE_ = () for down_block_res_sample, controlnet_block in zip(__magic_name__ , self.controlnet_down_blocks ): SCREAMING_SNAKE_CASE_ = controlnet_block(__magic_name__ ) controlnet_down_block_res_samples += (down_block_res_sample,) SCREAMING_SNAKE_CASE_ = controlnet_down_block_res_samples SCREAMING_SNAKE_CASE_ = self.controlnet_mid_block(__magic_name__ ) # 6. scaling SCREAMING_SNAKE_CASE_ = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=__magic_name__ , mid_block_res_sample=__magic_name__ )
305
from __future__ import annotations import numpy as np def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = np.shape(__UpperCamelCase ) if rows != columns: SCREAMING_SNAKE_CASE_ = ( "'table' has to be of square shaped array but got a " F'''{rows}x{columns} array:\n{table}''' ) raise ValueError(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = np.zeros((rows, columns) ) SCREAMING_SNAKE_CASE_ = np.zeros((rows, columns) ) for i in range(__UpperCamelCase ): for j in range(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = sum(lower[i][k] * upper[k][j] for k in range(__UpperCamelCase ) ) if upper[j][j] == 0: raise ArithmeticError("No LU decomposition exists" ) SCREAMING_SNAKE_CASE_ = (table[i][j] - total) / upper[j][j] SCREAMING_SNAKE_CASE_ = 1 for j in range(__UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = sum(lower[i][k] * upper[k][j] for k in range(__UpperCamelCase ) ) SCREAMING_SNAKE_CASE_ = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
305
1
"""simple docstring""" from collections.abc import Callable def a__ ( SCREAMING_SNAKE_CASE : Callable[[float], float] , SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : float ): '''simple docstring''' lowerCAmelCase : float = a lowerCAmelCase : float = b if function(SCREAMING_SNAKE_CASE ) == 0: # one of the a or b is a root for the function return a elif function(SCREAMING_SNAKE_CASE ) == 0: return b elif ( function(SCREAMING_SNAKE_CASE ) * function(SCREAMING_SNAKE_CASE ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("could not find root in given interval." ) else: lowerCAmelCase : float = start + (end - start) / 2.0 while abs(start - mid ) > 1_0**-7: # until precisely equals to 10^-7 if function(SCREAMING_SNAKE_CASE ) == 0: return mid elif function(SCREAMING_SNAKE_CASE ) * function(SCREAMING_SNAKE_CASE ) < 0: lowerCAmelCase : str = mid else: lowerCAmelCase : str = mid lowerCAmelCase : List[Any] = start + (end - start) / 2.0 return mid def a__ ( SCREAMING_SNAKE_CASE : float ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1_000)) import doctest doctest.testmod()
108
"""simple docstring""" import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ = '''▁''' lowerCAmelCase__ = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( lowercase , unittest.TestCase ): """simple docstring""" a : str =BigBirdTokenizer a : Union[str, Any] =BigBirdTokenizerFast a : Tuple =True a : Any =True def lowercase__ ( self ): """simple docstring""" super().setUp() lowerCAmelCase : str = self.tokenizer_class(snake_case__ , keep_accents=snake_case__ ) tokenizer.save_pretrained(self.tmpdirname ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : str = "<s>" lowerCAmelCase : Optional[int] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case__ ) , snake_case__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case__ ) , snake_case__ ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Dict = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "[MASK]" ) self.assertEqual(len(snake_case__ ) , 1_004 ) def lowercase__ ( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def lowercase__ ( self ): """simple docstring""" if not self.test_rust_tokenizer: return lowerCAmelCase : Tuple = self.get_tokenizer() lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() lowerCAmelCase : Tuple = "I was born in 92000, and this is falsé." lowerCAmelCase : Optional[int] = tokenizer.tokenize(snake_case__ ) lowerCAmelCase : int = rust_tokenizer.tokenize(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) lowerCAmelCase : Tuple = tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) lowerCAmelCase : int = rust_tokenizer.encode(snake_case__ , add_special_tokens=snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) lowerCAmelCase : List[Any] = self.get_rust_tokenizer() lowerCAmelCase : Tuple = tokenizer.encode(snake_case__ ) lowerCAmelCase : List[Any] = rust_tokenizer.encode(snake_case__ ) self.assertListEqual(snake_case__ , snake_case__ ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Any = BigBirdTokenizer(snake_case__ , keep_accents=snake_case__ ) lowerCAmelCase : Union[str, Any] = tokenizer.tokenize("This is a test" ) self.assertListEqual(snake_case__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(snake_case__ ) , [285, 46, 10, 170, 382] , ) lowerCAmelCase : Any = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( snake_case__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCAmelCase : str = tokenizer.convert_tokens_to_ids(snake_case__ ) self.assertListEqual( snake_case__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) lowerCAmelCase : List[str] = tokenizer.convert_ids_to_tokens(snake_case__ ) self.assertListEqual( snake_case__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def lowercase__ ( self ): """simple docstring""" return BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) @slow def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : List[Any] = "Hello World!" lowerCAmelCase : Any = [65, 18_536, 2_260, 101, 66] self.assertListEqual(snake_case__ , self.big_tokenizer.encode(snake_case__ ) ) @slow def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Union[str, Any] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) # fmt: off lowerCAmelCase : List[str] = [65, 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, 66] # noqa: E231 # fmt: on self.assertListEqual(snake_case__ , self.big_tokenizer.encode(snake_case__ ) ) @require_torch @slow def lowercase__ ( self ): """simple docstring""" import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence lowerCAmelCase : Dict = list(self.big_tokenizer.get_vocab().keys() )[:10] lowerCAmelCase : int = " ".join(snake_case__ ) lowerCAmelCase : Dict = self.big_tokenizer.encode_plus(snake_case__ , return_tensors="pt" , return_token_type_ids=snake_case__ ) lowerCAmelCase : Any = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=snake_case__ ) lowerCAmelCase : str = BigBirdConfig(attention_type="original_full" ) lowerCAmelCase : Any = BigBirdModel(snake_case__ ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**snake_case__ ) model(**snake_case__ ) @slow def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : List[str] = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) lowerCAmelCase : Union[str, Any] = tokenizer.decode(tokenizer("Paris is the [MASK]." ).input_ids ) self.assertTrue(decoded_text == "[CLS] Paris is the[MASK].[SEP]" ) @slow def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Any = {"input_ids": [[65, 39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114, 66], [65, 448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=snake_case__ , model_name="google/bigbird-roberta-base" , revision="215c99f1600e06f83acce68422f2035b2b5c3510" , )
108
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy lowercase__ : int = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE (a__ ): def __init__( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase): '''simple docstring''' __A : Any = feature_size __A : int = sampling_rate __A : str = padding_value __A : int = kwargs.pop('padding_side' , 'right') __A : List[str] = kwargs.pop('return_attention_mask' , _UpperCAmelCase) super().__init__(**_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase = True , _UpperCAmelCase = None , _UpperCAmelCase = False , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , ): '''simple docstring''' if isinstance(_UpperCAmelCase , (list, tuple)) and isinstance(processed_features[0] , (dict, BatchFeature)): __A : Dict = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' F' to this method that includes {self.model_input_names[0]}, but you provided' F' {list(processed_features.keys())}') __A : Tuple = processed_features[self.model_input_names[0]] __A : str = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(_UpperCAmelCase) == 0: if return_attention_mask: __A : Optional[Any] = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __A : Tuple = required_input[0] if isinstance(_UpperCAmelCase , (list, tuple)): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __A : Optional[Any] = 0 while len(required_input[index]) == 0: index += 1 if index < len(_UpperCAmelCase): __A : List[Any] = required_input[index][0] if return_tensors is None: if is_tf_tensor(_UpperCAmelCase): __A : str = 'tf' elif is_torch_tensor(_UpperCAmelCase): __A : Optional[Any] = 'pt' elif isinstance(_UpperCAmelCase , (int, float, list, tuple, np.ndarray)): __A : Any = 'np' else: raise ValueError( F'type of {first_element} unknown: {type(_UpperCAmelCase)}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.') for key, value in processed_features.items(): if isinstance(value[0] , (int, float)): __A : Union[str, Any] = to_numpy(_UpperCAmelCase) else: __A : str = [to_numpy(_UpperCAmelCase) for v in value] # Convert padding_strategy in PaddingStrategy __A : Optional[int] = self._get_padding_strategies(padding=_UpperCAmelCase , max_length=_UpperCAmelCase) __A : Dict = processed_features[self.model_input_names[0]] __A : List[str] = len(_UpperCAmelCase) if not all(len(_UpperCAmelCase) == batch_size for v in processed_features.values()): raise ValueError('Some items in the output dictionary have a different batch size than others.') __A : Any = [] for i in range(_UpperCAmelCase): __A : Union[str, Any] = {k: v[i] for k, v in processed_features.items()} # truncation __A : List[Any] = self._truncate( _UpperCAmelCase , max_length=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , truncation=_UpperCAmelCase , ) truncated_inputs.append(_UpperCAmelCase) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __A : Optional[int] = max(len(input_slice[self.model_input_names[0]]) for input_slice in truncated_inputs) __A : Union[str, Any] = PaddingStrategy.MAX_LENGTH __A : int = {} for i in range(_UpperCAmelCase): # padding __A : Optional[int] = self._pad( truncated_inputs[i] , max_length=_UpperCAmelCase , padding_strategy=_UpperCAmelCase , pad_to_multiple_of=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , ) for key, value in outputs.items(): if key not in batch_outputs: __A : List[Any] = [] if value.dtype is np.dtype(np.floataa): __A : Any = value.astype(np.floataa) batch_outputs[key].append(_UpperCAmelCase) return BatchFeature(_UpperCAmelCase , tensor_type=_UpperCAmelCase) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = PaddingStrategy.DO_NOT_PAD , _UpperCAmelCase = None , _UpperCAmelCase = None , ): '''simple docstring''' __A : Union[str, Any] = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __A : int = len(_UpperCAmelCase) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __A : List[Any] = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __A : Optional[Any] = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(_UpperCAmelCase) < max_length if return_attention_mask and "attention_mask" not in processed_features: __A : Any = np.ones(len(_UpperCAmelCase) , dtype=np.intaa) if needs_to_be_padded: __A : Tuple = max_length - len(_UpperCAmelCase) if self.padding_side == "right": if return_attention_mask: __A : int = np.pad( processed_features['attention_mask'] , (0, difference)) __A : List[Any] = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __A : Any = np.pad( _UpperCAmelCase , _UpperCAmelCase , 'constant' , constant_values=self.padding_value) elif self.padding_side == "left": if return_attention_mask: __A : List[str] = np.pad( processed_features['attention_mask'] , (difference, 0)) __A : Any = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __A : str = np.pad( _UpperCAmelCase , _UpperCAmelCase , 'constant' , constant_values=self.padding_value) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side)) return processed_features def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = None , ): '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.') __A : Dict = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __A : Optional[Any] = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __A : str = len(_UpperCAmelCase) > max_length if needs_to_be_truncated: __A : Dict = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __A : int = processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase=False , _UpperCAmelCase=None): '''simple docstring''' if padding is not False: if padding is True: __A : Optional[int] = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(_UpperCAmelCase , _UpperCAmelCase): __A : int = PaddingStrategy(_UpperCAmelCase) elif isinstance(_UpperCAmelCase , _UpperCAmelCase): __A : Union[str, Any] = padding else: __A : Optional[int] = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined') # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.') return padding_strategy
190
'''simple docstring''' import argparse lowercase__ : Any = '''docs/source/_static/js/custom.js''' def _lowerCAmelCase ( __snake_case : Union[str, Any] ) -> str: with open(__snake_case , encoding='utf-8' , newline='\n' ) as f: __A : Optional[Any] = f.readlines() __A : List[str] = 0 # First let's put the right version while not lines[index].startswith('const stableVersion =' ): index += 1 __A : Tuple = f'const stableVersion = "v{version}"\n' # Then update the dictionary while not lines[index].startswith('const versionMapping = {' ): index += 1 # We go until the end while not lines[index].startswith('}' ): index += 1 # We add the new version at the end lines[index - 1] += f' "v{version}": "v{version}",\n' with open(__snake_case , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(__snake_case ) if __name__ == "__main__": lowercase__ : Optional[Any] = argparse.ArgumentParser() parser.add_argument('''--version''', help='''Release version.''') lowercase__ : List[str] = parser.parse_args() update_custom_js(args.version)
190
1
"""simple docstring""" from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class UpperCAmelCase_ ( _a): lowerCamelCase__ : Optional[int] = ["vqvae"] def __init__( self , a , a , a , a , ) -> Optional[int]: super().__init__() self.register_modules(unet=a , scheduler=a , mel=a , vqvae=a ) def _UpperCAmelCase ( self ) -> int: return 5_0 if isinstance(self.scheduler , a ) else 1_0_0_0 @torch.no_grad() def __call__( self , a = 1 , a = None , a = None , a = 0 , a = 0 , a = None , a = None , a = 0 , a = 0 , a = None , a = 0 , a = None , a = None , a=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: lowercase__ : Optional[Any] = steps or self.get_default_steps() self.scheduler.set_timesteps(a ) lowercase__ : Dict = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: lowercase__ : str = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: lowercase__ : Union[str, Any] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=a , device=self.device , ) lowercase__ : Dict = noise lowercase__ : str = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(a , a ) lowercase__ : str = self.mel.audio_slice_to_image(a ) lowercase__ : Tuple = np.frombuffer(input_image.tobytes() , dtype='uint8' ).reshape( (input_image.height, input_image.width) ) lowercase__ : List[str] = (input_image / 2_5_5) * 2 - 1 lowercase__ : Optional[Any] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: lowercase__ : List[str] = self.vqvae.encode(torch.unsqueeze(a , 0 ) ).latent_dist.sample( generator=a )[0] lowercase__ : Tuple = self.vqvae.config.scaling_factor * input_images if start_step > 0: lowercase__ : Union[str, Any] = self.scheduler.add_noise(a , a , self.scheduler.timesteps[start_step - 1] ) lowercase__ : Any = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) lowercase__ : Optional[int] = int(mask_start_secs * pixels_per_second ) lowercase__ : Optional[int] = int(mask_end_secs * pixels_per_second ) lowercase__ : Optional[Any] = self.scheduler.add_noise(a , a , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , a ): lowercase__ : Any = self.unet(a , a , a )['sample'] else: lowercase__ : Optional[int] = self.unet(a , a )['sample'] if isinstance(self.scheduler , a ): lowercase__ : Union[str, Any] = self.scheduler.step( model_output=a , timestep=a , sample=a , eta=a , generator=a , )['prev_sample'] else: lowercase__ : int = self.scheduler.step( model_output=a , timestep=a , sample=a , generator=a , )['prev_sample'] if mask is not None: if mask_start > 0: lowercase__ : int = mask[:, step, :, :mask_start] if mask_end > 0: lowercase__ : Optional[int] = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance lowercase__ : Optional[Any] = 1 / self.vqvae.config.scaling_factor * images lowercase__ : Dict = self.vqvae.decode(a )['sample'] lowercase__ : Any = (images / 2 + 0.5).clamp(0 , 1 ) lowercase__ : List[str] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() lowercase__ : Optional[int] = (images * 2_5_5).round().astype('uint8' ) lowercase__ : List[str] = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(a , mode='RGB' ).convert('L' ) for _ in images) ) lowercase__ : int = [self.mel.image_to_audio(a ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(a )[:, np.newaxis, :] ) , **ImagePipelineOutput(a ) ) @torch.no_grad() def _UpperCAmelCase ( self , a , a = 5_0 ) -> np.ndarray: assert isinstance(self.scheduler , a ) self.scheduler.set_timesteps(a ) lowercase__ : Optional[Any] = np.array( [np.frombuffer(image.tobytes() , dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] ) lowercase__ : Any = (sample / 2_5_5) * 2 - 1 lowercase__ : Optional[int] = torch.Tensor(a ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): lowercase__ : Any = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps lowercase__ : List[Any] = self.scheduler.alphas_cumprod[t] lowercase__ : Tuple = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) lowercase__ : int = 1 - alpha_prod_t lowercase__ : int = self.unet(a , a )['sample'] lowercase__ : Optional[int] = (1 - alpha_prod_t_prev) ** 0.5 * model_output lowercase__ : Optional[Any] = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) lowercase__ : Union[str, Any] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def _UpperCAmelCase ( a , a , a ) -> torch.Tensor: lowercase__ : List[Any] = acos(torch.dot(torch.flatten(a ) , torch.flatten(a ) ) / torch.norm(a ) / torch.norm(a ) ) return sin((1 - alpha) * theta ) * xa / sin(a ) + sin(alpha * theta ) * xa / sin(a )
77
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = "naver-clova-ix/donut-base-finetuned-docvqa" _UpperCamelCase : Dict = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) _UpperCamelCase : Optional[int] = "document_qa" _UpperCamelCase : Any = AutoProcessor _UpperCamelCase : Union[str, Any] = VisionEncoderDecoderModel _UpperCamelCase : Union[str, Any] = ["image", "text"] _UpperCamelCase : List[str] = ["text"] def __init__( self , *a__ , **a__ ): if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*a__ , **a__ ) def __A ( self , a__ , a__ ): _lowerCAmelCase : Optional[int] = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" _lowerCAmelCase : Dict = task_prompt.replace("""{user_input}""" , a__ ) _lowerCAmelCase : str = self.pre_processor.tokenizer( a__ , add_special_tokens=a__ , return_tensors="""pt""" ).input_ids _lowerCAmelCase : Dict = self.pre_processor(a__ , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __A ( self , a__ ): return self.model.generate( inputs["""pixel_values"""].to(self.device ) , decoder_input_ids=inputs["""decoder_input_ids"""].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=a__ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=a__ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=a__ , ).sequences def __A ( self , a__ ): _lowerCAmelCase : Tuple = self.pre_processor.batch_decode(a__ )[0] _lowerCAmelCase : int = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) _lowerCAmelCase : List[str] = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) _lowerCAmelCase : List[str] = re.sub(r"""<.*?>""" , """""" , a__ , count=1 ).strip() # remove first task start token _lowerCAmelCase : List[str] = self.pre_processor.tokenajson(a__ ) return sequence["answer"]
44
0
import string import numpy def __lowerCamelCase (UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int ): return b if a == 0 else greatest_common_divisor(b % a , A_ ) class lowercase : lowercase__ : List[Any] = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) lowercase__ : Optional[Any] = numpy.vectorize(lambda a : x % 36 ) lowercase__ : Dict = numpy.vectorize(a_ ) def __init__( self : Any , _UpperCamelCase : numpy.ndarray ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.modulus(lowercase_ ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key SCREAMING_SNAKE_CASE = encrypt_key.shape[0] def __snake_case( self : Any , _UpperCamelCase : str ) -> Optional[Any]: '''simple docstring''' return self.key_string.index(lowercase_ ) def __snake_case( self : Any , _UpperCamelCase : int ) -> List[str]: '''simple docstring''' return self.key_string[round(lowercase_ )] def __snake_case( self : str ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: SCREAMING_SNAKE_CASE = det % len(self.key_string ) SCREAMING_SNAKE_CASE = len(self.key_string ) if greatest_common_divisor(lowercase_ , len(self.key_string ) ) != 1: SCREAMING_SNAKE_CASE = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(lowercase_ ) def __snake_case( self : Dict , _UpperCamelCase : str ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = [char for char in text.upper() if char in self.key_string] SCREAMING_SNAKE_CASE = chars[-1] while len(lowercase_ ) % self.break_key != 0: chars.append(lowercase_ ) return "".join(lowercase_ ) def __snake_case( self : Tuple , _UpperCamelCase : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.process_text(text.upper() ) SCREAMING_SNAKE_CASE = '''''' for i in range(0 , len(lowercase_ ) - self.break_key + 1 , self.break_key ): SCREAMING_SNAKE_CASE = text[i : i + self.break_key] SCREAMING_SNAKE_CASE = [self.replace_letters(lowercase_ ) for char in batch] SCREAMING_SNAKE_CASE = numpy.array([vec] ).T SCREAMING_SNAKE_CASE = self.modulus(self.encrypt_key.dot(lowercase_ ) ).T.tolist()[ 0 ] SCREAMING_SNAKE_CASE = ''''''.join( self.replace_digits(lowercase_ ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def __snake_case( self : str ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: SCREAMING_SNAKE_CASE = det % len(self.key_string ) SCREAMING_SNAKE_CASE = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: SCREAMING_SNAKE_CASE = i break SCREAMING_SNAKE_CASE = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(lowercase_ ) ) def __snake_case( self : List[Any] , _UpperCamelCase : str ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = self.make_decrypt_key() SCREAMING_SNAKE_CASE = self.process_text(text.upper() ) SCREAMING_SNAKE_CASE = '''''' for i in range(0 , len(lowercase_ ) - self.break_key + 1 , self.break_key ): SCREAMING_SNAKE_CASE = text[i : i + self.break_key] SCREAMING_SNAKE_CASE = [self.replace_letters(lowercase_ ) for char in batch] SCREAMING_SNAKE_CASE = numpy.array([vec] ).T SCREAMING_SNAKE_CASE = self.modulus(decrypt_key.dot(lowercase_ ) ).T.tolist()[0] SCREAMING_SNAKE_CASE = ''''''.join( self.replace_digits(lowercase_ ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def __lowerCamelCase (): SCREAMING_SNAKE_CASE = int(input("Enter the order of the encryption key: " ) ) SCREAMING_SNAKE_CASE = [] print("Enter each row of the encryption key with space separated integers" ) for _ in range(A_ ): SCREAMING_SNAKE_CASE = [int(A_ ) for x in input().split()] hill_matrix.append(A_ ) SCREAMING_SNAKE_CASE = HillCipher(numpy.array(A_ ) ) print("Would you like to encrypt or decrypt some text? (1 or 2)" ) SCREAMING_SNAKE_CASE = input("\n1. Encrypt\n2. Decrypt\n" ) if option == "1": SCREAMING_SNAKE_CASE = input("What text would you like to encrypt?: " ) print("Your encrypted text is:" ) print(hc.encrypt(A_ ) ) elif option == "2": SCREAMING_SNAKE_CASE = input("What text would you like to decrypt?: " ) print("Your decrypted text is:" ) print(hc.decrypt(A_ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
358
from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) def __lowerCamelCase (UpperCAmelCase__ : str , UpperCAmelCase__ : Dict ): try: with open(UpperCAmelCase__ , "rb" ) as flax_state_f: SCREAMING_SNAKE_CASE = from_bytes(UpperCAmelCase__ , flax_state_f.read() ) except UnpicklingError as e: try: with open(UpperCAmelCase__ ) as f: if f.read().startswith("version" ): raise OSError( "You seem to have cloned a repository without having git-lfs installed. Please" " install git-lfs and run `git lfs install` followed by `git lfs pull` in the" " folder you cloned." ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(F"Unable to convert {model_file} to Flax deserializable object. " ) return load_flax_weights_in_pytorch_model(UpperCAmelCase__ , UpperCAmelCase__ ) def __lowerCamelCase (UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[Any] ): try: import torch # noqa: F401 except ImportError: logger.error( "Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise # check if we have bf16 weights SCREAMING_SNAKE_CASE = flatten_dict(jax.tree_util.tree_map(lambda UpperCAmelCase__ : x.dtype == jnp.bfloataa , UpperCAmelCase__ ) ).values() if any(UpperCAmelCase__ ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` " "before loading those in PyTorch model." ) SCREAMING_SNAKE_CASE = jax.tree_util.tree_map( lambda UpperCAmelCase__ : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , UpperCAmelCase__ ) SCREAMING_SNAKE_CASE = "" SCREAMING_SNAKE_CASE = flatten_dict(UpperCAmelCase__ , sep="." ) SCREAMING_SNAKE_CASE = pt_model.state_dict() # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE = flax_key_tuple.split("." ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: SCREAMING_SNAKE_CASE = flax_key_tuple_array[:-1] + ["weight"] SCREAMING_SNAKE_CASE = jnp.transpose(UpperCAmelCase__ , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": SCREAMING_SNAKE_CASE = flax_key_tuple_array[:-1] + ["weight"] SCREAMING_SNAKE_CASE = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": SCREAMING_SNAKE_CASE = flax_key_tuple_array[:-1] + ["weight"] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(UpperCAmelCase__ ): SCREAMING_SNAKE_CASE = ( flax_key_tuple_string.replace("_0" , ".0" ) .replace("_1" , ".1" ) .replace("_2" , ".2" ) .replace("_3" , ".3" ) .replace("_4" , ".4" ) .replace("_5" , ".5" ) .replace("_6" , ".6" ) .replace("_7" , ".7" ) .replace("_8" , ".8" ) .replace("_9" , ".9" ) ) SCREAMING_SNAKE_CASE = ".".join(UpperCAmelCase__ ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected " F"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}." ) else: # add weight to pytorch dict SCREAMING_SNAKE_CASE = np.asarray(UpperCAmelCase__ ) if not isinstance(UpperCAmelCase__ , np.ndarray ) else flax_tensor SCREAMING_SNAKE_CASE = torch.from_numpy(UpperCAmelCase__ ) # remove from missing keys missing_keys.remove(UpperCAmelCase__ ) else: # weight is not expected by PyTorch model unexpected_keys.append(UpperCAmelCase__ ) pt_model.load_state_dict(UpperCAmelCase__ ) # re-transform missing_keys to list SCREAMING_SNAKE_CASE = list(UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 0: logger.warning( "Some weights of the Flax model were not used when initializing the PyTorch model" F" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing" F" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture" " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This" F" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect" " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a" " FlaxBertForSequenceClassification model)." ) if len(UpperCAmelCase__ ) > 0: logger.warning( F"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly" F" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to" " use it for predictions and inference." ) return pt_model
206
0
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: List[str] ) -> Dict: '''simple docstring''' A__ = [False] * len(SCREAMING_SNAKE_CASE_ ) A__ = [] queue.append(SCREAMING_SNAKE_CASE_ ) A__ = True while queue: A__ = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(SCREAMING_SNAKE_CASE_ ) A__ = True A__ = u return visited[t] def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Dict ) -> Union[str, Any]: '''simple docstring''' A__ = [-1] * (len(SCREAMING_SNAKE_CASE_ )) A__ = 0 while bfs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A__ = float("Inf" ) A__ = sink while s != source: # Find the minimum value in select path A__ = min(SCREAMING_SNAKE_CASE_ , graph[parent[s]][s] ) A__ = parent[s] max_flow += path_flow A__ = sink while v != source: A__ = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow A__ = parent[v] return max_flow lowerCAmelCase__ = [ [0, 1_6, 1_3, 0, 0, 0], [0, 0, 1_0, 1_2, 0, 0], [0, 4, 0, 0, 1_4, 0], [0, 0, 9, 0, 0, 2_0], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] lowerCAmelCase__ , lowerCAmelCase__ = 0, 5 print(ford_fulkerson(graph, source, sink))
68
import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers __A : Union[str, Any] = '''python tqdm regex requests packaging filelock numpy tokenizers'''.split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append('''dataclasses''') if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append('''importlib_metadata''') for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(F'can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py') def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase=None ) -> Dict: '''simple docstring''' require_version(deps[pkg], _UpperCAmelCase )
138
0
import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = [] if isinstance(lowerCamelCase__ , lowerCamelCase__ ): for v in tree.values(): shapes.extend(_fetch_dims(lowerCamelCase__ ) ) elif isinstance(lowerCamelCase__ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(lowerCamelCase__ ) ) elif isinstance(lowerCamelCase__ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("Not supported" ) return shapes @torch.jit.ignore def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = [] for d in reversed(lowerCamelCase__ ): idx.append(flat_idx % d ) lowerCamelCase_ = flat_idx // d return tuple(reversed(lowerCamelCase__ ) ) @torch.jit.ignore def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = None , ): # start_edges and end_edges both indicate whether, starting from any given # dimension, the start/end index is at the top/bottom edge of the # corresponding tensor, modeled as a tree def reduce_edge_list(lowerCamelCase__ ) -> None: lowerCamelCase_ = True for i in range(len(lowerCamelCase__ ) ): lowerCamelCase_ = -1 * (i + 1) l[reversed_idx] &= tally lowerCamelCase_ = l[reversed_idx] if start_edges is None: lowerCamelCase_ = [s == 0 for s in start] reduce_edge_list(lowerCamelCase__ ) if end_edges is None: lowerCamelCase_ = [e == (d - 1) for e, d in zip(lowerCamelCase__ , lowerCamelCase__ )] reduce_edge_list(lowerCamelCase__ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(lowerCamelCase__ ) == 0: return [()] elif len(lowerCamelCase__ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] lowerCamelCase_ = [] lowerCamelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(lowerCamelCase__ , lowerCamelCase__ ): if s == e: path_list.append(slice(lowerCamelCase__ , s + 1 ) ) else: break lowerCamelCase_ = tuple(lowerCamelCase__ ) lowerCamelCase_ = len(lowerCamelCase__ ) # start == end, and we're done if divergence_idx == len(lowerCamelCase__ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowerCamelCase_ = start[divergence_idx] return tuple( path + (slice(lowerCamelCase__ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowerCamelCase_ = end[divergence_idx] return tuple( path + (slice(lowerCamelCase__ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) lowerCamelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = t.shape[:no_batch_dims] lowerCamelCase_ = list(_flat_idx_to_idx(lowerCamelCase__ , lowerCamelCase__ ) ) # _get_minimal_slice_set is inclusive lowerCamelCase_ = list(_flat_idx_to_idx(flat_end - 1 , lowerCamelCase__ ) ) # Get an ordered list of slices to perform lowerCamelCase_ = _get_minimal_slice_set( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) lowerCamelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = False , lowerCamelCase__ = None , lowerCamelCase__ = False , ): if not (len(lowerCamelCase__ ) > 0): raise ValueError("Must provide at least one input" ) lowerCamelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(lowerCamelCase__ )] lowerCamelCase_ = tuple([max(lowerCamelCase__ ) for s in zip(*lowerCamelCase__ )] ) def _prep_inputs(lowerCamelCase__ ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: lowerCamelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) lowerCamelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: lowerCamelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t lowerCamelCase_ = tensor_tree_map(_prep_inputs , lowerCamelCase__ ) lowerCamelCase_ = None if _out is not None: lowerCamelCase_ = tensor_tree_map(lambda lowerCamelCase__ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) lowerCamelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d lowerCamelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(lowerCamelCase__ ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t lowerCamelCase_ = 0 lowerCamelCase_ = prepped_outputs for _ in range(lowerCamelCase__ ): # Chunk the input if not low_mem: lowerCamelCase_ = _select_chunk else: lowerCamelCase_ = partial( _chunk_slice , flat_start=lowerCamelCase__ , flat_end=min(lowerCamelCase__ , i + chunk_size ) , no_batch_dims=len(lowerCamelCase__ ) , ) lowerCamelCase_ = tensor_tree_map(lowerCamelCase__ , lowerCamelCase__ ) # Run the layer on the chunk lowerCamelCase_ = layer(**lowerCamelCase__ ) # Allocate space for the output if out is None: lowerCamelCase_ = tensor_tree_map(lambda lowerCamelCase__ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , lowerCamelCase__ ) # Put the chunk in its pre-allocated space if isinstance(lowerCamelCase__ , lowerCamelCase__ ): def assign(lowerCamelCase__ , lowerCamelCase__ ) -> None: for k, v in da.items(): if isinstance(lowerCamelCase__ , lowerCamelCase__ ): assign(lowerCamelCase__ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: lowerCamelCase_ = da[k] assign(lowerCamelCase__ , lowerCamelCase__ ) elif isinstance(lowerCamelCase__ , lowerCamelCase__ ): for xa, xa in zip(lowerCamelCase__ , lowerCamelCase__ ): if _add_into_out: xa[i : i + chunk_size] += xa else: lowerCamelCase_ = xa elif isinstance(lowerCamelCase__ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: lowerCamelCase_ = output_chunk else: raise ValueError("Not supported" ) i += chunk_size lowerCamelCase_ = tensor_tree_map(lambda lowerCamelCase__ : t.view(orig_batch_dims + t.shape[1:] ) , lowerCamelCase__ ) return out class _SCREAMING_SNAKE_CASE : def __init__( self , lowercase = 512 , ) -> str: lowerCamelCase_ = max_chunk_size lowerCamelCase_ = None lowerCamelCase_ = None def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase , lowercase ) -> int: logging.info("Tuning chunk size..." ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size lowerCamelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] lowerCamelCase_ = [c for c in candidates if c > min_chunk_size] lowerCamelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(lowercase ) -> bool: try: with torch.no_grad(): fn(*lowercase , chunk_size=lowercase ) return True except RuntimeError: return False lowerCamelCase_ = 0 lowerCamelCase_ = len(lowercase ) - 1 while i > min_viable_chunk_size_index: lowerCamelCase_ = test_chunk_size(candidates[i] ) if not viable: lowerCamelCase_ = (min_viable_chunk_size_index + i) // 2 else: lowerCamelCase_ = i lowerCamelCase_ = (i + len(lowercase ) - 1) // 2 return candidates[min_viable_chunk_size_index] def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase ) -> bool: lowerCamelCase_ = True for aa, aa in zip(lowercase , lowercase ): assert type(lowercase ) == type(lowercase ) if isinstance(lowercase , (list, tuple) ): consistent &= self._compare_arg_caches(lowercase , lowercase ) elif isinstance(lowercase , lowercase ): lowerCamelCase_ = [v for _, v in sorted(aa.items() , key=lambda lowercase : x[0] )] lowerCamelCase_ = [v for _, v in sorted(aa.items() , key=lambda lowercase : x[0] )] consistent &= self._compare_arg_caches(lowercase , lowercase ) else: consistent &= aa == aa return consistent def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase , lowercase , ) -> int: lowerCamelCase_ = True lowerCamelCase_ = tree_map(lambda lowercase : a.shape if isinstance(lowercase , torch.Tensor ) else a , lowercase , lowercase ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(lowercase ) lowerCamelCase_ = self._compare_arg_caches(self.cached_arg_data , lowercase ) else: # Otherwise, we can reuse the precomputed value lowerCamelCase_ = False if not consistent: lowerCamelCase_ = self._determine_favorable_chunk_size( lowercase , lowercase , lowercase , ) lowerCamelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
47
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() __A =logging.get_logger(__name__) def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: lowerCamelCase_ = 1_9_2 lowerCamelCase_ = 7_6_8 lowerCamelCase_ = 1_2 lowerCamelCase_ = 3 lowerCamelCase_ = [8_0_0, 1_3_3_3] lowerCamelCase_ = False elif yolos_name == "yolos_s_dWr": lowerCamelCase_ = 3_3_0 lowerCamelCase_ = 1_4 lowerCamelCase_ = 6 lowerCamelCase_ = 1_3_2_0 elif "yolos_s" in yolos_name: lowerCamelCase_ = 3_8_4 lowerCamelCase_ = 1_5_3_6 lowerCamelCase_ = 1_2 lowerCamelCase_ = 6 elif "yolos_b" in yolos_name: lowerCamelCase_ = [8_0_0, 1_3_4_4] lowerCamelCase_ = 9_1 lowerCamelCase_ = "huggingface/label-files" lowerCamelCase_ = "coco-detection-id2label.json" lowerCamelCase_ = json.load(open(hf_hub_download(lowerCamelCase__ , lowerCamelCase__ , repo_type="dataset" ) , "r" ) ) lowerCamelCase_ = {int(lowerCamelCase__ ): v for k, v in idalabel.items()} lowerCamelCase_ = idalabel lowerCamelCase_ = {v: k for k, v in idalabel.items()} return config def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = False ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCamelCase_ = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) lowerCamelCase_ = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict lowerCamelCase_ = in_proj_weight[: config.hidden_size, :] lowerCamelCase_ = in_proj_bias[: config.hidden_size] lowerCamelCase_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCamelCase_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCamelCase_ = in_proj_weight[-config.hidden_size :, :] lowerCamelCase_ = in_proj_bias[-config.hidden_size :] def lowerCamelCase_ ( lowerCamelCase__ ): if "backbone" in name: lowerCamelCase_ = name.replace("backbone" , "vit" ) if "cls_token" in name: lowerCamelCase_ = name.replace("cls_token" , "embeddings.cls_token" ) if "det_token" in name: lowerCamelCase_ = name.replace("det_token" , "embeddings.detection_tokens" ) if "mid_pos_embed" in name: lowerCamelCase_ = name.replace("mid_pos_embed" , "encoder.mid_position_embeddings" ) if "pos_embed" in name: lowerCamelCase_ = name.replace("pos_embed" , "embeddings.position_embeddings" ) if "patch_embed.proj" in name: lowerCamelCase_ = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "blocks" in name: lowerCamelCase_ = name.replace("blocks" , "encoder.layer" ) if "attn.proj" in name: lowerCamelCase_ = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: lowerCamelCase_ = name.replace("attn" , "attention.self" ) if "norm1" in name: lowerCamelCase_ = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: lowerCamelCase_ = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: lowerCamelCase_ = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: lowerCamelCase_ = name.replace("mlp.fc2" , "output.dense" ) if "class_embed" in name: lowerCamelCase_ = name.replace("class_embed" , "class_labels_classifier" ) if "bbox_embed" in name: lowerCamelCase_ = name.replace("bbox_embed" , "bbox_predictor" ) if "vit.norm" in name: lowerCamelCase_ = name.replace("vit.norm" , "vit.layernorm" ) return name def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): for key in orig_state_dict.copy().keys(): lowerCamelCase_ = orig_state_dict.pop(lowerCamelCase__ ) if "qkv" in key: lowerCamelCase_ = key.split("." ) lowerCamelCase_ = int(key_split[2] ) lowerCamelCase_ = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: lowerCamelCase_ = val[:dim, :] lowerCamelCase_ = val[ dim : dim * 2, : ] lowerCamelCase_ = val[-dim:, :] else: lowerCamelCase_ = val[:dim] lowerCamelCase_ = val[dim : dim * 2] lowerCamelCase_ = val[-dim:] else: lowerCamelCase_ = val return orig_state_dict def lowerCamelCase_ ( ): lowerCamelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCamelCase_ = Image.open(requests.get(lowerCamelCase__ , stream=lowerCamelCase__ ).raw ) return im @torch.no_grad() def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = False ): lowerCamelCase_ = get_yolos_config(lowerCamelCase__ ) # load original state_dict lowerCamelCase_ = torch.load(lowerCamelCase__ , map_location="cpu" )["model"] # load 🤗 model lowerCamelCase_ = YolosForObjectDetection(lowerCamelCase__ ) model.eval() lowerCamelCase_ = convert_state_dict(lowerCamelCase__ , lowerCamelCase__ ) model.load_state_dict(lowerCamelCase__ ) # Check outputs on an image, prepared by YolosImageProcessor lowerCamelCase_ = 8_0_0 if yolos_name != "yolos_ti" else 5_1_2 lowerCamelCase_ = YolosImageProcessor(format="coco_detection" , size=lowerCamelCase__ ) lowerCamelCase_ = image_processor(images=prepare_img() , return_tensors="pt" ) lowerCamelCase_ = model(**lowerCamelCase__ ) lowerCamelCase_ , lowerCamelCase_ = outputs.logits, outputs.pred_boxes lowerCamelCase_ , lowerCamelCase_ = None, None if yolos_name == "yolos_ti": lowerCamelCase_ = torch.tensor( [[-39.50_22, -11.98_20, -17.68_88], [-29.95_74, -9.97_69, -17.76_91], [-42.32_81, -20.72_00, -30.62_94]] ) lowerCamelCase_ = torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": lowerCamelCase_ = torch.tensor( [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]] ) lowerCamelCase_ = torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": lowerCamelCase_ = torch.tensor( [[-36.22_20, -14.43_85, -23.54_57], [-35.69_70, -14.75_83, -21.39_35], [-31.59_39, -13.60_42, -16.80_49]] ) lowerCamelCase_ = torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": lowerCamelCase_ = torch.tensor( [[-42.86_68, -24.10_49, -41.16_90], [-34.74_56, -14.12_74, -24.91_94], [-33.78_98, -12.19_46, -25.64_95]] ) lowerCamelCase_ = torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": lowerCamelCase_ = torch.tensor( [[-40.60_64, -24.30_84, -32.64_47], [-55.19_90, -30.77_19, -35.58_77], [-51.43_11, -33.35_07, -35.64_62]] ) lowerCamelCase_ = torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(F'Unknown yolos_name: {yolos_name}' ) assert torch.allclose(logits[0, :3, :3] , lowerCamelCase__ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , lowerCamelCase__ , atol=1e-4 ) Path(lowerCamelCase__ ).mkdir(exist_ok=lowerCamelCase__ ) print(F'Saving model {yolos_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCamelCase__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowerCamelCase__ ) if push_to_hub: lowerCamelCase_ = { "yolos_ti": "yolos-tiny", "yolos_s_200_pre": "yolos-small", "yolos_s_300_pre": "yolos-small-300", "yolos_s_dWr": "yolos-small-dwr", "yolos_base": "yolos-base", } print("Pushing to the hub..." ) lowerCamelCase_ = model_mapping[yolos_name] image_processor.push_to_hub(lowerCamelCase__ , organization="hustvl" ) model.push_to_hub(lowerCamelCase__ , organization="hustvl" ) if __name__ == "__main__": __A =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--yolos_name''', default='''yolos_s_200_pre''', type=str, help=( '''Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',''' ''' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.''' ), ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original state dict (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) __A =parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
47
1
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class a ( unittest.TestCase ): def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=9_9 , _lowerCamelCase=3_2 , _lowerCamelCase=5 , _lowerCamelCase=4 , _lowerCamelCase=3_7 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=5_1_2 , _lowerCamelCase=1_6 , _lowerCamelCase=2 , _lowerCamelCase=0.0_2 , _lowerCamelCase=4 , ): lowercase = parent lowercase = batch_size lowercase = seq_length lowercase = is_training lowercase = use_attention_mask lowercase = use_token_type_ids lowercase = use_labels lowercase = vocab_size lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = intermediate_size lowercase = hidden_act lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = max_position_embeddings lowercase = type_vocab_size lowercase = type_sequence_label_size lowercase = initializer_range lowercase = num_choices def UpperCamelCase_ ( self ): lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase = None if self.use_attention_mask: lowercase = random_attention_mask([self.batch_size, self.seq_length] ) lowercase = None if self.use_token_type_ids: lowercase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCAmelCase_ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase_ ( self ): lowercase = self.prepare_config_and_inputs() lowercase = config_and_inputs lowercase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class a ( SCREAMING_SNAKE_CASE__, unittest.TestCase ): UpperCAmelCase_ : Optional[int] =True UpperCAmelCase_ : Union[str, Any] =( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase_ ( self ): lowercase = FlaxRoFormerModelTester(self ) @slow def UpperCamelCase_ ( self ): for model_class_name in self.all_model_classes: lowercase = model_class_name.from_pretrained('junnyu/roformer_chinese_small' , from_pt=lowerCAmelCase_ ) lowercase = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCAmelCase_ ) @require_flax class a ( unittest.TestCase ): @slow def UpperCamelCase_ ( self ): lowercase = FlaxRoFormerForMaskedLM.from_pretrained('junnyu/roformer_chinese_base' ) lowercase = jnp.array([[0, 1, 2, 3, 4, 5]] ) lowercase = model(lowerCAmelCase_ )[0] lowercase = 5_0_0_0_0 lowercase = (1, 6, vocab_size) self.assertEqual(output.shape , lowerCAmelCase_ ) lowercase = jnp.array( [[[-0.1_2_0_5, -1.0_2_6_5, 0.2_9_2_2], [-1.5_1_3_4, 0.1_9_7_4, 0.1_5_1_9], [-5.0_1_3_5, -3.9_0_0_3, -0.8_4_0_4]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , lowerCAmelCase_ , atol=1e-4 ) )
220
import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Optional[int] ): """simple docstring""" return F"""gaussian_noise_s={seed}_shape={'_'.join([str(lowerCAmelCase_ ) for s in shape] )}.npy""" def __magic_name__ ( self : Tuple ): """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Any=0 , lowerCAmelCase_ : Tuple=(4, 4, 6_4, 6_4) , lowerCAmelCase_ : List[str]=False ): """simple docstring""" _A: List[str] = jnp.bfloataa if fpaa else jnp.floataa _A: Optional[int] = jnp.array(load_hf_numpy(self.get_file_format(lowerCAmelCase_ , lowerCAmelCase_ ) ) , dtype=lowerCAmelCase_ ) return image def __magic_name__ ( self : Optional[Any] , lowerCAmelCase_ : Optional[int]=False , lowerCAmelCase_ : Optional[Any]="CompVis/stable-diffusion-v1-4" ): """simple docstring""" _A: Tuple = jnp.bfloataa if fpaa else jnp.floataa _A: str = '''bf16''' if fpaa else None _A , _A: Union[str, Any] = FlaxUNetaDConditionModel.from_pretrained( lowerCAmelCase_ , subfolder='''unet''' , dtype=lowerCAmelCase_ , revision=lowerCAmelCase_ ) return model, params def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Optional[int]=0 , lowerCAmelCase_ : str=(4, 7_7, 7_6_8) , lowerCAmelCase_ : Dict=False ): """simple docstring""" _A: Optional[int] = jnp.bfloataa if fpaa else jnp.floataa _A: Union[str, Any] = jnp.array(load_hf_numpy(self.get_file_format(lowerCAmelCase_ , lowerCAmelCase_ ) ) , dtype=lowerCAmelCase_ ) return hidden_states @parameterized.expand( [ # fmt: off [8_3, 4, [-0.2323, -0.1304, 0.0813, -0.3093, -0.0919, -0.1571, -0.1125, -0.5806]], [1_7, 0.55, [-0.0831, -0.2443, 0.0901, -0.0919, 0.3396, 0.0103, -0.3743, 0.0701]], [8, 0.89, [-0.4863, 0.0859, 0.0875, -0.1658, 0.9199, -0.0114, 0.4839, 0.4639]], [3, 1_0_0_0, [-0.5649, 0.2402, -0.5518, 0.1248, 1.1328, -0.2443, -0.0325, -1.0078]], # fmt: on ] ) def __magic_name__ ( self : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Any ): """simple docstring""" _A , _A: Optional[Any] = self.get_unet_model(model_id='''CompVis/stable-diffusion-v1-4''' , fpaa=lowerCAmelCase_ ) _A: List[str] = self.get_latents(lowerCAmelCase_ , fpaa=lowerCAmelCase_ ) _A: Optional[int] = self.get_encoder_hidden_states(lowerCAmelCase_ , fpaa=lowerCAmelCase_ ) _A: List[str] = model.apply( {'''params''': params} , lowerCAmelCase_ , jnp.array(lowerCAmelCase_ , dtype=jnp.intaa ) , encoder_hidden_states=lowerCAmelCase_ , ).sample assert sample.shape == latents.shape _A: Any = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) _A: Tuple = jnp.array(lowerCAmelCase_ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware assert jnp.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-2 ) @parameterized.expand( [ # fmt: off [8_3, 4, [0.1514, 0.0807, 0.1624, 0.1016, -0.1896, 0.0263, 0.0677, 0.2310]], [1_7, 0.55, [0.1164, -0.0216, 0.0170, 0.1589, -0.3120, 0.1005, -0.0581, -0.1458]], [8, 0.89, [-0.1758, -0.0169, 0.1004, -0.1411, 0.1312, 0.1103, -0.1996, 0.2139]], [3, 1_0_0_0, [0.1214, 0.0352, -0.0731, -0.1562, -0.0994, -0.0906, -0.2340, -0.0539]], # fmt: on ] ) def __magic_name__ ( self : int , lowerCAmelCase_ : int , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Tuple ): """simple docstring""" _A , _A: Union[str, Any] = self.get_unet_model(model_id='''stabilityai/stable-diffusion-2''' , fpaa=lowerCAmelCase_ ) _A: Dict = self.get_latents(lowerCAmelCase_ , shape=(4, 4, 9_6, 9_6) , fpaa=lowerCAmelCase_ ) _A: Dict = self.get_encoder_hidden_states(lowerCAmelCase_ , shape=(4, 7_7, 1_0_2_4) , fpaa=lowerCAmelCase_ ) _A: Optional[int] = model.apply( {'''params''': params} , lowerCAmelCase_ , jnp.array(lowerCAmelCase_ , dtype=jnp.intaa ) , encoder_hidden_states=lowerCAmelCase_ , ).sample assert sample.shape == latents.shape _A: List[str] = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) _A: List[str] = jnp.array(lowerCAmelCase_ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware assert jnp.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1e-2 )
121
0
"""simple docstring""" import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def a__ ( snake_case__ ) -> List[Tuple[int, ...]]: lowerCamelCase = [] if isinstance(snake_case__ , snake_case__ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case__ ) ) elif isinstance(snake_case__ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case__ ) ) elif isinstance(snake_case__ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("""Not supported""" ) return shapes @torch.jit.ignore def a__ ( snake_case__ , snake_case__ ) -> Tuple[int, ...]: lowerCamelCase = [] for d in reversed(snake_case__ ): idx.append(flat_idx % d ) lowerCamelCase = flat_idx // d return tuple(reversed(snake_case__ ) ) @torch.jit.ignore def a__ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = None , snake_case__ = None , ) -> List[Tuple[slice, ...]]: # start_edges and end_edges both indicate whether, starting from any given # dimension, the start/end index is at the top/bottom edge of the # corresponding tensor, modeled as a tree def reduce_edge_list(snake_case__ ) -> None: lowerCamelCase = True for i in range(len(snake_case__ ) ): lowerCamelCase = -1 * (i + 1) l[reversed_idx] &= tally lowerCamelCase = l[reversed_idx] if start_edges is None: lowerCamelCase = [s == 0 for s in start] reduce_edge_list(snake_case__ ) if end_edges is None: lowerCamelCase = [e == (d - 1) for e, d in zip(snake_case__ , snake_case__ )] reduce_edge_list(snake_case__ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case__ ) == 0: return [()] elif len(snake_case__ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] lowerCamelCase = [] lowerCamelCase = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case__ , snake_case__ ): if s == e: path_list.append(slice(snake_case__ , s + 1 ) ) else: break lowerCamelCase = tuple(snake_case__ ) lowerCamelCase = len(snake_case__ ) # start == end, and we're done if divergence_idx == len(snake_case__ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowerCamelCase = start[divergence_idx] return tuple( path + (slice(snake_case__ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowerCamelCase = end[divergence_idx] return tuple( path + (slice(snake_case__ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) lowerCamelCase = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def a__ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> torch.Tensor: lowerCamelCase = t.shape[:no_batch_dims] lowerCamelCase = list(_flat_idx_to_idx(snake_case__ , snake_case__ ) ) # _get_minimal_slice_set is inclusive lowerCamelCase = list(_flat_idx_to_idx(flat_end - 1 , snake_case__ ) ) # Get an ordered list of slices to perform lowerCamelCase = _get_minimal_slice_set( snake_case__ , snake_case__ , snake_case__ , ) lowerCamelCase = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def a__ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ = False , snake_case__ = None , snake_case__ = False , ) -> Any: if not (len(snake_case__ ) > 0): raise ValueError("""Must provide at least one input""" ) lowerCamelCase = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case__ )] lowerCamelCase = tuple([max(snake_case__ ) for s in zip(*snake_case__ )] ) def _prep_inputs(snake_case__ ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: lowerCamelCase = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) lowerCamelCase = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: lowerCamelCase = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t lowerCamelCase = tensor_tree_map(_prep_inputs , snake_case__ ) lowerCamelCase = None if _out is not None: lowerCamelCase = tensor_tree_map(lambda snake_case__ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) lowerCamelCase = 1 for d in orig_batch_dims: flat_batch_dim *= d lowerCamelCase = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case__ ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t lowerCamelCase = 0 lowerCamelCase = prepped_outputs for _ in range(snake_case__ ): # Chunk the input if not low_mem: lowerCamelCase = _select_chunk else: lowerCamelCase = partial( _chunk_slice , flat_start=snake_case__ , flat_end=min(snake_case__ , i + chunk_size ) , no_batch_dims=len(snake_case__ ) , ) lowerCamelCase = tensor_tree_map(snake_case__ , snake_case__ ) # Run the layer on the chunk lowerCamelCase = layer(**snake_case__ ) # Allocate space for the output if out is None: lowerCamelCase = tensor_tree_map(lambda snake_case__ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case__ ) # Put the chunk in its pre-allocated space if isinstance(snake_case__ , snake_case__ ): def assign(snake_case__ , snake_case__ ) -> None: for k, v in da.items(): if isinstance(snake_case__ , snake_case__ ): assign(snake_case__ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: lowerCamelCase = da[k] assign(snake_case__ , snake_case__ ) elif isinstance(snake_case__ , snake_case__ ): for xa, xa in zip(snake_case__ , snake_case__ ): if _add_into_out: xa[i : i + chunk_size] += xa else: lowerCamelCase = xa elif isinstance(snake_case__ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: lowerCamelCase = output_chunk else: raise ValueError("""Not supported""" ) i += chunk_size lowerCamelCase = tensor_tree_map(lambda snake_case__ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case__ ) return out class __magic_name__ : '''simple docstring''' def __init__( self , _a = 512 , ): """simple docstring""" lowerCamelCase = max_chunk_size lowerCamelCase = None lowerCamelCase = None def _lowerCAmelCase ( self , _a , _a , _a ): """simple docstring""" logging.info("""Tuning chunk size...""" ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size lowerCamelCase = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] lowerCamelCase = [c for c in candidates if c > min_chunk_size] lowerCamelCase = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(_a ) -> bool: try: with torch.no_grad(): fn(*_a , chunk_size=_a ) return True except RuntimeError: return False lowerCamelCase = 0 lowerCamelCase = len(_a ) - 1 while i > min_viable_chunk_size_index: lowerCamelCase = test_chunk_size(candidates[i] ) if not viable: lowerCamelCase = (min_viable_chunk_size_index + i) // 2 else: lowerCamelCase = i lowerCamelCase = (i + len(_a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowerCAmelCase ( self , _a , _a ): """simple docstring""" lowerCamelCase = True for aa, aa in zip(_a , _a ): assert type(_a ) == type(_a ) if isinstance(_a , (list, tuple) ): consistent &= self._compare_arg_caches(_a , _a ) elif isinstance(_a , _a ): lowerCamelCase = [v for _, v in sorted(aa.items() , key=lambda _a : x[0] )] lowerCamelCase = [v for _, v in sorted(aa.items() , key=lambda _a : x[0] )] consistent &= self._compare_arg_caches(_a , _a ) else: consistent &= aa == aa return consistent def _lowerCAmelCase ( self , _a , _a , _a , ): """simple docstring""" lowerCamelCase = True lowerCamelCase = tree_map(lambda _a : a.shape if isinstance(_a , torch.Tensor ) else a , _a , _a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(_a ) lowerCamelCase = self._compare_arg_caches(self.cached_arg_data , _a ) else: # Otherwise, we can reuse the precomputed value lowerCamelCase = False if not consistent: lowerCamelCase = self._determine_favorable_chunk_size( _a , _a , _a , ) lowerCamelCase = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
168
"""simple docstring""" def a__ ( snake_case__ , snake_case__ ) -> int: return number | (1 << position) def a__ ( snake_case__ , snake_case__ ) -> int: return number & ~(1 << position) def a__ ( snake_case__ , snake_case__ ) -> int: return number ^ (1 << position) def a__ ( snake_case__ , snake_case__ ) -> bool: return ((number >> position) & 1) == 1 def a__ ( snake_case__ , snake_case__ ) -> int: return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
168
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 A =logging.get_logger(__name__) A ={ '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 ( __a , __a ): __a : Optional[Any] = """swin""" __a : Optional[Any] = { """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self : str , lowercase : List[Any]=224 , lowercase : Union[str, Any]=4 , lowercase : str=3 , lowercase : Union[str, Any]=96 , lowercase : Any=[2, 2, 6, 2] , lowercase : Tuple=[3, 6, 12, 24] , lowercase : Any=7 , lowercase : Optional[Any]=4.0 , lowercase : int=True , lowercase : int=0.0 , lowercase : Optional[int]=0.0 , lowercase : Dict=0.1 , lowercase : Tuple="gelu" , lowercase : Any=False , lowercase : int=0.02 , lowercase : List[str]=1E-5 , lowercase : int=32 , lowercase : Any=None , lowercase : str=None , **lowercase : List[Any] , ): '''simple docstring''' super().__init__(**lowercase ) UpperCAmelCase = image_size UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = embed_dim UpperCAmelCase = depths UpperCAmelCase = len(lowercase ) UpperCAmelCase = num_heads UpperCAmelCase = window_size UpperCAmelCase = mlp_ratio UpperCAmelCase = qkv_bias UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = drop_path_rate UpperCAmelCase = hidden_act UpperCAmelCase = use_absolute_embeddings UpperCAmelCase = layer_norm_eps UpperCAmelCase = initializer_range UpperCAmelCase = 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 = int(embed_dim * 2 ** (len(lowercase ) - 1) ) UpperCAmelCase = ['''stem'''] + [f"stage{idx}" for idx in range(1 , len(lowercase ) + 1 )] UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices( out_features=lowercase , out_indices=lowercase , stage_names=self.stage_names ) class _a ( __a ): __a : Optional[Any] = version.parse("""1.11""" ) @property def A ( self : Tuple ): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def A ( self : int ): '''simple docstring''' return 1E-4
34
from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput UpperCAmelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCamelCase__( __lowerCamelCase , __lowerCamelCase): @register_to_config def __init__( self: Optional[Any] , UpperCamelCase_: bool , UpperCamelCase_: Optional[int] = None , UpperCamelCase_: Optional[int] = None ): super().__init__() __lowerCamelCase = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" __lowerCamelCase = torch.zeros(UpperCamelCase_ , UpperCamelCase_ ) else: __lowerCamelCase = None __lowerCamelCase = torch.nn.Parameter(UpperCamelCase_ ) class lowerCamelCase__( __lowerCamelCase): UpperCAmelCase__ : VQModel UpperCAmelCase__ : CLIPTextModel UpperCAmelCase__ : CLIPTokenizer UpperCAmelCase__ : TransformeraDModel UpperCAmelCase__ : LearnedClassifierFreeSamplingEmbeddings UpperCAmelCase__ : VQDiffusionScheduler def __init__( self: str , UpperCamelCase_: VQModel , UpperCamelCase_: CLIPTextModel , UpperCamelCase_: CLIPTokenizer , UpperCamelCase_: TransformeraDModel , UpperCamelCase_: VQDiffusionScheduler , UpperCamelCase_: LearnedClassifierFreeSamplingEmbeddings , ): super().__init__() self.register_modules( vqvae=UpperCamelCase_ , transformer=UpperCamelCase_ , text_encoder=UpperCamelCase_ , tokenizer=UpperCamelCase_ , scheduler=UpperCamelCase_ , learned_classifier_free_sampling_embeddings=UpperCamelCase_ , ) def lowerCAmelCase__ ( self: str , UpperCamelCase_: Any , UpperCamelCase_: List[Any] , UpperCamelCase_: Any ): __lowerCamelCase = len(UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else 1 # get prompt text embeddings __lowerCamelCase = self.tokenizer( UpperCamelCase_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) __lowerCamelCase = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: __lowerCamelCase = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F' {self.tokenizer.model_max_length} tokens: {removed_text}' ) __lowerCamelCase = text_input_ids[:, : self.tokenizer.model_max_length] __lowerCamelCase = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 __lowerCamelCase = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=UpperCamelCase_ ) # duplicate text embeddings for each generation per prompt __lowerCamelCase = prompt_embeds.repeat_interleave(UpperCamelCase_ , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: __lowerCamelCase = self.learned_classifier_free_sampling_embeddings.embeddings __lowerCamelCase = negative_prompt_embeds.unsqueeze(0 ).repeat(UpperCamelCase_ , 1 , 1 ) else: __lowerCamelCase = [""""""] * batch_size __lowerCamelCase = text_input_ids.shape[-1] __lowerCamelCase = self.tokenizer( UpperCamelCase_ , padding="""max_length""" , max_length=UpperCamelCase_ , truncation=UpperCamelCase_ , return_tensors="""pt""" , ) __lowerCamelCase = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings __lowerCamelCase = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=UpperCamelCase_ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __lowerCamelCase = negative_prompt_embeds.shape[1] __lowerCamelCase = negative_prompt_embeds.repeat(1 , UpperCamelCase_ , 1 ) __lowerCamelCase = negative_prompt_embeds.view(batch_size * num_images_per_prompt , UpperCamelCase_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __lowerCamelCase = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self: Tuple , UpperCamelCase_: Union[str, List[str]] , UpperCamelCase_: int = 1_00 , UpperCamelCase_: float = 5.0 , UpperCamelCase_: float = 1.0 , UpperCamelCase_: int = 1 , UpperCamelCase_: Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase_: Optional[torch.FloatTensor] = None , UpperCamelCase_: Optional[str] = "pil" , UpperCamelCase_: bool = True , UpperCamelCase_: Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCamelCase_: int = 1 , ): if isinstance(UpperCamelCase_ , UpperCamelCase_ ): __lowerCamelCase = 1 elif isinstance(UpperCamelCase_ , UpperCamelCase_ ): __lowerCamelCase = len(UpperCamelCase_ ) else: raise ValueError(F'`prompt` has to be of type `str` or `list` but is {type(UpperCamelCase_ )}' ) __lowerCamelCase = batch_size * num_images_per_prompt __lowerCamelCase = guidance_scale > 1.0 __lowerCamelCase = self._encode_prompt(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCamelCase_ , UpperCamelCase_ ) or callback_steps <= 0) ): raise ValueError( F'`callback_steps` has to be a positive integer but is {callback_steps} of type' F' {type(UpperCamelCase_ )}.' ) # get the initial completely masked latents unless the user supplied it __lowerCamelCase = (batch_size, self.transformer.num_latent_pixels) if latents is None: __lowerCamelCase = self.transformer.num_vector_embeds - 1 __lowerCamelCase = torch.full(UpperCamelCase_ , UpperCamelCase_ ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( """Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,""" F' {self.transformer.num_vector_embeds - 1} (inclusive).' ) __lowerCamelCase = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(UpperCamelCase_ , device=self.device ) __lowerCamelCase = self.scheduler.timesteps.to(self.device ) __lowerCamelCase = latents for i, t in enumerate(self.progress_bar(UpperCamelCase_ ) ): # expand the sample if we are doing classifier free guidance __lowerCamelCase = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` __lowerCamelCase = self.transformer(UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , timestep=UpperCamelCase_ ).sample if do_classifier_free_guidance: __lowerCamelCase, __lowerCamelCase = model_output.chunk(2 ) __lowerCamelCase = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(UpperCamelCase_ , dim=1 , keepdim=UpperCamelCase_ ) __lowerCamelCase = self.truncate(UpperCamelCase_ , UpperCamelCase_ ) # remove `log(0)`'s (`-inf`s) __lowerCamelCase = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 __lowerCamelCase = self.scheduler.step(UpperCamelCase_ , timestep=UpperCamelCase_ , sample=UpperCamelCase_ , generator=UpperCamelCase_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __lowerCamelCase = self.vqvae.config.vq_embed_dim __lowerCamelCase = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) __lowerCamelCase = self.vqvae.quantize.get_codebook_entry(UpperCamelCase_ , shape=UpperCamelCase_ ) __lowerCamelCase = self.vqvae.decode(UpperCamelCase_ , force_not_quantize=UpperCamelCase_ ).sample __lowerCamelCase = (image / 2 + 0.5).clamp(0 , 1 ) __lowerCamelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __lowerCamelCase = self.numpy_to_pil(UpperCamelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCamelCase_ ) def lowerCAmelCase__ ( self: Union[str, Any] , UpperCamelCase_: torch.FloatTensor , UpperCamelCase_: float ): __lowerCamelCase, __lowerCamelCase = torch.sort(UpperCamelCase_ , 1 , descending=UpperCamelCase_ ) __lowerCamelCase = torch.exp(UpperCamelCase_ ) __lowerCamelCase = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out __lowerCamelCase = torch.full_like(keep_mask[:, 0:1, :] , UpperCamelCase_ ) __lowerCamelCase = torch.cat((all_true, keep_mask) , dim=1 ) __lowerCamelCase = keep_mask[:, :-1, :] __lowerCamelCase = keep_mask.gather(1 , indices.argsort(1 ) ) __lowerCamelCase = log_p_x_0.clone() __lowerCamelCase = -torch.inf # -inf = log(0) return rv
12
0
import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase__ = [ 'word_embeddings_layernorm.weight', 'word_embeddings_layernorm.bias', 'input_layernorm.weight', 'input_layernorm.bias', 'post_attention_layernorm.weight', 'post_attention_layernorm.bias', 'self_attention.dense.bias', 'mlp.dense_4h_to_h.bias', 'ln_f.weight', 'ln_f.bias', ] UpperCamelCase__ = [ 'mlp.dense_4h_to_h.weight', 'self_attention.dense.weight', ] def lowerCAmelCase_ ( __A, __A ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = { "word_embeddings.weight": "word_embeddings.weight", "word_embeddings.norm.weight": "word_embeddings_layernorm.weight", "word_embeddings.norm.bias": "word_embeddings_layernorm.bias", "weight": "ln_f.weight", "bias": "ln_f.bias", } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks UpperCAmelCase__ = int(re.match(r".*layer_(\d*).*", __A )[1] ) layer_number -= 3 return f"""h.{layer_number}.""" + key def lowerCAmelCase_ ( __A ) -> int: '''simple docstring''' if dtype == torch.bool: return 1 / 8 UpperCAmelCase__ = re.search(r"[^\d](\d+)$", str(__A ) ) if bit_search is None: raise ValueError(f"""`dtype` is not a valid dtype: {dtype}.""" ) UpperCAmelCase__ = int(bit_search.groups()[0] ) return bit_size // 8 def lowerCAmelCase_ ( __A, __A, __A, __A, __A ) -> Union[str, Any]: '''simple docstring''' if bloom_config_file == "": UpperCAmelCase__ = BloomConfig() else: UpperCAmelCase__ = BloomConfig.from_json_file(__A ) if shard_model: UpperCAmelCase__ = os.listdir(__A ) UpperCAmelCase__ = sorted(filter(lambda __A : s.startswith("layer" ) and "model_00" in s, __A ) ) UpperCAmelCase__ = {"weight_map": {}, "metadata": {}} UpperCAmelCase__ = 0 UpperCAmelCase__ = None UpperCAmelCase__ = BloomConfig() for j, file in enumerate(__A ): print("Processing file: {}".format(__A ) ) UpperCAmelCase__ = None for i in range(__A ): # load all TP files UpperCAmelCase__ = file.replace("model_00", f"""model_0{i}""" ) UpperCAmelCase__ = torch.load(os.path.join(__A, __A ), map_location="cpu" ) # Rename keys in the transformers names UpperCAmelCase__ = list(temp.keys() ) for key in keys: UpperCAmelCase__ = temp.pop(__A ) if tensors is None: UpperCAmelCase__ = temp else: for key in tensors.keys(): if any(key.endswith(__A ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel UpperCAmelCase__ = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks UpperCAmelCase__ = torch.cat([tensors[key], temp[key]], dim=__A ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(__A ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): UpperCAmelCase__ = tensors[key] / pretraining_tp torch.save( __A, os.path.join( __A, "pytorch_model_{}-of-{}.bin".format(str(j + 1 ).zfill(5 ), str(len(__A ) ).zfill(5 ) ), ), ) for key in tensors.keys(): UpperCAmelCase__ = tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: UpperCAmelCase__ = "pytorch_model_{}-of-{}.bin".format( str(j + 1 ).zfill(5 ), str(len(__A ) ).zfill(5 ) ) UpperCAmelCase__ = BloomConfig() UpperCAmelCase__ = pytorch_dump_folder_path + "/" + CONFIG_NAME UpperCAmelCase__ = total_size with open(__A, "w", encoding="utf-8" ) as f: f.write(config.to_json_string() ) with open(os.path.join(__A, WEIGHTS_NAME + ".index.json" ), "w", encoding="utf-8" ) as f: UpperCAmelCase__ = json.dumps(__A, indent=2, sort_keys=__A ) + "\n" f.write(__A ) else: UpperCAmelCase__ = BloomModel(__A ) UpperCAmelCase__ = os.listdir(__A ) UpperCAmelCase__ = sorted(filter(lambda __A : s.startswith("layer" ) and "model_00" in s, __A ) ) UpperCAmelCase__ = None for i, file in enumerate(__A ): UpperCAmelCase__ = None for i in range(__A ): # load all TP files UpperCAmelCase__ = file.replace("model_00", f"""model_0{i}""" ) UpperCAmelCase__ = torch.load(os.path.join(__A, __A ), map_location="cpu" ) # Rename keys in the transformers names UpperCAmelCase__ = list(temp.keys() ) for key in keys: UpperCAmelCase__ = temp.pop(__A ) if tensors is None: UpperCAmelCase__ = temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(__A ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel UpperCAmelCase__ = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks UpperCAmelCase__ = torch.cat([tensors[key], temp[key]], dim=__A ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(__A ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): UpperCAmelCase__ = tensors[key] / pretraining_tp UpperCAmelCase__ = model.load_state_dict(__A, strict=__A ) assert not other_keys.unexpected_keys, f"""The keys {other_keys.unexpected_keys} are unexpected""" if missing_keys is None: UpperCAmelCase__ = set(other_keys.missing_keys ) else: UpperCAmelCase__ = missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, f"""The keys {missing_keys} are missing""" # Save pytorch-model os.makedirs(__A, exist_ok=__A ) UpperCAmelCase__ = pytorch_dump_folder_path + "/" + WEIGHTS_NAME UpperCAmelCase__ = pytorch_dump_folder_path + "/" + CONFIG_NAME print(f"""Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}""" ) if config.torch_dtype is not None: UpperCAmelCase__ = model.to(config.torch_dtype ) torch.save(model.state_dict(), __A ) print(f"""Save configuration file to {pytorch_config_dump_path}""" ) with open(__A, "w", encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--bloom_checkpoint_path', default=None, type=str, required=True, help='Path to the Megatron-LM checkpoint path.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--bloom_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--shard_model', action='store_true', help='An optional setting to shard the output model \nThis enables sharding the converted checkpoint', ) parser.add_argument( '--pretraining_tp', default=4, type=int, help='Pretraining TP rank that has been used when training the model in Megatron-LM \n', ) UpperCamelCase__ = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
143
# 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 .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def lowerCAmelCase_ ( __A=None ) -> str: '''simple docstring''' UpperCAmelCase__ = argparse.ArgumentParser(add_help=__A, allow_abbrev=__A ) # The main config parser UpperCAmelCase__ = config_command_parser(__A ) # The subparser to add commands to UpperCAmelCase__ = config_parser.add_subparsers(title="subcommands", dest="subcommand" ) # Then add other parsers with the parent parser default_command_parser(__A, parents=[parent_parser] ) update_command_parser(__A, parents=[parent_parser] ) return config_parser def lowerCAmelCase_ ( ) -> Any: '''simple docstring''' UpperCAmelCase__ = get_config_parser() UpperCAmelCase__ = config_parser.parse_args() if not hasattr(__A, "func" ): config_parser.print_help() exit(1 ) # Run args.func(__A ) if __name__ == "__main__": main()
143
1
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser snake_case_ = re.compile(R"""\s+""") def _lowerCAmelCase ( lowercase_ ): return {"hash": hashlib.mda(re.sub(lowercase_ , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = [len(lowercase_ ) for line in example['content'].splitlines()] return {"line_mean": np.mean(lowercase_ ), "line_max": max(lowercase_ )} def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def _lowerCAmelCase ( lowercase_ , lowercase_ ): if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def _lowerCAmelCase ( lowercase_ , lowercase_=5 ): UpperCAmelCase = ['auto-generated', 'autogenerated', 'automatically generated'] UpperCAmelCase = example['content'].splitlines() for _, line in zip(range(lowercase_ ) , lowercase_ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def _lowerCAmelCase ( lowercase_ , lowercase_=5 , lowercase_=0.0_5 ): UpperCAmelCase = ['unit tests', 'test file', 'configuration file'] UpperCAmelCase = example['content'].splitlines() UpperCAmelCase = 0 UpperCAmelCase = 0 # first test for _, line in zip(range(lowercase_ ) , lowercase_ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test UpperCAmelCase = example['content'].count('\n' ) UpperCAmelCase = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = ['def ', 'class ', 'for ', 'while '] UpperCAmelCase = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def _lowerCAmelCase ( lowercase_ , lowercase_=4 ): UpperCAmelCase = example['content'].splitlines() UpperCAmelCase = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = tokenizer(example['content'] , truncation=lowercase_ )['input_ids'] UpperCAmelCase = len(example['content'] ) / len(lowercase_ ) return {"ratio": ratio} def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = {} results.update(get_hash(lowercase_ ) ) results.update(line_stats(lowercase_ ) ) results.update(alpha_stats(lowercase_ ) ) results.update(char_token_ratio(lowercase_ ) ) results.update(is_autogenerated(lowercase_ ) ) results.update(is_config_or_test(lowercase_ ) ) results.update(has_no_keywords(lowercase_ ) ) results.update(has_few_assignments(lowercase_ ) ) return results def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ ): if not check_uniques(lowercase_ , lowercase_ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def _lowerCAmelCase ( lowercase_ ): with open(lowercase_ , 'rb' ) as f_in: with gzip.open(str(lowercase_ ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(lowercase_ , lowercase_ ) os.unlink(lowercase_ ) # Settings snake_case_ = HfArgumentParser(PreprocessingArguments) snake_case_ = parser.parse_args() if args.num_workers is None: snake_case_ = multiprocessing.cpu_count() snake_case_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset snake_case_ = time.time() snake_case_ = load_dataset(args.dataset_name, split="""train""") print(f'''Time to load dataset: {time.time()-t_start:.2f}''') # Run preprocessing snake_case_ = time.time() snake_case_ = ds.map(preprocess, num_proc=args.num_workers) print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''') # Deduplicate hashes snake_case_ = set(ds.unique("""hash""")) snake_case_ = len(uniques) / len(ds) print(f'''Fraction of duplicates: {1-frac:.2%}''') # Deduplicate data and apply heuristics snake_case_ = time.time() snake_case_ = ds.filter(filter, fn_kwargs={"""uniques""": uniques, """args""": args}) print(f'''Time to filter dataset: {time.time()-t_start:.2f}''') print(f'''Size of filtered dataset: {len(ds_filter)}''') # Deduplicate with minhash and jaccard similarity if args.near_deduplication: snake_case_ = time.time() snake_case_ , snake_case_ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(f'''Time to deduplicate dataset: {time.time()-t_start:.2f}''') print(f'''Size of deduplicate dataset: {len(ds_filter)}''') # Save data in batches of samples_per_file snake_case_ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / """duplicate_clusters.json""", """w""") as f: json.dump(duplicate_clusters, f) snake_case_ = output_dir / """data""" data_dir.mkdir(exist_ok=True) snake_case_ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): snake_case_ = str(data_dir / f'''file-{file_number+1:012}.json''') snake_case_ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(f'''Time to save dataset: {time.time()-t_start:.2f}''')
78
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase : Tuple = logging.get_logger(__name__) lowerCAmelCase : str = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} lowerCAmelCase : Dict = { 'vocab_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json' ), }, 'merges_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt' ), }, } lowerCAmelCase : Dict = { 'allenai/longformer-base-4096': 40_96, 'allenai/longformer-large-4096': 40_96, 'allenai/longformer-large-4096-finetuned-triviaqa': 40_96, 'allenai/longformer-base-4096-extra.pos.embd.only': 40_96, 'allenai/longformer-large-4096-extra.pos.embd.only': 40_96, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def A_ ( ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = ( list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) ) ) SCREAMING_SNAKE_CASE_ : List[str] = bs[:] SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 for b in range(2**8 ): if b not in bs: bs.append(a ) cs.append(2**8 + n ) n += 1 SCREAMING_SNAKE_CASE_ : int = [chr(a ) for n in cs] return dict(zip(a , a ) ) def A_ ( a ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = set() SCREAMING_SNAKE_CASE_ : Optional[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) SCREAMING_SNAKE_CASE_ : Any = char return pairs class _A ( __magic_name__): SCREAMING_SNAKE_CASE : Tuple = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE : int = ['''input_ids''', '''attention_mask'''] def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="replace" , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="<unk>" , _SCREAMING_SNAKE_CASE="<pad>" , _SCREAMING_SNAKE_CASE="<mask>" , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else bos_token SCREAMING_SNAKE_CASE_ : Dict = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else eos_token SCREAMING_SNAKE_CASE_ : int = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else sep_token SCREAMING_SNAKE_CASE_ : Any = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else cls_token SCREAMING_SNAKE_CASE_ : Optional[Any] = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else unk_token SCREAMING_SNAKE_CASE_ : Dict = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else pad_token # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE_ : Any = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else mask_token super().__init__( errors=_SCREAMING_SNAKE_CASE , 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 , mask_token=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as vocab_handle: SCREAMING_SNAKE_CASE_ : List[str] = json.load(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Optional[int] = {v: k for k, v in self.encoder.items()} SCREAMING_SNAKE_CASE_ : int = errors # how to handle errors in decoding SCREAMING_SNAKE_CASE_ : List[Any] = bytes_to_unicode() SCREAMING_SNAKE_CASE_ : Union[str, Any] = {v: k for k, v in self.byte_encoder.items()} with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as merges_handle: SCREAMING_SNAKE_CASE_ : Optional[int] = merges_handle.read().split('\n' )[1:-1] SCREAMING_SNAKE_CASE_ : List[Any] = [tuple(merge.split() ) for merge in bpe_merges] SCREAMING_SNAKE_CASE_ : Dict = dict(zip(_SCREAMING_SNAKE_CASE , range(len(_SCREAMING_SNAKE_CASE ) ) ) ) SCREAMING_SNAKE_CASE_ : Dict = {} SCREAMING_SNAKE_CASE_ : List[Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions SCREAMING_SNAKE_CASE_ : Tuple = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def UpperCAmelCase ( self ): """simple docstring""" return len(self.encoder ) def UpperCAmelCase ( self ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): """simple docstring""" if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE_ : Optional[int] = tuple(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Dict = get_pairs(_SCREAMING_SNAKE_CASE ) if not pairs: return token while True: SCREAMING_SNAKE_CASE_ : int = min(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : self.bpe_ranks.get(_SCREAMING_SNAKE_CASE , float('inf' ) ) ) if bigram not in self.bpe_ranks: break SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = bigram SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : List[Any] = 0 while i < len(_SCREAMING_SNAKE_CASE ): try: SCREAMING_SNAKE_CASE_ : Any = word.index(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) SCREAMING_SNAKE_CASE_ : Tuple = j if word[i] == first and i < len(_SCREAMING_SNAKE_CASE ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 SCREAMING_SNAKE_CASE_ : str = tuple(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Tuple = new_word if len(_SCREAMING_SNAKE_CASE ) == 1: break else: SCREAMING_SNAKE_CASE_ : Any = get_pairs(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : List[Any] = ' '.join(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : Tuple = word return word def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [] for token in re.findall(self.pat , _SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_SCREAMING_SNAKE_CASE ).split(' ' ) ) return bpe_tokens def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): """simple docstring""" return self.encoder.get(_SCREAMING_SNAKE_CASE , self.encoder.get(self.unk_token ) ) def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): """simple docstring""" return self.decoder.get(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ''.join(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ : str = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ): """simple docstring""" if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE_ : Tuple = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE_ : Optional[Any] = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_SCREAMING_SNAKE_CASE , ensure_ascii=_SCREAMING_SNAKE_CASE ) + '\n' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0 with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _SCREAMING_SNAKE_CASE : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." ' Please check that the tokenizer is not corrupted!' ) SCREAMING_SNAKE_CASE_ : List[Any] = token_index writer.write(' '.join(_SCREAMING_SNAKE_CASE ) + '\n' ) index += 1 return vocab_file, merge_file def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE_ : Optional[int] = [self.cls_token_id] SCREAMING_SNAKE_CASE_ : List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False ): """simple docstring""" 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 )) + [1] return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1, 1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(_SCREAMING_SNAKE_CASE ) > 0 and not text[0].isspace()): SCREAMING_SNAKE_CASE_ : List[Any] = ' ' + text return (text, kwargs)
253
0
"""simple docstring""" def lowerCAmelCase__ ( lowerCamelCase_ : int ,lowerCamelCase_ : int): '''simple docstring''' while b: lowerCAmelCase__ : Optional[Any] = b, a % b return a def lowerCAmelCase__ ( lowerCamelCase_ : int ,lowerCamelCase_ : int): '''simple docstring''' return a if b == 0 else euclidean_gcd_recursive(lowerCamelCase_ ,a % b) def lowerCAmelCase__ ( ): '''simple docstring''' print(f"""euclidean_gcd(3, 5) = {euclidean_gcd(3 ,5)}""") print(f"""euclidean_gcd(5, 3) = {euclidean_gcd(5 ,3)}""") print(f"""euclidean_gcd(1, 3) = {euclidean_gcd(1 ,3)}""") print(f"""euclidean_gcd(3, 6) = {euclidean_gcd(3 ,6)}""") print(f"""euclidean_gcd(6, 3) = {euclidean_gcd(6 ,3)}""") print(f"""euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 ,5)}""") print(f"""euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 ,3)}""") print(f"""euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 ,3)}""") print(f"""euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 ,6)}""") print(f"""euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 ,3)}""") if __name__ == "__main__": main()
355
import flax.linen as nn import jax import jax.numpy as jnp class lowerCamelCase__ ( nn.Module): '''simple docstring''' snake_case_ =42 snake_case_ =jnp.floataa def lowerCAmelCase__ (self ) -> List[str]: """simple docstring""" lowerCAmelCase__ : Dict = nn.Conv( self.out_channels ,kernel_size=(3, 3) ,strides=(1, 1) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) def __call__(self ,__lowerCamelCase ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ : Dict = hidden_states.shape lowerCAmelCase__ : Dict = jax.image.resize( __lowerCamelCase ,shape=(batch, height * 2, width * 2, channels) ,method='''nearest''' ,) lowerCAmelCase__ : Dict = self.conv(__lowerCamelCase ) return hidden_states class lowerCamelCase__ ( nn.Module): '''simple docstring''' snake_case_ =42 snake_case_ =jnp.floataa def lowerCAmelCase__ (self ) -> int: """simple docstring""" lowerCAmelCase__ : List[Any] = nn.Conv( self.out_channels ,kernel_size=(3, 3) ,strides=(2, 2) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) def __call__(self ,__lowerCamelCase ) -> Any: """simple docstring""" lowerCAmelCase__ : Optional[int] = self.conv(__lowerCamelCase ) return hidden_states class lowerCamelCase__ ( nn.Module): '''simple docstring''' snake_case_ =42 snake_case_ =None snake_case_ =0.0 snake_case_ =None snake_case_ =jnp.floataa def lowerCAmelCase__ (self ) -> int: """simple docstring""" lowerCAmelCase__ : List[str] = self.in_channels if self.out_channels is None else self.out_channels lowerCAmelCase__ : Union[str, Any] = nn.GroupNorm(num_groups=32 ,epsilon=1e-5 ) lowerCAmelCase__ : Union[str, Any] = nn.Conv( __lowerCamelCase ,kernel_size=(3, 3) ,strides=(1, 1) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) lowerCAmelCase__ : int = nn.Dense(__lowerCamelCase ,dtype=self.dtype ) lowerCAmelCase__ : List[Any] = nn.GroupNorm(num_groups=32 ,epsilon=1e-5 ) lowerCAmelCase__ : Union[str, Any] = nn.Dropout(self.dropout_prob ) lowerCAmelCase__ : Optional[int] = nn.Conv( __lowerCamelCase ,kernel_size=(3, 3) ,strides=(1, 1) ,padding=((1, 1), (1, 1)) ,dtype=self.dtype ,) lowerCAmelCase__ : str = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut lowerCAmelCase__ : Union[str, Any] = None if use_nin_shortcut: lowerCAmelCase__ : Optional[Any] = nn.Conv( __lowerCamelCase ,kernel_size=(1, 1) ,strides=(1, 1) ,padding='''VALID''' ,dtype=self.dtype ,) def __call__(self ,__lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase=True ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ : Tuple = hidden_states lowerCAmelCase__ : Dict = self.norma(__lowerCamelCase ) lowerCAmelCase__ : Union[str, Any] = nn.swish(__lowerCamelCase ) lowerCAmelCase__ : List[Any] = self.conva(__lowerCamelCase ) lowerCAmelCase__ : List[Any] = self.time_emb_proj(nn.swish(__lowerCamelCase ) ) lowerCAmelCase__ : Dict = jnp.expand_dims(jnp.expand_dims(__lowerCamelCase ,1 ) ,1 ) lowerCAmelCase__ : Optional[int] = hidden_states + temb lowerCAmelCase__ : Optional[int] = self.norma(__lowerCamelCase ) lowerCAmelCase__ : Optional[int] = nn.swish(__lowerCamelCase ) lowerCAmelCase__ : int = self.dropout(__lowerCamelCase ,__lowerCamelCase ) lowerCAmelCase__ : List[Any] = self.conva(__lowerCamelCase ) if self.conv_shortcut is not None: lowerCAmelCase__ : Optional[int] = self.conv_shortcut(__lowerCamelCase ) return hidden_states + residual
94
0
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() _A = logging.get_logger(__name__) _A = ["""model.decoder.embed_positions.weights"""] def lowercase_ ( __UpperCAmelCase ) -> Any: if "emb" in name: lowerCAmelCase__ : Optional[Any] = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: lowerCAmelCase__ : List[Any] = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: lowerCAmelCase__ : Union[str, Any] = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: lowerCAmelCase__ : Optional[Any] = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: lowerCAmelCase__ : Dict = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: lowerCAmelCase__ : Optional[Any] = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: lowerCAmelCase__ : Optional[int] = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: lowerCAmelCase__ : str = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: lowerCAmelCase__ : Tuple = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: lowerCAmelCase__ : Optional[int] = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: lowerCAmelCase__ : Union[str, Any] = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase ) -> Tuple[Dict, Dict]: lowerCAmelCase__ : List[str] = list(state_dict.keys() ) lowerCAmelCase__ : Union[str, Any] = {} for key in keys: lowerCAmelCase__ : Union[str, Any] = state_dict.pop(__UpperCAmelCase ) lowerCAmelCase__ : Tuple = rename_keys(__UpperCAmelCase ) if "in_proj_weight" in key: # split fused qkv proj lowerCAmelCase__ : Union[str, Any] = val[:hidden_size, :] lowerCAmelCase__ : List[Any] = val[hidden_size : 2 * hidden_size, :] lowerCAmelCase__ : int = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: lowerCAmelCase__ : Dict = val else: lowerCAmelCase__ : Tuple = val return state_dict, enc_dec_proj_state_dict def lowercase_ ( __UpperCAmelCase ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values lowerCAmelCase__ : List[Any] = 1024 lowerCAmelCase__ : List[str] = 24 lowerCAmelCase__ : str = 16 elif checkpoint == "medium": lowerCAmelCase__ : Optional[Any] = 1536 lowerCAmelCase__ : List[Any] = 48 lowerCAmelCase__ : Union[str, Any] = 24 elif checkpoint == "large": lowerCAmelCase__ : Any = 2048 lowerCAmelCase__ : int = 48 lowerCAmelCase__ : Optional[Any] = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) lowerCAmelCase__ : List[str] = MusicgenDecoderConfig( hidden_size=__UpperCAmelCase , ffn_dim=hidden_size * 4 , num_hidden_layers=__UpperCAmelCase , num_attention_heads=__UpperCAmelCase , ) return config @torch.no_grad() def lowercase_ ( __UpperCAmelCase , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="cpu" ) -> Dict: lowerCAmelCase__ : List[Any] = MusicGen.get_pretrained(__UpperCAmelCase , device=__UpperCAmelCase ) lowerCAmelCase__ : List[str] = decoder_config_from_checkpoint(__UpperCAmelCase ) lowerCAmelCase__ : Optional[int] = fairseq_model.lm.state_dict() lowerCAmelCase__ , lowerCAmelCase__ : int = rename_state_dict( __UpperCAmelCase , hidden_size=decoder_config.hidden_size ) lowerCAmelCase__ : int = TaEncoderModel.from_pretrained("""t5-base""" ) lowerCAmelCase__ : Optional[Any] = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) lowerCAmelCase__ : str = MusicgenForCausalLM(__UpperCAmelCase ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = decoder.load_state_dict(__UpperCAmelCase , strict=__UpperCAmelCase ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__UpperCAmelCase ) if len(__UpperCAmelCase ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(__UpperCAmelCase ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model lowerCAmelCase__ : Optional[int] = MusicgenForConditionalGeneration(text_encoder=__UpperCAmelCase , audio_encoder=__UpperCAmelCase , decoder=__UpperCAmelCase ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__UpperCAmelCase ) # check we can do a forward pass lowerCAmelCase__ : Tuple = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) lowerCAmelCase__ : Any = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): lowerCAmelCase__ : List[str] = model(input_ids=__UpperCAmelCase , decoder_input_ids=__UpperCAmelCase ).logits if logits.shape != (8, 1, 2048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor lowerCAmelCase__ : List[str] = AutoTokenizer.from_pretrained("""t5-base""" ) lowerCAmelCase__ : List[str] = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) lowerCAmelCase__ : Dict = MusicgenProcessor(feature_extractor=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) # set the appropriate bos/pad token ids lowerCAmelCase__ : Union[str, Any] = 2048 lowerCAmelCase__ : Dict = 2048 # set other default generation config params lowerCAmelCase__ : Optional[int] = int(30 * audio_encoder.config.frame_rate ) lowerCAmelCase__ : List[str] = True lowerCAmelCase__ : Tuple = 3.0 if pytorch_dump_folder is not None: Path(__UpperCAmelCase ).mkdir(exist_ok=__UpperCAmelCase ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(__UpperCAmelCase ) processor.save_pretrained(__UpperCAmelCase ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(__UpperCAmelCase ) processor.push_to_hub(__UpperCAmelCase ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint""", default="""small""", type=str, help="""Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.""", ) parser.add_argument( """--pytorch_dump_folder""", required=True, default=None, type=str, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=None, type=str, help="""Where to upload the converted model on the 🤗 hub.""" ) parser.add_argument( """--device""", default="""cpu""", type=str, help="""Torch device to run the conversion, either cpu or cuda.""" ) _A = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
242
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class _lowerCamelCase ( a_ ): _lowerCamelCase :Any = "Salesforce/blip-image-captioning-base" _lowerCamelCase :int = ( "This is a tool that generates a description of an image. It takes an input named `image` which should be the " "image to caption, and returns a text that contains the description in English." ) _lowerCamelCase :List[Any] = "image_captioner" _lowerCamelCase :Tuple = AutoModelForVisionaSeq _lowerCamelCase :Dict = ["image"] _lowerCamelCase :str = ["text"] def __init__( self : Dict , *UpperCamelCase : Any , **UpperCamelCase : Any ) -> Any: """simple docstring""" requires_backends(self , ["""vision"""] ) super().__init__(*UpperCamelCase , **UpperCamelCase ) def _lowerCAmelCase ( self : Any , UpperCamelCase : "Image" ) -> Union[str, Any]: """simple docstring""" return self.pre_processor(images=UpperCamelCase , return_tensors="""pt""" ) def _lowerCAmelCase ( self : Optional[Any] , UpperCamelCase : str ) -> Tuple: """simple docstring""" return self.model.generate(**UpperCamelCase ) def _lowerCAmelCase ( self : Tuple , UpperCamelCase : int ) -> Tuple: """simple docstring""" return self.pre_processor.batch_decode(UpperCamelCase , skip_special_tokens=UpperCamelCase )[0].strip()
242
1
"""simple docstring""" import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse("0.12.2"): raise Exception("requires fairseq >= 0.12.2") if version.parse(fairseq.__version__) > version.parse("2"): raise Exception("requires fairseq < v2") logging.set_verbosity_info() __A : Any = logging.get_logger(__name__) __A : List[str] = """Hello, World!""" __A : Any = """en_XX""" def lowercase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : bool ): '''simple docstring''' _UpperCAmelCase = Path('''data_bin''' ) _UpperCAmelCase = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(__snake_case ).parent ) , checkpoint_file=Path(__snake_case ).name , _name='''xmod_base''' , arch='''xmod_base''' , task='''multilingual_masked_lm''' , data_name_or_path=str(__snake_case ) , bpe='''sentencepiece''' , sentencepiece_model=str(Path(__snake_case ).parent / '''sentencepiece.bpe.model''' ) , src_dict=str(data_dir / '''dict.txt''' ) , ) xmod.eval() # disable dropout print(__snake_case ) _UpperCAmelCase = xmod.model.encoder.sentence_encoder _UpperCAmelCase = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , '''bottleneck''' , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: _UpperCAmelCase = xmod.model.classification_heads['''mnli'''].out_proj.weight.shape[0] print('''Our X-MOD config:''' , __snake_case ) _UpperCAmelCase = XmodForSequenceClassification(__snake_case ) if classification_head else XmodForMaskedLM(__snake_case ) model.eval() # Now let's copy all the weights. # Embeddings _UpperCAmelCase = xmod_sent_encoder.embed_tokens.weight _UpperCAmelCase = xmod_sent_encoder.embed_positions.weight _UpperCAmelCase = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. _UpperCAmelCase = xmod_sent_encoder.layernorm_embedding.weight _UpperCAmelCase = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer _UpperCAmelCase = model.roberta.encoder.layer[i] _UpperCAmelCase = xmod_sent_encoder.layers[i] # self attention _UpperCAmelCase = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError('''Dimensions of self-attention weights do not match.''' ) _UpperCAmelCase = xmod_layer.self_attn.q_proj.weight _UpperCAmelCase = xmod_layer.self_attn.q_proj.bias _UpperCAmelCase = xmod_layer.self_attn.k_proj.weight _UpperCAmelCase = xmod_layer.self_attn.k_proj.bias _UpperCAmelCase = xmod_layer.self_attn.v_proj.weight _UpperCAmelCase = xmod_layer.self_attn.v_proj.bias # self-attention output _UpperCAmelCase = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError('''Dimensions of self-attention output weights do not match.''' ) _UpperCAmelCase = xmod_layer.self_attn.out_proj.weight _UpperCAmelCase = xmod_layer.self_attn.out_proj.bias _UpperCAmelCase = xmod_layer.self_attn_layer_norm.weight _UpperCAmelCase = xmod_layer.self_attn_layer_norm.bias # intermediate _UpperCAmelCase = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('''Dimensions of intermediate weights do not match.''' ) _UpperCAmelCase = xmod_layer.fca.weight _UpperCAmelCase = xmod_layer.fca.bias # output _UpperCAmelCase = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('''Dimensions of feed-forward weights do not match.''' ) _UpperCAmelCase = xmod_layer.fca.weight _UpperCAmelCase = xmod_layer.fca.bias _UpperCAmelCase = xmod_layer.final_layer_norm.weight _UpperCAmelCase = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: _UpperCAmelCase = xmod_layer.adapter_layer_norm.weight _UpperCAmelCase = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError('''Lists of language adapters do not match.''' ) for lang_code, adapter in xmod_layer.adapter_modules.items(): _UpperCAmelCase = bert_output.adapter_modules[lang_code] _UpperCAmelCase = xmod_layer.adapter_modules[lang_code] _UpperCAmelCase = from_adapter.fca.weight _UpperCAmelCase = from_adapter.fca.bias _UpperCAmelCase = from_adapter.fca.weight _UpperCAmelCase = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: _UpperCAmelCase = xmod_sent_encoder.layer_norm.weight _UpperCAmelCase = xmod_sent_encoder.layer_norm.bias if classification_head: _UpperCAmelCase = xmod.model.classification_heads['''mnli'''].dense.weight _UpperCAmelCase = xmod.model.classification_heads['''mnli'''].dense.bias _UpperCAmelCase = xmod.model.classification_heads['''mnli'''].out_proj.weight _UpperCAmelCase = xmod.model.classification_heads['''mnli'''].out_proj.bias else: # LM Head _UpperCAmelCase = xmod.model.encoder.lm_head.dense.weight _UpperCAmelCase = xmod.model.encoder.lm_head.dense.bias _UpperCAmelCase = xmod.model.encoder.lm_head.layer_norm.weight _UpperCAmelCase = xmod.model.encoder.lm_head.layer_norm.bias _UpperCAmelCase = xmod.model.encoder.lm_head.weight _UpperCAmelCase = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. _UpperCAmelCase = xmod.encode(__snake_case ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(__snake_case ) _UpperCAmelCase = model(__snake_case )[0] if classification_head: _UpperCAmelCase = xmod.model.classification_heads['''mnli'''](xmod.extract_features(__snake_case ) ) else: _UpperCAmelCase = xmod.model(__snake_case , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) _UpperCAmelCase = torch.max(torch.abs(our_output - their_output ) ).item() print(f'max_absolute_diff = {max_absolute_diff}' ) # ~ 1e-7 _UpperCAmelCase = torch.allclose(__snake_case , __snake_case , atol=1E-3 ) print('''Do both models output the same tensors?''' , '''🔥''' if success else '''💩''' ) if not success: raise Exception('''Something went wRoNg''' ) Path(__snake_case ).mkdir(parents=__snake_case , exist_ok=__snake_case ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(__snake_case ) if __name__ == "__main__": __A : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xmod_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--classification_head", action="store_true", help="Whether to convert a final classification head." ) __A : int = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
356
"""simple docstring""" import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowercase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any ): '''simple docstring''' with open(_SCREAMING_SNAKE_CASE ) as metadata_file: _UpperCAmelCase = json.load(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = LukeConfig(use_entity_aware_attention=_SCREAMING_SNAKE_CASE , **metadata['''model_config'''] ) # Load in the weights from the checkpoint_path _UpperCAmelCase = torch.load(_SCREAMING_SNAKE_CASE , map_location='''cpu''' )['''module'''] # Load the entity vocab file _UpperCAmelCase = load_original_entity_vocab(_SCREAMING_SNAKE_CASE ) # add an entry for [MASK2] _UpperCAmelCase = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 _UpperCAmelCase = XLMRobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] ) # Add special tokens to the token vocabulary for downstream tasks _UpperCAmelCase = AddedToken('''<ent>''' , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = AddedToken('''<ent2>''' , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(f'Saving tokenizer to {pytorch_dump_folder_path}' ) tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE ) with open(os.path.join(_SCREAMING_SNAKE_CASE , '''tokenizer_config.json''' ) , '''r''' ) as f: _UpperCAmelCase = json.load(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = '''MLukeTokenizer''' with open(os.path.join(_SCREAMING_SNAKE_CASE , '''tokenizer_config.json''' ) , '''w''' ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) with open(os.path.join(_SCREAMING_SNAKE_CASE , MLukeTokenizer.vocab_files_names['''entity_vocab_file'''] ) , '''w''' ) as f: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = MLukeTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) # Initialize the embeddings of the special tokens _UpperCAmelCase = tokenizer.convert_tokens_to_ids(['''@'''] )[0] _UpperCAmelCase = tokenizer.convert_tokens_to_ids(['''#'''] )[0] _UpperCAmelCase = state_dict['''embeddings.word_embeddings.weight'''] _UpperCAmelCase = word_emb[ent_init_index].unsqueeze(0 ) _UpperCAmelCase = word_emb[enta_init_index].unsqueeze(0 ) _UpperCAmelCase = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: _UpperCAmelCase = state_dict[bias_name] _UpperCAmelCase = decoder_bias[ent_init_index].unsqueeze(0 ) _UpperCAmelCase = decoder_bias[enta_init_index].unsqueeze(0 ) _UpperCAmelCase = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: _UpperCAmelCase = f'encoder.layer.{layer_index}.attention.self.' _UpperCAmelCase = state_dict[prefix + matrix_name] _UpperCAmelCase = state_dict[prefix + matrix_name] _UpperCAmelCase = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks _UpperCAmelCase = state_dict['''entity_embeddings.entity_embeddings.weight'''] _UpperCAmelCase = entity_emb[entity_vocab['''[MASK]''']].unsqueeze(0 ) _UpperCAmelCase = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' _UpperCAmelCase = state_dict['''entity_predictions.bias'''] _UpperCAmelCase = entity_prediction_bias[entity_vocab['''[MASK]''']].unsqueeze(0 ) _UpperCAmelCase = torch.cat([entity_prediction_bias, entity_mask_bias] ) _UpperCAmelCase = LukeForMaskedLM(config=_SCREAMING_SNAKE_CASE ).eval() state_dict.pop('''entity_predictions.decoder.weight''' ) state_dict.pop('''lm_head.decoder.weight''' ) state_dict.pop('''lm_head.decoder.bias''' ) _UpperCAmelCase = OrderedDict() for key, value in state_dict.items(): if not (key.startswith('''lm_head''' ) or key.startswith('''entity_predictions''' )): _UpperCAmelCase = state_dict[key] else: _UpperCAmelCase = state_dict[key] _UpperCAmelCase , _UpperCAmelCase = model.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) if set(_SCREAMING_SNAKE_CASE ) != {"luke.embeddings.position_ids"}: raise ValueError(f'Unexpected unexpected_keys: {unexpected_keys}' ) if set(_SCREAMING_SNAKE_CASE ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(f'Unexpected missing_keys: {missing_keys}' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs _UpperCAmelCase = MLukeTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE , task='''entity_classification''' ) _UpperCAmelCase = '''ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).''' _UpperCAmelCase = (0, 9) _UpperCAmelCase = tokenizer(_SCREAMING_SNAKE_CASE , entity_spans=[span] , return_tensors='''pt''' ) _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base _UpperCAmelCase = torch.Size((1, 33, 768) ) _UpperCAmelCase = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( f'Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base _UpperCAmelCase = torch.Size((1, 1, 768) ) _UpperCAmelCase = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( f'Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is' f' {expected_shape}' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction _UpperCAmelCase = MLukeTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = '''Tokyo is the capital of <mask>.''' _UpperCAmelCase = (24, 30) _UpperCAmelCase = tokenizer(_SCREAMING_SNAKE_CASE , entity_spans=[span] , return_tensors='''pt''' ) _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = encoding['''input_ids'''][0].tolist() _UpperCAmelCase = input_ids.index(tokenizer.convert_tokens_to_ids('''<mask>''' ) ) _UpperCAmelCase = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = outputs.entity_logits[0][0].argmax().item() _UpperCAmelCase = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('''en:''' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('''Saving PyTorch model to {}'''.format(_SCREAMING_SNAKE_CASE ) ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) def lowercase ( _SCREAMING_SNAKE_CASE : Tuple ): '''simple docstring''' _UpperCAmelCase = ['''[MASK]''', '''[PAD]''', '''[UNK]'''] _UpperCAmelCase = [json.loads(_SCREAMING_SNAKE_CASE ) for line in open(_SCREAMING_SNAKE_CASE )] _UpperCAmelCase = {} for entry in data: _UpperCAmelCase = entry['''id'''] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: _UpperCAmelCase = entity_id break _UpperCAmelCase = f'{language}:{entity_name}' _UpperCAmelCase = entity_id return new_mapping if __name__ == "__main__": __A : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("--checkpoint_path", type=str, help="Path to a pytorch_model.bin file.") parser.add_argument( "--metadata_path", default=None, type=str, help="Path to a metadata.json file, defining the configuration." ) parser.add_argument( "--entity_vocab_path", default=None, type=str, help="Path to an entity_vocab.tsv file, containing the entity vocabulary.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to where to dump the output PyTorch model." ) parser.add_argument( "--model_size", default="base", type=str, choices=["base", "large"], help="Size of the model to be converted." ) __A : List[str] = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
326
0
'''simple docstring''' import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def _lowerCAmelCase ( _UpperCamelCase : Optional[int] ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =model.config _SCREAMING_SNAKE_CASE =DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=1_28 , ) _SCREAMING_SNAKE_CASE =MBartConfig( is_decoder=_UpperCamelCase , is_encoder_decoder=_UpperCamelCase , add_cross_attention=_UpperCamelCase , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=_UpperCamelCase , add_final_layer_norm=_UpperCamelCase , ) return encoder_config, decoder_config def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] ) -> Optional[Any]: """simple docstring""" if "encoder.model" in name: _SCREAMING_SNAKE_CASE =name.replace('encoder.model' , 'encoder' ) if "decoder.model" in name: _SCREAMING_SNAKE_CASE =name.replace('decoder.model' , 'decoder' ) if "patch_embed.proj" in name: _SCREAMING_SNAKE_CASE =name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: _SCREAMING_SNAKE_CASE =name.replace('patch_embed.norm' , 'embeddings.norm' ) if name.startswith('encoder' ): if "layers" in name: _SCREAMING_SNAKE_CASE ='encoder.' + name if "attn.proj" in name: _SCREAMING_SNAKE_CASE =name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name and "mask" not in name: _SCREAMING_SNAKE_CASE =name.replace('attn' , 'attention.self' ) if "norm1" in name: _SCREAMING_SNAKE_CASE =name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: _SCREAMING_SNAKE_CASE =name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: _SCREAMING_SNAKE_CASE =name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: _SCREAMING_SNAKE_CASE =name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": _SCREAMING_SNAKE_CASE ='encoder.layernorm.weight' if name == "encoder.norm.bias": _SCREAMING_SNAKE_CASE ='encoder.layernorm.bias' return name def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Tuple ) -> Dict: """simple docstring""" for key in orig_state_dict.copy().keys(): _SCREAMING_SNAKE_CASE =orig_state_dict.pop(_UpperCamelCase ) if "qkv" in key: _SCREAMING_SNAKE_CASE =key.split('.' ) _SCREAMING_SNAKE_CASE =int(key_split[3] ) _SCREAMING_SNAKE_CASE =int(key_split[5] ) _SCREAMING_SNAKE_CASE =model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _SCREAMING_SNAKE_CASE =val[:dim, :] _SCREAMING_SNAKE_CASE =val[dim : dim * 2, :] _SCREAMING_SNAKE_CASE =val[-dim:, :] else: _SCREAMING_SNAKE_CASE =val[:dim] _SCREAMING_SNAKE_CASE =val[dim : dim * 2] _SCREAMING_SNAKE_CASE =val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: _SCREAMING_SNAKE_CASE =val return orig_state_dict def _lowerCAmelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Dict=None , _UpperCamelCase : Optional[int]=False ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =DonutModel.from_pretrained(_UpperCamelCase ).eval() # load HuggingFace model _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =get_configs(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =DonutSwinModel(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =MBartForCausalLM(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =VisionEncoderDecoderModel(encoder=_UpperCamelCase , decoder=_UpperCamelCase ) model.eval() _SCREAMING_SNAKE_CASE =original_model.state_dict() _SCREAMING_SNAKE_CASE =convert_state_dict(_UpperCamelCase , _UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # verify results on scanned document _SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/example-documents' ) _SCREAMING_SNAKE_CASE =dataset['test'][0]['image'].convert('RGB' ) _SCREAMING_SNAKE_CASE =XLMRobertaTokenizerFast.from_pretrained(_UpperCamelCase , from_slow=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) _SCREAMING_SNAKE_CASE =DonutProcessor(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =processor(_UpperCamelCase , return_tensors='pt' ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": _SCREAMING_SNAKE_CASE ='<s_docvqa><s_question>{user_input}</s_question><s_answer>' _SCREAMING_SNAKE_CASE ='When is the coffee break?' _SCREAMING_SNAKE_CASE =task_prompt.replace('{user_input}' , _UpperCamelCase ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": _SCREAMING_SNAKE_CASE ='<s_rvlcdip>' elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: _SCREAMING_SNAKE_CASE ='<s_cord>' elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": _SCREAMING_SNAKE_CASE ='s_cord-v2>' elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": _SCREAMING_SNAKE_CASE ='<s_zhtrainticket>' elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt _SCREAMING_SNAKE_CASE ='hello world' else: raise ValueError('Model name not supported' ) _SCREAMING_SNAKE_CASE =original_model.decoder.tokenizer(_UpperCamelCase , add_special_tokens=_UpperCamelCase , return_tensors='pt' )[ 'input_ids' ] _SCREAMING_SNAKE_CASE =original_model.encoder.model.patch_embed(_UpperCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =model.encoder.embeddings(_UpperCamelCase ) assert torch.allclose(_UpperCamelCase , _UpperCamelCase , atol=1E-3 ) # verify encoder hidden states _SCREAMING_SNAKE_CASE =original_model.encoder(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =model.encoder(_UpperCamelCase ).last_hidden_state assert torch.allclose(_UpperCamelCase , _UpperCamelCase , atol=1E-2 ) # verify decoder hidden states _SCREAMING_SNAKE_CASE =original_model(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ).logits _SCREAMING_SNAKE_CASE =model(_UpperCamelCase , decoder_input_ids=_UpperCamelCase ).logits assert torch.allclose(_UpperCamelCase , _UpperCamelCase , atol=1E-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f"Saving model and processor to {pytorch_dump_folder_path}" ) model.save_pretrained(_UpperCamelCase ) processor.save_pretrained(_UpperCamelCase ) if push_to_hub: model.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) processor.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) if __name__ == "__main__": lowerCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) lowerCamelCase : Optional[Any] = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
47
'''simple docstring''' lowerCamelCase : Any = "\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" lowerCamelCase : int = [{"type": "code", "content": INSTALL_CONTENT}] lowerCamelCase : str = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
47
1
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig 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 transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def a ( self ): '''simple docstring''' _lowerCAmelCase : int = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(snake_case__ , 'tf_padding' ) ) self.parent.assertTrue(hasattr(snake_case__ , 'depth_multiplier' ) ) class UpperCamelCase__ : """simple docstring""" def __init__( self , snake_case__ , snake_case__=13 , snake_case__=3 , snake_case__=32 , snake_case__=0.25 , snake_case__=8 , snake_case__=8 , snake_case__=6 , snake_case__=32 , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__="relu6" , snake_case__=1280 , snake_case__=0.1 , snake_case__=0.02 , snake_case__=True , snake_case__=True , snake_case__=10 , snake_case__=None , ): '''simple docstring''' _lowerCAmelCase : str = parent _lowerCAmelCase : Tuple = batch_size _lowerCAmelCase : Dict = num_channels _lowerCAmelCase : List[Any] = image_size _lowerCAmelCase : int = depth_multiplier _lowerCAmelCase : int = depth_divisible_by _lowerCAmelCase : str = min_depth _lowerCAmelCase : Any = expand_ratio _lowerCAmelCase : int = tf_padding _lowerCAmelCase : Dict = output_stride _lowerCAmelCase : List[str] = first_layer_is_expansion _lowerCAmelCase : Tuple = finegrained_output _lowerCAmelCase : int = hidden_act _lowerCAmelCase : Tuple = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) _lowerCAmelCase : Any = classifier_dropout_prob _lowerCAmelCase : int = use_labels _lowerCAmelCase : List[Any] = is_training _lowerCAmelCase : List[str] = num_labels _lowerCAmelCase : Dict = initializer_range _lowerCAmelCase : Union[str, Any] = scope def a ( self ): '''simple docstring''' _lowerCAmelCase : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase : Union[str, Any] = None _lowerCAmelCase : Union[str, Any] = None if self.use_labels: _lowerCAmelCase : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) _lowerCAmelCase : int = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) _lowerCAmelCase : Optional[int] = self.get_config() return config, pixel_values, labels, pixel_labels def a ( self ): '''simple docstring''' return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def a ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = MobileNetVaModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() _lowerCAmelCase : str = model(snake_case__ ) 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, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def a ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' _lowerCAmelCase : List[Any] = self.num_labels _lowerCAmelCase : List[str] = MobileNetVaForImageClassification(snake_case__ ) model.to(snake_case__ ) model.eval() _lowerCAmelCase : List[str] = model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' _lowerCAmelCase : List[Any] = self.num_labels _lowerCAmelCase : List[str] = MobileNetVaForSemanticSegmentation(snake_case__ ) model.to(snake_case__ ) model.eval() _lowerCAmelCase : Any = model(snake_case__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) _lowerCAmelCase : int = model(snake_case__ , labels=snake_case__ ) 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 a ( self ): '''simple docstring''' _lowerCAmelCase : Any = self.prepare_config_and_inputs() _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : str = config_and_inputs _lowerCAmelCase : List[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" __magic_name__ = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) __magic_name__ = ( { "feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification, "image-segmentation": MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) __magic_name__ = False __magic_name__ = False __magic_name__ = False __magic_name__ = False def a ( self ): '''simple docstring''' _lowerCAmelCase : Any = MobileNetVaModelTester(self ) _lowerCAmelCase : Dict = MobileNetVaConfigTester(self , config_class=snake_case__ , has_text_modality=snake_case__ ) def a ( self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='MobileNetV2 does not use inputs_embeds' ) def a ( self ): '''simple docstring''' pass @unittest.skip(reason='MobileNetV2 does not support input and output embeddings' ) def a ( self ): '''simple docstring''' pass @unittest.skip(reason='MobileNetV2 does not output attentions' ) def a ( self ): '''simple docstring''' pass def a ( self ): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : Dict = model_class(snake_case__ ) _lowerCAmelCase : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase : Any = [*signature.parameters.keys()] _lowerCAmelCase : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , snake_case__ ) def a ( self ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def a ( self ): '''simple docstring''' def check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ): _lowerCAmelCase : List[str] = model_class(snake_case__ ) model.to(snake_case__ ) model.eval() with torch.no_grad(): _lowerCAmelCase : List[Any] = model(**self._prepare_for_class(snake_case__ , snake_case__ ) ) _lowerCAmelCase : Optional[int] = outputs.hidden_states _lowerCAmelCase : Dict = 16 self.assertEqual(len(snake_case__ ) , snake_case__ ) _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : str = True check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCAmelCase : str = True check_hidden_states_output(snake_case__ , snake_case__ , snake_case__ ) def a ( self ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case__ ) def a ( self ): '''simple docstring''' _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__ ) @slow def a ( self ): '''simple docstring''' for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : str = MobileNetVaModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) def lowercase (): """simple docstring""" _lowerCAmelCase : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self ): '''simple docstring''' return ( MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224' ) if is_vision_available() else None ) @slow def a ( self ): '''simple docstring''' _lowerCAmelCase : List[Any] = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224' ).to(snake_case__ ) _lowerCAmelCase : Any = self.default_image_processor _lowerCAmelCase : Tuple = prepare_img() _lowerCAmelCase : Dict = image_processor(images=snake_case__ , return_tensors='pt' ).to(snake_case__ ) # forward pass with torch.no_grad(): _lowerCAmelCase : Union[str, Any] = model(**snake_case__ ) # verify the logits _lowerCAmelCase : int = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , snake_case__ ) _lowerCAmelCase : str = torch.tensor([0.2445, -1.1993, 0.1905] ).to(snake_case__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case__ , atol=1E-4 ) ) @slow def a ( self ): '''simple docstring''' _lowerCAmelCase : List[Any] = MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513' ) _lowerCAmelCase : Union[str, Any] = model.to(snake_case__ ) _lowerCAmelCase : str = MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513' ) _lowerCAmelCase : int = prepare_img() _lowerCAmelCase : Tuple = image_processor(images=snake_case__ , return_tensors='pt' ).to(snake_case__ ) # forward pass with torch.no_grad(): _lowerCAmelCase : str = model(**snake_case__ ) _lowerCAmelCase : int = outputs.logits # verify the logits _lowerCAmelCase : int = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , snake_case__ ) _lowerCAmelCase : List[str] = torch.tensor( [ [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]], [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]], [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]], ] , device=snake_case__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , snake_case__ , atol=1E-4 ) )
25
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def a ( self ): '''simple docstring''' _lowerCAmelCase : Tuple = SMALL_MODEL_IDENTIFIER _lowerCAmelCase : Optional[int] = 'pt' _lowerCAmelCase : Tuple = 'tf' def a ( self , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(snake_case__ ) def a ( self , snake_case__ ): '''simple docstring''' _lowerCAmelCase : Tuple = TFAutoModel.from_pretrained(self.test_model , from_pt=snake_case__ ) model_tf.save_pretrained(snake_case__ ) def a ( self ): '''simple docstring''' _lowerCAmelCase : Tuple = 'mock_framework' # Framework provided - return whatever the user provides _lowerCAmelCase : Any = FeaturesManager.determine_framework(self.test_model , snake_case__ ) self.assertEqual(snake_case__ , snake_case__ ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(snake_case__ ) _lowerCAmelCase : Dict = FeaturesManager.determine_framework(snake_case__ , snake_case__ ) self.assertEqual(snake_case__ , snake_case__ ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(snake_case__ ) _lowerCAmelCase : int = FeaturesManager.determine_framework(snake_case__ , snake_case__ ) self.assertEqual(snake_case__ , snake_case__ ) def a ( self ): '''simple docstring''' with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(snake_case__ ) _lowerCAmelCase : Tuple = FeaturesManager.determine_framework(snake_case__ ) self.assertEqual(snake_case__ , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(snake_case__ ) _lowerCAmelCase : Optional[int] = FeaturesManager.determine_framework(snake_case__ ) self.assertEqual(snake_case__ , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(snake_case__ ): _lowerCAmelCase : str = FeaturesManager.determine_framework(snake_case__ ) def a ( self ): '''simple docstring''' _lowerCAmelCase : Optional[int] = MagicMock(return_value=snake_case__ ) with patch('transformers.onnx.features.is_tf_available' , snake_case__ ): _lowerCAmelCase : Any = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(snake_case__ , self.framework_pt ) # PyTorch not in environment -> use TensorFlow _lowerCAmelCase : Any = MagicMock(return_value=snake_case__ ) with patch('transformers.onnx.features.is_torch_available' , snake_case__ ): _lowerCAmelCase : Union[str, Any] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(snake_case__ , self.framework_tf ) # Both in environment -> use PyTorch _lowerCAmelCase : int = MagicMock(return_value=snake_case__ ) _lowerCAmelCase : Optional[int] = MagicMock(return_value=snake_case__ ) with patch('transformers.onnx.features.is_tf_available' , snake_case__ ), patch( 'transformers.onnx.features.is_torch_available' , snake_case__ ): _lowerCAmelCase : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(snake_case__ , self.framework_pt ) # Both not in environment -> raise error _lowerCAmelCase : str = MagicMock(return_value=snake_case__ ) _lowerCAmelCase : Optional[Any] = MagicMock(return_value=snake_case__ ) with patch('transformers.onnx.features.is_tf_available' , snake_case__ ), patch( 'transformers.onnx.features.is_torch_available' , snake_case__ ): with self.assertRaises(snake_case__ ): _lowerCAmelCase : Any = FeaturesManager.determine_framework(self.test_model )
25
1
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _UpperCAmelCase = trt.Logger(trt.Logger.WARNING) _UpperCAmelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _UpperCAmelCase = logging.getLogger(__name__) _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--onnx_model_path""", default=None, type=str, required=True, help="""Path to ONNX model: """, ) parser.add_argument( """--output_dir""", default=None, type=str, required=True, help="""The output directory where the model checkpoints and predictions will be written.""", ) # Other parameters parser.add_argument( """--tokenizer_name""", default="""""", type=str, required=True, help="""Pretrained tokenizer name or path if not the same as model_name""", ) parser.add_argument( """--version_2_with_negative""", action="""store_true""", help="""If true, the SQuAD examples contain some that do not have an answer.""", ) parser.add_argument( """--null_score_diff_threshold""", type=float, default=0.0, help="""If null_score - best_non_null is greater than the threshold predict null.""", ) parser.add_argument( """--max_seq_length""", default=3_8_4, type=int, help=( """The maximum total input sequence length after WordPiece tokenization. Sequences """ """longer than this will be truncated, and sequences shorter than this will be padded.""" ), ) parser.add_argument( """--doc_stride""", default=1_2_8, type=int, help="""When splitting up a long document into chunks, how much stride to take between chunks.""", ) parser.add_argument("""--per_device_eval_batch_size""", default=8, type=int, help="""Batch size per GPU/CPU for evaluation.""") parser.add_argument( """--n_best_size""", default=2_0, type=int, help="""The total number of n-best predictions to generate in the nbest_predictions.json output file.""", ) parser.add_argument( """--max_answer_length""", default=3_0, type=int, help=( """The maximum length of an answer that can be generated. This is needed because the start """ """and end predictions are not conditioned on one another.""" ), ) parser.add_argument("""--seed""", type=int, default=4_2, help="""random seed for initialization""") parser.add_argument( """--dataset_name""", type=str, default=None, required=True, help="""The name of the dataset to use (via the datasets library).""", ) parser.add_argument( """--dataset_config_name""", type=str, default=None, help="""The configuration name of the dataset to use (via the datasets library).""", ) parser.add_argument( """--preprocessing_num_workers""", type=int, default=4, help="""A csv or a json file containing the training data.""" ) parser.add_argument("""--overwrite_cache""", action="""store_true""", help="""Overwrite the cached training and evaluation sets""") parser.add_argument( """--fp16""", action="""store_true""", help="""Whether to use 16-bit (mixed) precision instead of 32-bit""", ) parser.add_argument( """--int8""", action="""store_true""", help="""Whether to use INT8""", ) _UpperCAmelCase = parser.parse_args() if args.tokenizer_name: _UpperCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) logger.info("""Training/evaluation parameters %s""", args) _UpperCAmelCase = args.per_device_eval_batch_size _UpperCAmelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _UpperCAmelCase = True _UpperCAmelCase = """temp_engine/bert-fp32.engine""" if args.fpaa: _UpperCAmelCase = """temp_engine/bert-fp16.engine""" if args.inta: _UpperCAmelCase = """temp_engine/bert-int8.engine""" # import ONNX file if not os.path.exists("""temp_engine"""): os.makedirs("""temp_engine""") _UpperCAmelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, """rb""") as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _UpperCAmelCase = [network.get_input(i) for i in range(network.num_inputs)] _UpperCAmelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _UpperCAmelCase = 1 << 5_0 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _UpperCAmelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _UpperCAmelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, """wb""") as f: f.write(engine.serialize()) def __magic_name__ ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): SCREAMING_SNAKE_CASE_: Optional[Any] =np.asarray(inputs["""input_ids"""] , dtype=np.intaa ) SCREAMING_SNAKE_CASE_: Dict =np.asarray(inputs["""attention_mask"""] , dtype=np.intaa ) SCREAMING_SNAKE_CASE_: Dict =np.asarray(inputs["""token_type_ids"""] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase ) # start time SCREAMING_SNAKE_CASE_: List[Any] =time.time() # Run inference context.execute_async( bindings=[int(lowercase ) for d_inp in d_inputs] + [int(lowercase ), int(lowercase )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase , lowercase , lowercase ) cuda.memcpy_dtoh_async(lowercase , lowercase , lowercase ) # Synchronize the stream and take time stream.synchronize() # end time SCREAMING_SNAKE_CASE_: str =time.time() SCREAMING_SNAKE_CASE_: int =end_time - start_time SCREAMING_SNAKE_CASE_: Optional[int] =(h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _UpperCAmelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _UpperCAmelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError("""Evaluation requires a dataset name""") # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _UpperCAmelCase = raw_datasets["""validation"""].column_names _UpperCAmelCase = """question""" if """question""" in column_names else column_names[0] _UpperCAmelCase = """context""" if """context""" in column_names else column_names[1] _UpperCAmelCase = """answers""" if """answers""" in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _UpperCAmelCase = tokenizer.padding_side == """right""" if args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) _UpperCAmelCase = min(args.max_seq_length, tokenizer.model_max_length) def __magic_name__ ( lowercase ): # Some of the questions have lots of whitespace on the left, which is not useful and will make the # truncation of the context fail (the tokenized question will take a lots of space). So we remove that # left whitespace SCREAMING_SNAKE_CASE_: List[Any] =[q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. SCREAMING_SNAKE_CASE_: Any =tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation="""only_second""" if pad_on_right else """only_first""" , max_length=lowercase , stride=args.doc_stride , return_overflowing_tokens=lowercase , return_offsets_mapping=lowercase , padding="""max_length""" , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. SCREAMING_SNAKE_CASE_: int =tokenized_examples.pop("""overflow_to_sample_mapping""" ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. SCREAMING_SNAKE_CASE_: Dict =[] for i in range(len(tokenized_examples["""input_ids"""] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). SCREAMING_SNAKE_CASE_: Optional[int] =tokenized_examples.sequence_ids(lowercase ) SCREAMING_SNAKE_CASE_: str =1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. SCREAMING_SNAKE_CASE_: Any =sample_mapping[i] tokenized_examples["example_id"].append(examples["""id"""][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. SCREAMING_SNAKE_CASE_: List[Any] =[ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples["""offset_mapping"""][i] ) ] return tokenized_examples _UpperCAmelCase = raw_datasets["""validation"""] # Validation Feature Creation _UpperCAmelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc="""Running tokenizer on validation dataset""", ) _UpperCAmelCase = default_data_collator _UpperCAmelCase = eval_dataset.remove_columns(["""example_id""", """offset_mapping"""]) _UpperCAmelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def __magic_name__ ( lowercase , lowercase , lowercase , lowercase="eval" ): # Post-processing: we match the start logits and end logits to answers in the original context. SCREAMING_SNAKE_CASE_: List[str] =postprocess_qa_predictions( examples=lowercase , features=lowercase , predictions=lowercase , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase , ) # Format the result to the format the metric expects. if args.version_2_with_negative: SCREAMING_SNAKE_CASE_: List[Any] =[ {"""id""": k, """prediction_text""": v, """no_answer_probability""": 0.0} for k, v in predictions.items() ] else: SCREAMING_SNAKE_CASE_: Any =[{"""id""": k, """prediction_text""": v} for k, v in predictions.items()] SCREAMING_SNAKE_CASE_: Optional[int] =[{"""id""": ex["""id"""], """answers""": ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase , label_ids=lowercase ) _UpperCAmelCase = load_metric("""squad_v2""" if args.version_2_with_negative else """squad""") # Evaluation! logger.info("""Loading ONNX model %s for evaluation""", args.onnx_model_path) with open(engine_name, """rb""") as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def __magic_name__ ( lowercase ): return trt.volume(engine.get_binding_shape(lowercase ) ) * engine.get_binding_dtype(lowercase ).itemsize # Allocate device memory for inputs and outputs. _UpperCAmelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _UpperCAmelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _UpperCAmelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _UpperCAmelCase = cuda.mem_alloc(h_outputa.nbytes) _UpperCAmelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _UpperCAmelCase = cuda.Stream() # Evaluation logger.info("""***** Running Evaluation *****""") logger.info(f""" Num examples = {len(eval_dataset)}""") logger.info(f""" Batch size = {args.per_device_eval_batch_size}""") _UpperCAmelCase = 0.0 _UpperCAmelCase = 0 _UpperCAmelCase = timeit.default_timer() _UpperCAmelCase = None for step, batch in enumerate(eval_dataloader): _UpperCAmelCase, _UpperCAmelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _UpperCAmelCase, _UpperCAmelCase = outputs _UpperCAmelCase = torch.tensor(start_logits) _UpperCAmelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _UpperCAmelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_0_0) _UpperCAmelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_0_0) _UpperCAmelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _UpperCAmelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_0_0) if all_preds is not None: _UpperCAmelCase = nested_truncate(all_preds, len(eval_dataset)) _UpperCAmelCase = timeit.default_timer() - start_time logger.info(""" Evaluation done in total %f secs (%f sec per example)""", evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info("""Average Inference Time = {:.3f} ms""".format(total_time * 1_0_0_0 / niter)) logger.info("""Total Inference Time = {:.3f} ms""".format(total_time * 1_0_0_0)) logger.info("""Total Number of Inference = %d""", niter) _UpperCAmelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _UpperCAmelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f"""Evaluation metrics: {eval_metric}""")
173
"""simple docstring""" import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin _UpperCAmelCase = get_tests_dir("""fixtures/test_sentencepiece.model""") _UpperCAmelCase = {"""target_lang""": """fi""", """source_lang""": """en"""} _UpperCAmelCase = """>>zh<<""" _UpperCAmelCase = """Helsinki-NLP/""" if is_torch_available(): _UpperCAmelCase = """pt""" elif is_tf_available(): _UpperCAmelCase = """tf""" else: _UpperCAmelCase = """jax""" @require_sentencepiece class a ( UpperCAmelCase__ , unittest.TestCase ): UpperCamelCase : Any = MarianTokenizer UpperCamelCase : List[Any] = False UpperCamelCase : Optional[Any] = True def lowerCamelCase__ ( self : Optional[Any] ) -> int: '''simple docstring''' super().setUp() SCREAMING_SNAKE_CASE_: str =["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] SCREAMING_SNAKE_CASE_: List[Any] =dict(zip(lowerCAmelCase , range(len(lowerCAmelCase ) ) ) ) SCREAMING_SNAKE_CASE_: Optional[int] =Path(self.tmpdirname ) save_json(lowerCAmelCase , save_dir / VOCAB_FILES_NAMES["""vocab"""] ) save_json(lowerCAmelCase , save_dir / VOCAB_FILES_NAMES["""tokenizer_config_file"""] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(lowerCAmelCase , save_dir / VOCAB_FILES_NAMES["""source_spm"""] ) copyfile(lowerCAmelCase , save_dir / VOCAB_FILES_NAMES["""target_spm"""] ) SCREAMING_SNAKE_CASE_: str =MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self : str , **lowerCAmelCase : Any ) -> MarianTokenizer: '''simple docstring''' return MarianTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase ) def lowerCamelCase__ ( self : Union[str, Any] , lowerCAmelCase : List[str] ) -> int: '''simple docstring''' return ( "This is a test", "This is a test", ) def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] ="""</s>""" SCREAMING_SNAKE_CASE_: List[str] =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase ) , lowerCAmelCase ) def lowerCamelCase__ ( self : str ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """</s>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """<pad>""" ) self.assertEqual(len(lowerCAmelCase ) , 9 ) def lowerCamelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[Any] =MarianTokenizer.from_pretrained(f'''{ORG_NAME}opus-mt-en-de''' ) SCREAMING_SNAKE_CASE_: List[Any] =en_de_tokenizer(["""I am a small frog"""] , return_tensors=lowerCAmelCase ) self.assertIsInstance(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =[38, 121, 14, 697, 3_8848, 0] self.assertListEqual(lowerCAmelCase , batch.input_ids[0] ) SCREAMING_SNAKE_CASE_: Optional[int] =tempfile.mkdtemp() en_de_tokenizer.save_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =[x.name for x in Path(lowerCAmelCase ).glob("""*""" )] self.assertIn("""source.spm""" , lowerCAmelCase ) MarianTokenizer.from_pretrained(lowerCAmelCase ) def lowerCamelCase__ ( self : int ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple =self.get_tokenizer() SCREAMING_SNAKE_CASE_: str =tok( ["""I am a small frog""" * 1000, """I am a small frog"""] , padding=lowerCAmelCase , truncation=lowerCAmelCase , return_tensors=lowerCAmelCase ) self.assertIsInstance(lowerCAmelCase , lowerCAmelCase ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def lowerCamelCase__ ( self : Optional[int] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =self.get_tokenizer() SCREAMING_SNAKE_CASE_: int =tok(["""I am a tiny frog""", """I am a small frog"""] , padding=lowerCAmelCase , return_tensors=lowerCAmelCase ) self.assertIsInstance(lowerCAmelCase , lowerCAmelCase ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def lowerCamelCase__ ( self : str ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_: Tuple ={"""input_ids""": [[4_3495, 462, 20, 4_2164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 3_8999, 6, 8, 464, 132, 1703, 492, 13, 4669, 3_7867, 13, 7525, 27, 1593, 988, 13, 3_3972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 1_2338, 2, 1_3958, 387, 2, 3629, 6953, 188, 2900, 2, 1_3958, 8011, 1_1501, 23, 8460, 4073, 3_4009, 20, 435, 1_1439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 3_7867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 2_6453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 1_0767, 6, 316, 304, 4239, 3, 0], [148, 1_5722, 19, 1839, 12, 1350, 13, 2_2327, 5082, 5418, 4_7567, 3_5938, 59, 318, 1_9552, 108, 2183, 54, 1_4976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 1_9088, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100], [36, 6395, 1_2570, 3_9147, 1_1597, 6, 266, 4, 4_5405, 7296, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase , model_name="""Helsinki-NLP/opus-mt-en-de""" , revision="""1a8c2263da11e68e50938f97e10cd57820bd504c""" , decode_kwargs={"""use_source_tokenizer""": True} , ) def lowerCamelCase__ ( self : int ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =MarianTokenizer.from_pretrained("""hf-internal-testing/test-marian-two-vocabs""" ) SCREAMING_SNAKE_CASE_: Optional[int] ="""Tämä on testi""" SCREAMING_SNAKE_CASE_: Union[str, Any] ="""This is a test""" SCREAMING_SNAKE_CASE_: List[Any] =[76, 7, 2047, 2] SCREAMING_SNAKE_CASE_: Any =[69, 12, 11, 940, 2] SCREAMING_SNAKE_CASE_: Optional[int] =tokenizer(lowerCAmelCase ).input_ids self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =tokenizer(text_target=lowerCAmelCase ).input_ids self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =tokenizer.decode(lowerCAmelCase , skip_special_tokens=lowerCAmelCase ) self.assertEqual(lowerCAmelCase , lowerCAmelCase )
173
1
# flake8: noqa # Lint as: python3 from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_table, query_table, ) from .np_formatter import NumpyFormatter UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} def lowerCamelCase__ ( A__ : type , A__ : Optional[str] , A__ : Optional[List[str]] = None , ): '''simple docstring''' __lowerCamelCase = aliases if aliases is not None else [] if format_type in _FORMAT_TYPES: logger.warning( f'Overwriting format type \'{format_type}\' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})' ) __lowerCamelCase = formatter_cls for alias in set(aliases + [format_type] ): if alias in _FORMAT_TYPES_ALIASES: logger.warning( f'Overwriting format type alias \'{alias}\' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})' ) __lowerCamelCase = format_type def lowerCamelCase__ ( A__ : Exception , A__ : Optional[str] , A__ : Optional[List[str]] = None ): '''simple docstring''' __lowerCamelCase = aliases if aliases is not None else [] for alias in set(aliases + [format_type] ): __lowerCamelCase = unavailable_error # Here we define all the available formatting functions that can be used by `Dataset.set_format` _register_formatter(PythonFormatter, None, aliases=['python']) _register_formatter(ArrowFormatter, 'arrow', aliases=['pa', 'pyarrow']) _register_formatter(NumpyFormatter, 'numpy', aliases=['np']) _register_formatter(PandasFormatter, 'pandas', aliases=['pd']) _register_formatter(CustomFormatter, 'custom') if config.TORCH_AVAILABLE: from .torch_formatter import TorchFormatter _register_formatter(TorchFormatter, 'torch', aliases=['pt', 'pytorch']) else: UpperCAmelCase_ = ValueError('PyTorch needs to be installed to be able to return PyTorch tensors.') _register_unavailable_formatter(_torch_error, 'torch', aliases=['pt', 'pytorch']) if config.TF_AVAILABLE: from .tf_formatter import TFFormatter _register_formatter(TFFormatter, 'tensorflow', aliases=['tf']) else: UpperCAmelCase_ = ValueError('Tensorflow needs to be installed to be able to return Tensorflow tensors.') _register_unavailable_formatter(_tf_error, 'tensorflow', aliases=['tf']) if config.JAX_AVAILABLE: from .jax_formatter import JaxFormatter _register_formatter(JaxFormatter, 'jax', aliases=[]) else: UpperCAmelCase_ = ValueError('JAX needs to be installed to be able to return JAX arrays.') _register_unavailable_formatter(_jax_error, 'jax', aliases=[]) def lowerCamelCase__ ( A__ : Optional[str] ): '''simple docstring''' if format_type in _FORMAT_TYPES_ALIASES: return _FORMAT_TYPES_ALIASES[format_type] else: return format_type def lowerCamelCase__ ( A__ : Optional[str] , **A__ : Dict ): '''simple docstring''' __lowerCamelCase = get_format_type_from_alias(A__ ) if format_type in _FORMAT_TYPES: return _FORMAT_TYPES[format_type](**A__ ) if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE: raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type] else: raise ValueError( f'Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None )}, but got \'{format_type}\'' )
29
from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging 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_VISUAL_QUESTION_ANSWERING_MAPPING UpperCAmelCase_ = logging.get_logger(__name__) @add_end_docstrings(__lowerCamelCase) class lowerCamelCase__( __lowerCamelCase): def __init__( self: List[Any] , *UpperCamelCase_: Dict , **UpperCamelCase_: Dict ): super().__init__(*UpperCamelCase_ , **UpperCamelCase_ ) self.check_model_type(UpperCamelCase_ ) def lowerCAmelCase__ ( self: Tuple , UpperCamelCase_: str=None , UpperCamelCase_: Optional[int]=None , UpperCamelCase_: Optional[int]=None , **UpperCamelCase_: List[Any] ): __lowerCamelCase, __lowerCamelCase = {}, {} if padding is not None: __lowerCamelCase = padding if truncation is not None: __lowerCamelCase = truncation if top_k is not None: __lowerCamelCase = top_k return preprocess_params, {}, postprocess_params def __call__( self: Optional[Any] , UpperCamelCase_: Union["Image.Image", str] , UpperCamelCase_: str = None , **UpperCamelCase_: List[str] ): if isinstance(UpperCamelCase_ , (Image.Image, str) ) and isinstance(UpperCamelCase_ , UpperCamelCase_ ): __lowerCamelCase = {"""image""": image, """question""": question} else: __lowerCamelCase = image __lowerCamelCase = super().__call__(UpperCamelCase_ , **UpperCamelCase_ ) return results def lowerCAmelCase__ ( self: Tuple , UpperCamelCase_: str , UpperCamelCase_: Any=False , UpperCamelCase_: Optional[int]=False ): __lowerCamelCase = load_image(inputs["""image"""] ) __lowerCamelCase = self.tokenizer( inputs["""question"""] , return_tensors=self.framework , padding=UpperCamelCase_ , truncation=UpperCamelCase_ ) __lowerCamelCase = self.image_processor(images=UpperCamelCase_ , return_tensors=self.framework ) model_inputs.update(UpperCamelCase_ ) return model_inputs def lowerCAmelCase__ ( self: Optional[int] , UpperCamelCase_: Tuple ): __lowerCamelCase = self.model(**UpperCamelCase_ ) return model_outputs def lowerCAmelCase__ ( self: List[str] , UpperCamelCase_: Optional[int] , UpperCamelCase_: Optional[Any]=5 ): if top_k > self.model.config.num_labels: __lowerCamelCase = self.model.config.num_labels if self.framework == "pt": __lowerCamelCase = model_outputs.logits.sigmoid()[0] __lowerCamelCase, __lowerCamelCase = probs.topk(UpperCamelCase_ ) else: raise ValueError(F'Unsupported framework: {self.framework}' ) __lowerCamelCase = scores.tolist() __lowerCamelCase = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(UpperCamelCase_ , UpperCamelCase_ )]
29
1
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ('''dense.weight''', '''attention.self.query''', '''attention.self.key''', '''attention.self.value''') __SCREAMING_SNAKE_CASE : int = ( ('''layer.''', '''layer_'''), ('''word_embeddings.weight''', '''word_embeddings'''), ('''position_embeddings.weight''', '''position_embeddings'''), ('''token_type_embeddings.weight''', '''token_type_embeddings'''), ('''.''', '''/'''), ('''LayerNorm/weight''', '''LayerNorm/gamma'''), ('''LayerNorm/bias''', '''LayerNorm/beta'''), ('''weight''', '''kernel'''), ) if not os.path.isdir(lowercase__ ): os.makedirs(lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = model.state_dict() def to_tf_var_name(lowercase__ ): for patt, repl in iter(lowercase__ ): __SCREAMING_SNAKE_CASE : Any = name.replace(lowercase__ , lowercase__ ) return F'''bert/{name}''' def create_tf_var(lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tf.dtypes.as_dtype(tensor.dtype ) __SCREAMING_SNAKE_CASE : int = tf.get_variable(dtype=lowercase__ , shape=tensor.shape , name=lowercase__ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(lowercase__ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: __SCREAMING_SNAKE_CASE : Union[str, Any] = to_tf_var_name(lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): __SCREAMING_SNAKE_CASE : Dict = torch_tensor.T __SCREAMING_SNAKE_CASE : Optional[Any] = create_tf_var(tensor=lowercase__ , name=lowercase__ , session=lowercase__ ) tf.keras.backend.set_value(lowercase__ , lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = session.run(lowercase__ ) print(F'''Successfully created {tf_name}: {np.allclose(lowercase__ , lowercase__ )}''' ) __SCREAMING_SNAKE_CASE : Dict = tf.train.Saver(tf.trainable_variables() ) saver.save(lowercase__ , os.path.join(lowercase__ , model_name.replace('''-''' , '''_''' ) + '''.ckpt''' ) ) def _UpperCamelCase ( lowercase__=None ): __SCREAMING_SNAKE_CASE : Dict = argparse.ArgumentParser() parser.add_argument('''--model_name''' , type=lowercase__ , required=lowercase__ , help='''model name e.g. bert-base-uncased''' ) parser.add_argument( '''--cache_dir''' , type=lowercase__ , default=lowercase__ , required=lowercase__ , help='''Directory containing pytorch model''' ) parser.add_argument('''--pytorch_model_path''' , type=lowercase__ , required=lowercase__ , help='''/path/to/<pytorch-model-name>.bin''' ) parser.add_argument('''--tf_cache_dir''' , type=lowercase__ , required=lowercase__ , help='''Directory in which to save tensorflow model''' ) __SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args(lowercase__ ) __SCREAMING_SNAKE_CASE : int = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=lowercase__ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
9
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __lowerCAmelCase : Optional[int] =logging.get_logger(__name__) __lowerCAmelCase : Optional[Any] ={'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} __lowerCAmelCase : List[str] ={ 'tokenizer_file': { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json', }, } __lowerCAmelCase : Optional[int] ={ 'gpt-neox-20b': 2_0_4_8, } class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ : Dict = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ : Optional[Any] = ['''input_ids''', '''attention_mask'''] def __init__( self :int , lowerCAmelCase__ :Any=None , lowerCAmelCase__ :Optional[Any]=None , lowerCAmelCase__ :List[Any]=None , lowerCAmelCase__ :str="<|endoftext|>" , lowerCAmelCase__ :str="<|endoftext|>" , lowerCAmelCase__ :Dict="<|endoftext|>" , lowerCAmelCase__ :Union[str, Any]=False , **lowerCAmelCase__ :List[str] , ) -> Any: super().__init__( lowerCAmelCase__ , lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ , **lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE : List[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , lowerCAmelCase__ ) != add_prefix_space: __SCREAMING_SNAKE_CASE : List[str] = getattr(lowerCAmelCase__ , pre_tok_state.pop('''type''' ) ) __SCREAMING_SNAKE_CASE : str = add_prefix_space __SCREAMING_SNAKE_CASE : Any = pre_tok_class(**lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = add_prefix_space def __magic_name__( self :Union[str, Any] , lowerCAmelCase__ :str , lowerCAmelCase__ :Optional[str] = None ) -> Tuple[str]: __SCREAMING_SNAKE_CASE : List[str] = self._tokenizer.model.save(lowerCAmelCase__ , name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ ) def __magic_name__( self :Optional[Any] , lowerCAmelCase__ :"Conversation" ) -> List[int]: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) + [self.eos_token_id] ) if len(lowerCAmelCase__ ) > self.model_max_length: __SCREAMING_SNAKE_CASE : List[str] = input_ids[-self.model_max_length :] return input_ids
9
1
"""simple docstring""" import gc import unittest from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline from diffusers.utils import is_flax_available, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class __a ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): super().tearDown() gc.collect() def _lowerCAmelCase ( self : List[str] ): UpperCamelCase__ : int =FlaxStableDiffusionPipeline.from_pretrained( '''stabilityai/stable-diffusion-2''' , revision='''bf16''' , dtype=jnp.bfloataa , ) UpperCamelCase__ : Union[str, Any] ='A painting of a squirrel eating a burger' UpperCamelCase__ : Optional[Any] =jax.device_count() UpperCamelCase__ : Union[str, Any] =num_samples * [prompt] UpperCamelCase__ : Tuple =sd_pipe.prepare_inputs(lowercase_ ) UpperCamelCase__ : List[Any] =replicate(lowercase_ ) UpperCamelCase__ : Dict =shard(lowercase_ ) UpperCamelCase__ : Tuple =jax.random.PRNGKey(0 ) UpperCamelCase__ : Optional[int] =jax.random.split(lowercase_ , jax.device_count() ) UpperCamelCase__ : Tuple =sd_pipe(lowercase_ , lowercase_ , lowercase_ , num_inference_steps=25 , jit=lowercase_ )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) UpperCamelCase__ : Dict =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) UpperCamelCase__ : Any =images[0, 253:256, 253:256, -1] UpperCamelCase__ : int =jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase__ : str =jnp.array([0.4_2_3_8, 0.4_4_1_4, 0.4_3_9_5, 0.4_4_5_3, 0.4_6_2_9, 0.4_5_9_0, 0.4_5_3_1, 0.4_5_5_0_8, 0.4_5_1_2] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def _lowerCAmelCase ( self : str ): UpperCamelCase__ : int ='stabilityai/stable-diffusion-2' UpperCamelCase__ : List[str] =FlaxDPMSolverMultistepScheduler.from_pretrained(lowercase_ , subfolder='''scheduler''' ) UpperCamelCase__ : Optional[Any] =FlaxStableDiffusionPipeline.from_pretrained( lowercase_ , scheduler=lowercase_ , revision='''bf16''' , dtype=jnp.bfloataa , ) UpperCamelCase__ : int =scheduler_params UpperCamelCase__ : Any ='A painting of a squirrel eating a burger' UpperCamelCase__ : Optional[int] =jax.device_count() UpperCamelCase__ : List[Any] =num_samples * [prompt] UpperCamelCase__ : str =sd_pipe.prepare_inputs(lowercase_ ) UpperCamelCase__ : List[Any] =replicate(lowercase_ ) UpperCamelCase__ : List[str] =shard(lowercase_ ) UpperCamelCase__ : int =jax.random.PRNGKey(0 ) UpperCamelCase__ : List[Any] =jax.random.split(lowercase_ , jax.device_count() ) UpperCamelCase__ : Union[str, Any] =sd_pipe(lowercase_ , lowercase_ , lowercase_ , num_inference_steps=25 , jit=lowercase_ )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) UpperCamelCase__ : Union[str, Any] =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) UpperCamelCase__ : List[Any] =images[0, 253:256, 253:256, -1] UpperCamelCase__ : Tuple =jnp.asarray(jax.device_get(image_slice.flatten() ) ) UpperCamelCase__ : int =jnp.array([0.4_3_3_6, 0.4_2_9_6_9, 0.4_4_5_3, 0.4_1_9_9, 0.4_2_9_7, 0.4_5_3_1, 0.4_4_3_4, 0.4_4_3_4, 0.4_2_9_7] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
368
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys _SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output("""git merge-base main HEAD""".split()).decode("""utf-8""") _SCREAMING_SNAKE_CASE : List[Any] = ( subprocess.check_output(F'''git diff --diff-filter=d --name-only {fork_point_sha}'''.split()).decode("""utf-8""").split() ) _SCREAMING_SNAKE_CASE : Tuple = """|""".join(sys.argv[1:]) _SCREAMING_SNAKE_CASE : Union[str, Any] = re.compile(rF'''^({joined_dirs}).*?\.py$''') _SCREAMING_SNAKE_CASE : str = [x for x in modified_files if regex.match(x)] print(""" """.join(relevant_modified_files), end="""""")
157
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __A = logging.get_logger(__name__) if is_vision_available(): import PIL class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" snake_case_ = ['''pixel_values'''] def __init__( self , lowerCamelCase__ = True , lowerCamelCase__ = None , lowerCamelCase__ = PILImageResampling.BICUBIC , lowerCamelCase__ = True , lowerCamelCase__ = None , lowerCamelCase__ = True , lowerCamelCase__ = 1 / 255 , lowerCamelCase__ = True , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = True , **lowerCamelCase__ , ) -> None: '''simple docstring''' super().__init__(**lowerCamelCase__ ) __lowerCamelCase = size if size is not None else {'shortest_edge': 224} __lowerCamelCase = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ ) __lowerCamelCase = crop_size if crop_size is not None else {'height': 224, 'width': 224} __lowerCamelCase = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ , param_name='crop_size' ) __lowerCamelCase = do_resize __lowerCamelCase = size __lowerCamelCase = resample __lowerCamelCase = do_center_crop __lowerCamelCase = crop_size __lowerCamelCase = do_rescale __lowerCamelCase = rescale_factor __lowerCamelCase = do_normalize __lowerCamelCase = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __lowerCamelCase = image_std if image_std is not None else OPENAI_CLIP_STD __lowerCamelCase = do_convert_rgb def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = PILImageResampling.BICUBIC , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> np.ndarray: '''simple docstring''' __lowerCamelCase = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ ) if "shortest_edge" not in size: raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) __lowerCamelCase = get_resize_output_image_size(lowerCamelCase__ , size=size['shortest_edge'] , default_to_square=lowerCamelCase__ ) return resize(lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> np.ndarray: '''simple docstring''' __lowerCamelCase = get_size_dict(lowerCamelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(lowerCamelCase__ , size=(size['height'], size['width']) , data_format=lowerCamelCase__ , **lowerCamelCase__ ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> Any: '''simple docstring''' return rescale(lowerCamelCase__ , scale=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None , **lowerCamelCase__ , ) -> np.ndarray: '''simple docstring''' return normalize(lowerCamelCase__ , mean=lowerCamelCase__ , std=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = ChannelDimension.FIRST , **lowerCamelCase__ , ) -> PIL.Image.Image: '''simple docstring''' __lowerCamelCase = do_resize if do_resize is not None else self.do_resize __lowerCamelCase = size if size is not None else self.size __lowerCamelCase = get_size_dict(lowerCamelCase__ , param_name='size' , default_to_square=lowerCamelCase__ ) __lowerCamelCase = resample if resample is not None else self.resample __lowerCamelCase = do_center_crop if do_center_crop is not None else self.do_center_crop __lowerCamelCase = crop_size if crop_size is not None else self.crop_size __lowerCamelCase = get_size_dict(lowerCamelCase__ , param_name='crop_size' , default_to_square=lowerCamelCase__ ) __lowerCamelCase = do_rescale if do_rescale is not None else self.do_rescale __lowerCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor __lowerCamelCase = do_normalize if do_normalize is not None else self.do_normalize __lowerCamelCase = image_mean if image_mean is not None else self.image_mean __lowerCamelCase = image_std if image_std is not None else self.image_std __lowerCamelCase = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __lowerCamelCase = make_list_of_images(lowerCamelCase__ ) if not valid_images(lowerCamelCase__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __lowerCamelCase = [convert_to_rgb(lowerCamelCase__ ) for image in images] # All transformations expect numpy arrays. __lowerCamelCase = [to_numpy_array(lowerCamelCase__ ) for image in images] if do_resize: __lowerCamelCase = [self.resize(image=lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ ) for image in images] if do_center_crop: __lowerCamelCase = [self.center_crop(image=lowerCamelCase__ , size=lowerCamelCase__ ) for image in images] if do_rescale: __lowerCamelCase = [self.rescale(image=lowerCamelCase__ , scale=lowerCamelCase__ ) for image in images] if do_normalize: __lowerCamelCase = [self.normalize(image=lowerCamelCase__ , mean=lowerCamelCase__ , std=lowerCamelCase__ ) for image in images] __lowerCamelCase = [to_channel_dimension_format(lowerCamelCase__ , lowerCamelCase__ ) for image in images] __lowerCamelCase = {'pixel_values': images} return BatchFeature(data=lowerCamelCase__ , tensor_type=lowerCamelCase__ )
90
import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" def __init__( self , lowerCamelCase__ , lowerCamelCase__=13 , lowerCamelCase__=7 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=99 , lowerCamelCase__=32 , lowerCamelCase__=5 , lowerCamelCase__=4 , lowerCamelCase__=37 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=512 , lowerCamelCase__=16 , lowerCamelCase__=2 , lowerCamelCase__=0.02 , lowerCamelCase__=False , lowerCamelCase__=True , lowerCamelCase__="None" , lowerCamelCase__=3 , lowerCamelCase__=4 , lowerCamelCase__=None , ) -> int: '''simple docstring''' __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_input_mask __lowerCamelCase = use_token_type_ids __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = type_sequence_label_size __lowerCamelCase = initializer_range __lowerCamelCase = num_labels __lowerCamelCase = num_choices __lowerCamelCase = relative_attention __lowerCamelCase = position_biased_input __lowerCamelCase = pos_att_type __lowerCamelCase = scope def lowercase_ ( self ) -> str: '''simple docstring''' __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase = None if self.use_input_mask: __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __lowerCamelCase = None if self.use_token_type_ids: __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None if self.use_labels: __lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __lowerCamelCase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ ( self ) -> Optional[Any]: '''simple docstring''' return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def lowercase_ ( self ) -> List[str]: '''simple docstring''' __lowerCamelCase = self.get_config() __lowerCamelCase = 300 return config def lowercase_ ( self , lowerCamelCase__ ) -> Optional[int]: '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: '''simple docstring''' __lowerCamelCase = DebertaModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ )[0] __lowerCamelCase = model(lowerCamelCase__ , token_type_ids=lowerCamelCase__ )[0] __lowerCamelCase = model(lowerCamelCase__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Tuple: '''simple docstring''' __lowerCamelCase = DebertaForMaskedLM(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' __lowerCamelCase = self.num_labels __lowerCamelCase = DebertaForSequenceClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(lowerCamelCase__ ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: '''simple docstring''' __lowerCamelCase = self.num_labels __lowerCamelCase = DebertaForTokenClassification(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Dict: '''simple docstring''' __lowerCamelCase = DebertaForQuestionAnswering(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowerCamelCase = model( lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , start_positions=lowerCamelCase__ , end_positions=lowerCamelCase__ , ) 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 lowercase_ ( self ) -> Union[str, Any]: '''simple docstring''' __lowerCamelCase = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) = config_and_inputs __lowerCamelCase = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __magic_name__ , __magic_name__ , unittest.TestCase ): """simple docstring""" snake_case_ = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) snake_case_ = ( { '''feature-extraction''': DebertaModel, '''fill-mask''': DebertaForMaskedLM, '''question-answering''': DebertaForQuestionAnswering, '''text-classification''': DebertaForSequenceClassification, '''token-classification''': DebertaForTokenClassification, '''zero-shot''': DebertaForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = True snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def lowercase_ ( self ) -> List[Any]: '''simple docstring''' __lowerCamelCase = DebertaModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=lowerCamelCase__ , hidden_size=37 ) def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def lowercase_ ( self ) -> List[str]: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*lowerCamelCase__ ) def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*lowerCamelCase__ ) def lowercase_ ( self ) -> Dict: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*lowerCamelCase__ ) def lowercase_ ( self ) -> Optional[Any]: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*lowerCamelCase__ ) def lowercase_ ( self ) -> str: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*lowerCamelCase__ ) @slow def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase = DebertaModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) @require_torch @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @unittest.skip(reason='Model not available yet' ) def lowercase_ ( self ) -> Union[str, Any]: '''simple docstring''' pass @slow def lowercase_ ( self ) -> Tuple: '''simple docstring''' __lowerCamelCase = DebertaModel.from_pretrained('microsoft/deberta-base' ) __lowerCamelCase = torch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) __lowerCamelCase = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ )[0] # compare the actual values for a slice. __lowerCamelCase = torch.tensor( [[[-0.59_86, -0.80_55, -0.84_62], [1.44_84, -0.93_48, -0.80_59], [0.31_23, 0.00_32, -1.41_31]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowerCamelCase__ , atol=1e-4 ) , f"""{output[:, 1:4, 1:4]}""" )
90
1
import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version __A = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''') def snake_case_(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 16_000 ) -> int: """simple docstring""" _snake_case = int(round(sample_rate * max_length ) ) if len(_UpperCamelCase ) <= sample_length: return wav _snake_case = randint(0 , len(_UpperCamelCase ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class lowercase_ : UpperCamelCase_ : Optional[str] = field(default=__lowercase , metadata={"help": "Name of a dataset from the datasets package"} ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "A file containing the training audio paths and labels."} ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "A file containing the validation audio paths and labels."} ) UpperCamelCase_ : str = field( default="train" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) UpperCamelCase_ : str = field( default="validation" , metadata={ "help": ( "The name of the training data set split to use (via the datasets library). Defaults to 'validation'" ) } , ) UpperCamelCase_ : str = field( default="audio" , metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"} , ) UpperCamelCase_ : str = field( default="label" , metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"} ) UpperCamelCase_ : Optional[int] = field( default=__lowercase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) UpperCamelCase_ : Optional[int] = field( default=__lowercase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) UpperCamelCase_ : float = field( default=2_0 , metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."} , ) @dataclass class lowercase_ : UpperCamelCase_ : str = field( default="facebook/wav2vec2-base" , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} , ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"} ) UpperCamelCase_ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) UpperCamelCase_ : Optional[str] = field( default=__lowercase , metadata={"help": "Name or path of preprocessor config."} ) UpperCamelCase_ : bool = field( default=__lowercase , metadata={"help": "Whether to freeze the feature encoder layers of the model."} ) UpperCamelCase_ : bool = field( default=__lowercase , metadata={"help": "Whether to generate an attention mask in the feature extractor."} ) UpperCamelCase_ : bool = field( default=__lowercase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) UpperCamelCase_ : Optional[bool] = field( default=__lowercase , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) UpperCamelCase_ : bool = field( default=__lowercase , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def UpperCamelCase_ ( self : Optional[int] ) -> List[Any]: if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''will be removed in a future version. Use `--freeze_feature_encoder`''' '''instead. Setting `freeze_feature_encoder==True`.''' , A__ , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''should not be used in combination with `--freeze_feature_encoder`.''' '''Only make use of `--freeze_feature_encoder`.''' ) def snake_case_() -> Optional[int]: """simple docstring""" _snake_case = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _snake_case, _snake_case, _snake_case = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _snake_case, _snake_case, _snake_case = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_audio_classification''' , _UpperCamelCase , _UpperCamelCase ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _snake_case = training_args.get_process_log_level() logger.setLevel(_UpperCamelCase ) transformers.utils.logging.set_verbosity(_UpperCamelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} """ + F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(F"""Training/evaluation parameters {training_args}""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. _snake_case = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _snake_case = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. """ '''Use --overwrite_output_dir to train from scratch.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset and prepare it for the audio classification task. _snake_case = DatasetDict() _snake_case = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) _snake_case = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """ '''Make sure to set `--audio_column_name` to the correct audio column - one of ''' F"""{', '.join(raw_datasets['train'].column_names )}.""" ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """ '''Make sure to set `--label_column_name` to the correct text column - one of ''' F"""{', '.join(raw_datasets['train'].column_names )}.""" ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy _snake_case = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. _snake_case = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) _snake_case = feature_extractor.model_input_names[0] def train_transforms(_UpperCamelCase ): _snake_case = [] for audio in batch[data_args.audio_column_name]: _snake_case = random_subsample( audio['''array'''] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(_UpperCamelCase ) _snake_case = feature_extractor(_UpperCamelCase , sampling_rate=feature_extractor.sampling_rate ) _snake_case = {model_input_name: inputs.get(_UpperCamelCase )} _snake_case = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(_UpperCamelCase ): _snake_case = [audio['''array'''] for audio in batch[data_args.audio_column_name]] _snake_case = feature_extractor(_UpperCamelCase , sampling_rate=feature_extractor.sampling_rate ) _snake_case = {model_input_name: inputs.get(_UpperCamelCase )} _snake_case = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. _snake_case = raw_datasets['''train'''].features[data_args.label_column_name].names _snake_case, _snake_case = {}, {} for i, label in enumerate(_UpperCamelCase ): _snake_case = str(_UpperCamelCase ) _snake_case = label # Load the accuracy metric from the datasets package _snake_case = evaluate.load('''accuracy''' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(_UpperCamelCase ): _snake_case = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=_UpperCamelCase , references=eval_pred.label_ids ) _snake_case = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(_UpperCamelCase ) , labelaid=_UpperCamelCase , idalabel=_UpperCamelCase , finetuning_task='''audio-classification''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) _snake_case = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=_UpperCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: _snake_case = ( raw_datasets['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(_UpperCamelCase , output_all_columns=_UpperCamelCase ) if training_args.do_eval: if data_args.max_eval_samples is not None: _snake_case = ( raw_datasets['''eval'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(_UpperCamelCase , output_all_columns=_UpperCamelCase ) # Initialize our trainer _snake_case = Trainer( model=_UpperCamelCase , args=_UpperCamelCase , train_dataset=raw_datasets['''train'''] if training_args.do_train else None , eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None , compute_metrics=_UpperCamelCase , tokenizer=_UpperCamelCase , ) # Training if training_args.do_train: _snake_case = None if training_args.resume_from_checkpoint is not None: _snake_case = training_args.resume_from_checkpoint elif last_checkpoint is not None: _snake_case = last_checkpoint _snake_case = trainer.train(resume_from_checkpoint=_UpperCamelCase ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _snake_case = trainer.evaluate() trainer.log_metrics('''eval''' , _UpperCamelCase ) trainer.save_metrics('''eval''' , _UpperCamelCase ) # Write model card and (optionally) push to hub _snake_case = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''audio-classification''', '''dataset''': data_args.dataset_name, '''tags''': ['''audio-classification'''], } if training_args.push_to_hub: trainer.push_to_hub(**_UpperCamelCase ) else: trainer.create_model_card(**_UpperCamelCase ) if __name__ == "__main__": main()
278
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging __A = logging.get_logger(__name__) __A = '''▁''' __A = { '''vocab_file''': '''vocab.json''', '''spm_file''': '''sentencepiece.bpe.model''', '''tokenizer_config_file''': '''tokenizer_config.json''', } __A = { '''vocab_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json''', }, '''spm_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_config_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json''', }, } __A = { '''facebook/m2m100_418M''': 10_24, } # fmt: off __A = { '''m2m100''': ['''af''', '''am''', '''ar''', '''ast''', '''az''', '''ba''', '''be''', '''bg''', '''bn''', '''br''', '''bs''', '''ca''', '''ceb''', '''cs''', '''cy''', '''da''', '''de''', '''el''', '''en''', '''es''', '''et''', '''fa''', '''ff''', '''fi''', '''fr''', '''fy''', '''ga''', '''gd''', '''gl''', '''gu''', '''ha''', '''he''', '''hi''', '''hr''', '''ht''', '''hu''', '''hy''', '''id''', '''ig''', '''ilo''', '''is''', '''it''', '''ja''', '''jv''', '''ka''', '''kk''', '''km''', '''kn''', '''ko''', '''lb''', '''lg''', '''ln''', '''lo''', '''lt''', '''lv''', '''mg''', '''mk''', '''ml''', '''mn''', '''mr''', '''ms''', '''my''', '''ne''', '''nl''', '''no''', '''ns''', '''oc''', '''or''', '''pa''', '''pl''', '''ps''', '''pt''', '''ro''', '''ru''', '''sd''', '''si''', '''sk''', '''sl''', '''so''', '''sq''', '''sr''', '''ss''', '''su''', '''sv''', '''sw''', '''ta''', '''th''', '''tl''', '''tn''', '''tr''', '''uk''', '''ur''', '''uz''', '''vi''', '''wo''', '''xh''', '''yi''', '''yo''', '''zh''', '''zu'''], '''wmt21''': ['''en''', '''ha''', '''is''', '''ja''', '''cs''', '''ru''', '''zh''', '''de'''] } class lowercase_ ( __lowercase ): UpperCamelCase_ : str = VOCAB_FILES_NAMES UpperCamelCase_ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Dict = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = ["input_ids", "attention_mask"] UpperCamelCase_ : List[int] = [] UpperCamelCase_ : List[int] = [] def __init__( self : str , A__ : str , A__ : Optional[Any] , A__ : Union[str, Any]=None , A__ : Dict=None , A__ : Any="<s>" , A__ : Union[str, Any]="</s>" , A__ : Tuple="</s>" , A__ : Dict="<pad>" , A__ : List[Any]="<unk>" , A__ : str="m2m100" , A__ : Optional[Dict[str, Any]] = None , A__ : List[Any]=8 , **A__ : Union[str, Any] , ) -> None: _snake_case = {} if sp_model_kwargs is None else sp_model_kwargs _snake_case = language_codes _snake_case = FAIRSEQ_LANGUAGE_CODES[language_codes] _snake_case = {lang_code: f"""__{lang_code}__""" for lang_code in fairseq_language_code} _snake_case = kwargs.get('''additional_special_tokens''' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(A__ ) for lang_code in fairseq_language_code if self.get_lang_token(A__ ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=A__ , tgt_lang=A__ , bos_token=A__ , eos_token=A__ , sep_token=A__ , unk_token=A__ , pad_token=A__ , language_codes=A__ , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=A__ , **A__ , ) _snake_case = vocab_file _snake_case = load_json(A__ ) _snake_case = {v: k for k, v in self.encoder.items()} _snake_case = spm_file _snake_case = load_spm(A__ , self.sp_model_kwargs ) _snake_case = len(self.encoder ) _snake_case = { self.get_lang_token(A__ ): self.encoder_size + i for i, lang_code in enumerate(A__ ) } _snake_case = {lang_code: self.encoder_size + i for i, lang_code in enumerate(A__ )} _snake_case = {v: k for k, v in self.lang_token_to_id.items()} _snake_case = src_lang if src_lang is not None else '''en''' _snake_case = tgt_lang _snake_case = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) _snake_case = num_madeup_words @property def UpperCamelCase_ ( self : int ) -> int: return len(self.encoder ) + len(self.lang_token_to_id ) @property def UpperCamelCase_ ( self : Dict ) -> str: return self._src_lang @src_lang.setter def UpperCamelCase_ ( self : List[str] , A__ : str ) -> None: _snake_case = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def UpperCamelCase_ ( self : Any , A__ : str ) -> List[str]: return self.sp_model.encode(A__ , out_type=A__ ) def UpperCamelCase_ ( self : Optional[int] , A__ : Dict ) -> str: if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(A__ , self.encoder[self.unk_token] ) def UpperCamelCase_ ( self : Union[str, Any] , A__ : int ) -> str: if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(A__ , self.unk_token ) def UpperCamelCase_ ( self : Optional[int] , A__ : Optional[int] ) -> List[Any]: _snake_case = [] _snake_case = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(A__ ) + token _snake_case = [] else: current_sub_tokens.append(A__ ) out_string += self.sp_model.decode(A__ ) return out_string.strip() def UpperCamelCase_ ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None , A__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A__ , token_ids_a=A__ , already_has_special_tokens=A__ ) _snake_case = [1] * len(self.prefix_tokens ) _snake_case = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(A__ )) + suffix_ones return prefix_ones + ([0] * len(A__ )) + ([0] * len(A__ )) + suffix_ones def UpperCamelCase_ ( self : Tuple , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def UpperCamelCase_ ( self : str ) -> Dict: _snake_case = {self.convert_ids_to_tokens(A__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : str ) -> Dict: _snake_case = self.__dict__.copy() _snake_case = None return state def __setstate__( self : Union[str, Any] , A__ : Dict ) -> None: _snake_case = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): _snake_case = {} _snake_case = load_spm(self.spm_file , self.sp_model_kwargs ) def UpperCamelCase_ ( self : Any , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: _snake_case = Path(A__ ) if not save_dir.is_dir(): raise OSError(f"""{save_directory} should be a directory""" ) _snake_case = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''vocab_file'''] ) _snake_case = save_dir / ( (filename_prefix + '''-''' if filename_prefix else '''''') + self.vocab_files_names['''spm_file'''] ) save_json(self.encoder , A__ ) if os.path.abspath(self.spm_file ) != os.path.abspath(A__ ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , A__ ) elif not os.path.isfile(self.spm_file ): with open(A__ , '''wb''' ) as fi: _snake_case = self.sp_model.serialized_model_proto() fi.write(A__ ) return (str(A__ ), str(A__ )) def UpperCamelCase_ ( self : Optional[int] , A__ : List[str] , A__ : str = "en" , A__ : Optional[List[str]] = None , A__ : str = "ro" , **A__ : List[Any] , ) -> BatchEncoding: _snake_case = src_lang _snake_case = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(A__ , A__ , **A__ ) def UpperCamelCase_ ( self : List[str] , A__ : int , A__ : Optional[str] , A__ : Optional[str] , **A__ : Union[str, Any] ) -> Tuple: if src_lang is None or tgt_lang is None: raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model''' ) _snake_case = src_lang _snake_case = self(A__ , add_special_tokens=A__ , **A__ ) _snake_case = self.get_lang_id(A__ ) _snake_case = tgt_lang_id return inputs def UpperCamelCase_ ( self : Dict ) -> Optional[Any]: self.set_src_lang_special_tokens(self.src_lang ) def UpperCamelCase_ ( self : Optional[Any] ) -> Dict: self.set_tgt_lang_special_tokens(self.tgt_lang ) def UpperCamelCase_ ( self : List[Any] , A__ : str ) -> None: _snake_case = self.get_lang_token(A__ ) _snake_case = self.lang_token_to_id[lang_token] _snake_case = [self.cur_lang_id] _snake_case = [self.eos_token_id] def UpperCamelCase_ ( self : List[str] , A__ : str ) -> None: _snake_case = self.get_lang_token(A__ ) _snake_case = self.lang_token_to_id[lang_token] _snake_case = [self.cur_lang_id] _snake_case = [self.eos_token_id] def UpperCamelCase_ ( self : Dict , A__ : str ) -> str: return self.lang_code_to_token[lang] def UpperCamelCase_ ( self : Tuple , A__ : str ) -> int: _snake_case = self.get_lang_token(A__ ) return self.lang_token_to_id[lang_token] def snake_case_(_UpperCamelCase , _UpperCamelCase ) -> sentencepiece.SentencePieceProcessor: """simple docstring""" _snake_case = sentencepiece.SentencePieceProcessor(**_UpperCamelCase ) spm.Load(str(_UpperCamelCase ) ) return spm def snake_case_(_UpperCamelCase ) -> Union[Dict, List]: """simple docstring""" with open(_UpperCamelCase , '''r''' ) as f: return json.load(_UpperCamelCase ) def snake_case_(_UpperCamelCase , _UpperCamelCase ) -> None: """simple docstring""" with open(_UpperCamelCase , '''w''' ) as f: json.dump(_UpperCamelCase , _UpperCamelCase , indent=2 )
278
1
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): a_ : List[str] = yaml.safe_load( """\ name: \"\" allow_empty: false allow_empty_text: true subsections: - name: \"Dataset Card for X\" # First-level markdown heading allow_empty: false allow_empty_text: true subsections: - name: \"Table of Contents\" allow_empty: false allow_empty_text: false subsections: null - name: \"Dataset Description\" allow_empty: false allow_empty_text: false subsections: - name: \"Dataset Summary\" allow_empty: false allow_empty_text: false subsections: null - name: \"Supported Tasks and Leaderboards\" allow_empty: true allow_empty_text: true subsections: null - name: Languages allow_empty: false allow_empty_text: true subsections: null """ ) a_ : int = { """name""": """root""", """text""": """""", """is_empty_text""": True, """subsections""": [ { """name""": """Dataset Card for My Dataset""", """text""": """""", """is_empty_text""": True, """subsections""": [ {"""name""": """Table of Contents""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": []}, { """name""": """Dataset Description""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": [ { """name""": """Dataset Summary""", """text""": """Some text here.""", """is_empty_text""": False, """subsections""": [], }, { """name""": """Supported Tasks and Leaderboards""", """text""": """""", """is_empty_text""": True, """subsections""": [], }, {"""name""": """Languages""", """text""": """Language Text""", """is_empty_text""": False, """subsections""": []}, ], }, ], } ], } a_ : List[str] = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ a_ : str = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. #### Extra Ignored Subsection ### Supported Tasks and Leaderboards ### Languages Language Text """ a_ : List[str] = { """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_ : str = """\ --- --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ a_ : Tuple = ( """The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.""" ) a_ : List[Any] = """\ # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ a_ : Dict = ( """The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.""" ) a_ : List[str] = """\ --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ a_ : str = """The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.""" a_ : Optional[Any] = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary ### Supported Tasks and Leaderboards ### Languages Language Text """ a_ : int = """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_ : Optional[Any] = """\ --- language: - zh - en --- # Dataset Card for My Dataset """ a_ : List[Any] = """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_ : Any = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Languages Language Text """ a_ : Optional[Any] = """The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.""" a_ : int = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages """ a_ : str = """The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.""" a_ : int = """\ --- language: - zh - en --- ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ a_ : List[Any] = """The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.""" a_ : int = """\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text # Dataset Card My Dataset """ a_ : Optional[Any] = """The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.""" a_ : Dict = """\ --- language: - zh - en --- # Dataset Card My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ a_ : List[Any] = """The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.""" a_ : Optional[Any] = """""" a_ : Tuple = """The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.""" a_ : Optional[Any] = """\ --- language: - zh - en --- # Dataset Card for My Dataset # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text """ a_ : Dict = """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_ ( __snake_case : Tuple , __snake_case : str ) -> str: """simple docstring""" assert ReadMe.from_string(__snake_case , __snake_case ).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_ ( __snake_case : List[str] , __snake_case : Union[str, Any] ) -> Optional[int]: """simple docstring""" with pytest.raises(__snake_case , match=re.escape(expected_error.format(path='''root''' ) ) ): lowerCamelCase_ =ReadMe.from_string(__snake_case , __snake_case ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def a_ ( __snake_case : Union[str, Any] , __snake_case : Dict ) -> List[str]: """simple docstring""" with pytest.raises(__snake_case , match=re.escape(expected_error.format(path='''root''' ) ) ): ReadMe.from_string(__snake_case , __snake_case ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def a_ ( __snake_case : Tuple ) -> int: """simple docstring""" ReadMe.from_string(__snake_case , __snake_case , suppress_parsing_errors=__snake_case ) @pytest.mark.parametrize( '''readme_md, expected_dict''' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def a_ ( __snake_case : Tuple , __snake_case : Tuple ) -> Union[str, Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase_ =Path(__snake_case ) / '''README.md''' with open(__snake_case , '''w+''' ) as readme_file: readme_file.write(__snake_case ) lowerCamelCase_ =ReadMe.from_readme(__snake_case , __snake_case ).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_ ( __snake_case : Union[str, Any] , __snake_case : int ) -> str: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase_ =Path(__snake_case ) / '''README.md''' with open(__snake_case , '''w+''' ) as readme_file: readme_file.write(__snake_case ) lowerCamelCase_ =expected_error.format(path=__snake_case ) with pytest.raises(__snake_case , match=re.escape(__snake_case ) ): lowerCamelCase_ =ReadMe.from_readme(__snake_case , __snake_case ) readme.validate() @pytest.mark.parametrize( '''readme_md, expected_error''' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def a_ ( __snake_case : List[Any] , __snake_case : Union[str, Any] ) -> List[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase_ =Path(__snake_case ) / '''README.md''' with open(__snake_case , '''w+''' ) as readme_file: readme_file.write(__snake_case ) lowerCamelCase_ =expected_error.format(path=__snake_case ) with pytest.raises(__snake_case , match=re.escape(__snake_case ) ): ReadMe.from_readme(__snake_case , __snake_case ) @pytest.mark.parametrize( '''readme_md,''' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def a_ ( __snake_case : List[Any] ) -> List[str]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase_ =Path(__snake_case ) / '''README.md''' with open(__snake_case , '''w+''' ) as readme_file: readme_file.write(__snake_case ) ReadMe.from_readme(__snake_case , __snake_case , suppress_parsing_errors=__snake_case )
75
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available SCREAMING_SNAKE_CASE__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ["""BartphoTokenizer"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
325
0
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers lowerCamelCase_ : Any = float("""nan""") class a__ : def __init__( self , UpperCAmelCase ) -> List[str]: __a = sys.stdout __a = open(UpperCAmelCase , 'a' ) def __getattr__( self , UpperCAmelCase ) -> List[Any]: return getattr(self.stdout , UpperCAmelCase ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase ) -> Tuple: self.stdout.write(UpperCAmelCase ) # strip tqdm codes self.file.write(re.sub(R'^.*\r' , '' , UpperCAmelCase , 0 , re.M ) ) def lowerCAmelCase( __lowerCamelCase=80 , __lowerCamelCase=False ): __a = [] # deal with critical env vars __a = ['CUDA_VISIBLE_DEVICES'] for key in env_keys: __a = os.environ.get(__lowerCamelCase , __lowerCamelCase ) if val is not None: cmd.append(f'''{key}={val}''' ) # python executable (not always needed if the script is executable) __a = sys.executable if full_python_path else sys.executable.split('/' )[-1] cmd.append(__lowerCamelCase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes __a = [] __a = '' while len(__lowerCamelCase ) > 0: current_line += f'''{cmd.pop(0 )} ''' if len(__lowerCamelCase ) == 0 or len(__lowerCamelCase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(__lowerCamelCase ) __a = '' return "\\\n".join(__lowerCamelCase ) def lowerCAmelCase( __lowerCamelCase , __lowerCamelCase ): # unwrap multi-line input __a = re.sub(r'[\\\n]+' , ' ' , args.base_cmd ) # remove --output_dir if any and set our own __a = re.sub('--output_dir\s+[^\s]+' , '' , args.base_cmd ) args.base_cmd += f''' --output_dir {output_dir}''' # ensure we have --overwrite_output_dir __a = re.sub('--overwrite_output_dir\s+' , '' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def lowerCAmelCase( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): # Enable to debug everything but the run itself, to do it fast and see the progress. # This is useful for debugging the output formatting quickly - we can remove it later once # everybody is happy with the output if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 1_00.2, 55.66_66, 2_22.22_22_22_22] )} , ) __a = subprocess.run(__lowerCamelCase , capture_output=__lowerCamelCase , text=__lowerCamelCase ) if verbose: print('STDOUT' , result.stdout ) print('STDERR' , result.stderr ) # save the streams __a = variation.replace(' ' , '-' ) with open(Path(__lowerCamelCase ) / f'''log.{prefix}.stdout.txt''' , 'w' ) as f: f.write(result.stdout ) with open(Path(__lowerCamelCase ) / f'''log.{prefix}.stderr.txt''' , 'w' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('failed' ) return {target_metric_key: nan} with io.open(f'''{output_dir}/all_results.json''' , 'r' , encoding='utf-8' ) as f: __a = json.load(__lowerCamelCase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def lowerCAmelCase( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ): __a = [] __a = [] __a = f'''{id}: {variation:<{longest_variation_len}}''' __a = f'''{preamble}: ''' __a = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(__lowerCamelCase ) , desc=__lowerCamelCase , leave=__lowerCamelCase ): __a = process_run_single( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) __a = single_run_metrics[target_metric_key] if not math.isnan(__lowerCamelCase ): metrics.append(__lowerCamelCase ) results.append(__lowerCamelCase ) outcome += "✓" else: outcome += "✘" __a = f'''\33[2K\r{outcome}''' if len(__lowerCamelCase ) > 0: __a = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} __a = round(mean_metrics[target_metric_key] , 2 ) __a = f'''{outcome} {mean_target}''' if len(__lowerCamelCase ) > 1: results_str += f''' {tuple(round(__lowerCamelCase , 2 ) for x in results )}''' print(__lowerCamelCase ) __a = variation return mean_metrics else: print(__lowerCamelCase ) return {variation_key: variation, target_metric_key: nan} def lowerCAmelCase( ): __a = torch.cuda.get_device_properties(torch.device('cuda' ) ) return f''' Datetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB ''' def lowerCAmelCase( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __a = pd.DataFrame(__lowerCamelCase ) __a = 'variation' __a = 'diff_%' __a = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan __a = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(__lowerCamelCase ): # as a fallback, use the minimal value as the sentinel __a = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(__lowerCamelCase ): __a = df.apply( lambda __lowerCamelCase : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='columns' , ) # re-order columns __a = [variation_key, target_metric_key, diff_key, *report_metric_keys] __a = df.reindex(__lowerCamelCase , axis='columns' ) # reorder cols # capitalize __a = df.rename(str.capitalize , axis='columns' ) # make the cols as narrow as possible __a = df.rename(lambda __lowerCamelCase : c.replace('_' , '<br>' ) , axis='columns' ) __a = df.rename(lambda __lowerCamelCase : c.replace('_' , '\n' ) , axis='columns' ) __a = ['', 'Copy between the cut-here-lines and paste as is to github or a forum'] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=__lowerCamelCase , floatfmt='.2f' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=__lowerCamelCase , floatfmt='.2f' )] print('\n\n'.join(__lowerCamelCase ) ) def lowerCAmelCase( ): __a = argparse.ArgumentParser() parser.add_argument( '--base-cmd' , default=__lowerCamelCase , type=__lowerCamelCase , required=__lowerCamelCase , help='Base cmd' , ) parser.add_argument( '--variations' , default=__lowerCamelCase , type=__lowerCamelCase , nargs='+' , required=__lowerCamelCase , help='Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'' , ) parser.add_argument( '--base-variation' , default=__lowerCamelCase , type=__lowerCamelCase , help='Baseline variation to compare to. if None the minimal target value will be used to compare against' , ) parser.add_argument( '--target-metric-key' , default=__lowerCamelCase , type=__lowerCamelCase , required=__lowerCamelCase , help='Target metric key in output_dir/all_results.json, e.g., train_samples_per_second' , ) parser.add_argument( '--report-metric-keys' , default='' , type=__lowerCamelCase , help='Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples' , ) parser.add_argument( '--repeat-times' , default=1 , type=__lowerCamelCase , help='How many times to re-run each variation - an average will be reported' , ) parser.add_argument( '--output_dir' , default='output_benchmark' , type=__lowerCamelCase , help='The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked' , ) parser.add_argument( '--verbose' , default=__lowerCamelCase , action='store_true' , help='Whether to show the outputs of each run or just the benchmark progress' , ) __a = parser.parse_args() __a = args.output_dir Path(__lowerCamelCase ).mkdir(exist_ok=__lowerCamelCase ) __a = get_base_command(__lowerCamelCase , __lowerCamelCase ) # split each dimension into its --foo variations __a = [list(map(str.strip , re.split(r'\|' , __lowerCamelCase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty __a = list(map(str.strip , map(' '.join , itertools.product(*__lowerCamelCase ) ) ) ) __a = max(len(__lowerCamelCase ) for x in variations ) # split wanted keys __a = args.report_metric_keys.split() # capture prints into a log file for convenience __a = f'''benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt''' print(f'''\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt''' ) print(f'''and this script\'s output is also piped into {report_fn}''' ) __a = Tee(__lowerCamelCase ) print(f'''\n*** Running {len(__lowerCamelCase )} benchmarks:''' ) print(f'''Base command: {" ".join(__lowerCamelCase )}''' ) __a = 'variation' __a = [] for id, variation in enumerate(tqdm(__lowerCamelCase , desc='Total completion: ' , leave=__lowerCamelCase ) ): __a = base_cmd + variation.split() results.append( process_run( id + 1 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , args.target_metric_key , __lowerCamelCase , args.repeat_times , __lowerCamelCase , args.verbose , ) ) process_results(__lowerCamelCase , args.target_metric_key , __lowerCamelCase , args.base_variation , __lowerCamelCase ) if __name__ == "__main__": main()
197
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class a__ ( __snake_case ): A__ : torch.FloatTensor A__ : torch.FloatTensor A__ : Optional[torch.FloatTensor] = None class a__ ( __snake_case , __snake_case ): A__ : Optional[Any] = 2 @register_to_config def __init__( self , UpperCAmelCase = 0.02 , UpperCAmelCase = 1_0_0 , UpperCAmelCase = 1.007 , UpperCAmelCase = 8_0 , UpperCAmelCase = 0.05 , UpperCAmelCase = 5_0 , ) -> Optional[Any]: # standard deviation of the initial noise distribution __a = sigma_max # setable values __a = None __a = None __a = None # sigma(t_i) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase = None ) -> torch.FloatTensor: return sample def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase = None ) -> int: __a = num_inference_steps __a = np.arange(0 , self.num_inference_steps )[::-1].copy() __a = torch.from_numpy(UpperCAmelCase ).to(UpperCAmelCase ) __a = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] __a = torch.tensor(UpperCAmelCase , dtype=torch.floataa , device=UpperCAmelCase ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = None ) -> Tuple[torch.FloatTensor, float]: if self.config.s_min <= sigma <= self.config.s_max: __a = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: __a = 0 # sample eps ~ N(0, S_noise^2 * I) __a = self.config.s_noise * randn_tensor(sample.shape , generator=UpperCAmelCase ).to(sample.device ) __a = sigma + gamma * sigma __a = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = True , ) -> Union[KarrasVeOutput, Tuple]: __a = sample_hat + sigma_hat * model_output __a = (sample_hat - pred_original_sample) / sigma_hat __a = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=UpperCAmelCase , derivative=UpperCAmelCase , pred_original_sample=UpperCAmelCase ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = True , ) -> Union[KarrasVeOutput, Tuple]: __a = sample_prev + sigma_prev * model_output __a = (sample_prev - pred_original_sample) / sigma_prev __a = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=UpperCAmelCase , derivative=UpperCAmelCase , pred_original_sample=UpperCAmelCase ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[Any]: raise NotImplementedError()
197
1
"""simple docstring""" from math import factorial _a = {str(d): factorial(d) for d in range(10)} def _A ( UpperCamelCase_ : int) -> int: '''simple docstring''' return sum(DIGIT_FACTORIAL[d] for d in str(UpperCamelCase_)) def _A ( ) -> int: '''simple docstring''' __lowercase = 7 * factorial(9) + 1 return sum(i for i in range(3, UpperCamelCase_) if sum_of_digit_factorial(UpperCamelCase_) == i) if __name__ == "__main__": print(F"{solution() = }")
17
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys a_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
330
0
import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() __UpperCamelCase : str = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : str , _UpperCAmelCase : Any ): lowerCAmelCase = WavaVecaForSequenceClassification.from_pretrained(_snake_case , config=_snake_case ) lowerCAmelCase = downstream_dict['''projector.weight'''] lowerCAmelCase = downstream_dict['''projector.bias'''] lowerCAmelCase = downstream_dict['''model.post_net.linear.weight'''] lowerCAmelCase = downstream_dict['''model.post_net.linear.bias'''] return model def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Optional[Any] , _UpperCAmelCase : str , _UpperCAmelCase : str ): lowerCAmelCase = WavaVecaForAudioFrameClassification.from_pretrained(_snake_case , config=_snake_case ) lowerCAmelCase = downstream_dict['''model.linear.weight'''] lowerCAmelCase = downstream_dict['''model.linear.bias'''] return model def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Dict , _UpperCAmelCase : Optional[int] ): lowerCAmelCase = WavaVecaForXVector.from_pretrained(_snake_case , config=_snake_case ) lowerCAmelCase = downstream_dict['''connector.weight'''] lowerCAmelCase = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): lowerCAmelCase = downstream_dict[ F'model.framelevel_feature_extractor.module.{i}.kernel.weight' ] lowerCAmelCase = downstream_dict[F'model.framelevel_feature_extractor.module.{i}.kernel.bias'] lowerCAmelCase = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] lowerCAmelCase = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] lowerCAmelCase = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] lowerCAmelCase = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] lowerCAmelCase = downstream_dict['''objective.W'''] return model @torch.no_grad() def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : int ): lowerCAmelCase = torch.load(_snake_case , map_location='cpu' ) lowerCAmelCase = checkpoint['''Downstream'''] lowerCAmelCase = WavaVecaConfig.from_pretrained(_snake_case ) lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained( _snake_case , return_attention_mask=_snake_case , do_normalize=_snake_case ) lowerCAmelCase = hf_config.architectures[0] if arch.endswith('ForSequenceClassification' ): lowerCAmelCase = convert_classification(_snake_case , _snake_case , _snake_case ) elif arch.endswith('ForAudioFrameClassification' ): lowerCAmelCase = convert_diarization(_snake_case , _snake_case , _snake_case ) elif arch.endswith('ForXVector' ): lowerCAmelCase = convert_xvector(_snake_case , _snake_case , _snake_case ) else: raise NotImplementedError(F'S3PRL weights conversion is not supported for {arch}' ) if hf_config.use_weighted_layer_sum: lowerCAmelCase = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(_snake_case ) hf_model.save_pretrained(_snake_case ) if __name__ == "__main__": __UpperCamelCase : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.''' ) parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''') parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''') __UpperCamelCase : List[str] = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
352
"""simple docstring""" import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () __UpperCamelCase : List[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). __UpperCamelCase : str = [0, 25, 50] __UpperCamelCase : int = [25, 50, 75] __UpperCamelCase : str = fuzz.membership.trimf(X, abca) __UpperCamelCase : Tuple = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. __UpperCamelCase : Dict = np.ones(75) __UpperCamelCase : str = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) __UpperCamelCase : Optional[Any] = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) __UpperCamelCase : Dict = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) __UpperCamelCase : Dict = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) __UpperCamelCase : List[str] = 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 : List[str] = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) __UpperCamelCase : Tuple = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] __UpperCamelCase : Union[str, Any] = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] __UpperCamelCase : Dict = 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()
309
0
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def A_ ( A__ , A__ , A__ , A__ , A__ ) -> float: a__ : Optional[Any] = np.array([[1, item, train_mtch[i]] for i, item in enumerate(A__ )] ) a__ : Dict = np.array(A__ ) a__ : List[Any] = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , A__ ) ) , x.transpose() ) , A__ ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def A_ ( A__ , A__ , A__ ) -> float: a__ : List[Any] = (1, 2, 1) a__ : Union[str, Any] = (1, 1, 0, 7) a__ : str = SARIMAX( A__ , exog=A__ , order=A__ , seasonal_order=A__ ) a__ : List[str] = model.fit(disp=A__ , maxiter=600 , method='nm' ) a__ : List[Any] = model_fit.predict(1 , len(A__ ) , exog=[test_match] ) return result[0] def A_ ( A__ , A__ , A__ ) -> float: a__ : Optional[Any] = SVR(kernel='rbf' , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(A__ , A__ ) a__ : Optional[int] = regressor.predict(A__ ) return y_pred[0] def A_ ( A__ ) -> float: train_user.sort() a__ : Union[str, Any] = np.percentile(A__ , 25 ) a__ : Dict = np.percentile(A__ , 75 ) a__ : Union[str, Any] = qa - qa a__ : str = qa - (iqr * 0.1) return low_lim def A_ ( A__ , A__ ) -> bool: a__ : Optional[Any] = 0 a__ : List[Any] = 0 for i in list_vote: if i > actual_result: a__ : Tuple = not_safe + 1 else: if abs(abs(A__ ) - abs(A__ ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) lowercase : Optional[int] = [[1_8_2_3_1, 0.0, 1], [2_2_6_2_1, 1.0, 2], [1_5_6_7_5, 0.0, 3], [2_3_5_8_3, 1.0, 4]] lowercase : List[str] = pd.DataFrame( data_input, columns=["""total_user""", """total_even""", """days"""] ) lowercase : str = Normalizer().fit_transform(data_input_df.values) # split data lowercase : List[str] = normalize_df[:, 2].tolist() lowercase : int = normalize_df[:, 0].tolist() lowercase : int = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) lowercase : Optional[int] = normalize_df[:, [1, 2]].tolist() lowercase : Optional[Any] = x[: len(x) - 1] lowercase : Any = x[len(x) - 1 :] # for linear regression & sarimax lowercase : Union[str, Any] = total_date[: len(total_date) - 1] lowercase : Optional[Any] = total_user[: len(total_user) - 1] lowercase : List[Any] = total_match[: len(total_match) - 1] lowercase : List[Any] = total_date[len(total_date) - 1 :] lowercase : Optional[Any] = total_user[len(total_user) - 1 :] lowercase : Union[str, Any] = total_match[len(total_match) - 1 :] # voting system with forecasting lowercase : int = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data lowercase : Dict = """""" if data_safety_checker(res_vote, tst_user) else """not """ print("""Today's data is {not_str}safe.""")
99
'''simple docstring''' import copy import re class A__ : A__ = 'hp' A__ = {} A__ = None @classmethod def A ( cls : Optional[Any] , _a : Optional[Any] , _a : Any ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prefix _SCREAMING_SNAKE_CASE =defaults cls.build_naming_info() @staticmethod def A ( _a : Optional[Any] , _a : List[Any] ) -> Any: '''simple docstring''' if len(_a ) == 0: return "" _SCREAMING_SNAKE_CASE =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(_a ) + 1 ): _SCREAMING_SNAKE_CASE =word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: _SCREAMING_SNAKE_CASE =prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(_a : str ): _SCREAMING_SNAKE_CASE ='' while integer != 0: _SCREAMING_SNAKE_CASE =chr(ord('A' ) + integer % 10 ) + s integer //= 10 return s _SCREAMING_SNAKE_CASE =0 while True: _SCREAMING_SNAKE_CASE =word + '#' + int_to_alphabetic(_a ) if sword in info["reverse_short_word"]: continue else: _SCREAMING_SNAKE_CASE =sword break _SCREAMING_SNAKE_CASE =short_word _SCREAMING_SNAKE_CASE =word return short_word @staticmethod def A ( _a : Optional[Any] , _a : int ) -> Optional[int]: '''simple docstring''' _SCREAMING_SNAKE_CASE =param_name.split('_' ) _SCREAMING_SNAKE_CASE =[TrialShortNamer.shortname_for_word(_a , _a ) 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 _SCREAMING_SNAKE_CASE =['', '_'] for separator in separators: _SCREAMING_SNAKE_CASE =separator.join(_a ) if shortname not in info["reverse_short_param"]: _SCREAMING_SNAKE_CASE =shortname _SCREAMING_SNAKE_CASE =param_name return shortname return param_name @staticmethod def A ( _a : Dict , _a : int ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =TrialShortNamer.shortname_for_key(_a , _a ) _SCREAMING_SNAKE_CASE =short_name _SCREAMING_SNAKE_CASE =param_name @classmethod def A ( cls : Optional[int] ) -> Tuple: '''simple docstring''' if cls.NAMING_INFO is not None: return _SCREAMING_SNAKE_CASE ={ 'short_word': {}, 'reverse_short_word': {}, 'short_param': {}, 'reverse_short_param': {}, } _SCREAMING_SNAKE_CASE =list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(_a , _a ) _SCREAMING_SNAKE_CASE =info @classmethod def A ( cls : List[Any] , _a : int ) -> int: '''simple docstring''' cls.build_naming_info() assert cls.PREFIX is not None _SCREAMING_SNAKE_CASE =[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 _SCREAMING_SNAKE_CASE =cls.NAMING_INFO['short_param'][k] if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =1 if v else 0 _SCREAMING_SNAKE_CASE ='' if isinstance(_a , (int, float) ) else '-' _SCREAMING_SNAKE_CASE =f"{key}{sep}{v}" name.append(_a ) return "_".join(_a ) @classmethod def A ( cls : Optional[Any] , _a : List[Any] ) -> Dict: '''simple docstring''' _SCREAMING_SNAKE_CASE =repr[len(cls.PREFIX ) + 1 :] if repr == "": _SCREAMING_SNAKE_CASE =[] else: _SCREAMING_SNAKE_CASE =repr.split('_' ) _SCREAMING_SNAKE_CASE ={} for value in values: if "-" in value: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =value.split('-' ) else: _SCREAMING_SNAKE_CASE =re.sub('[0-9.]' , '' , _a ) _SCREAMING_SNAKE_CASE =float(re.sub('[^0-9.]' , '' , _a ) ) _SCREAMING_SNAKE_CASE =cls.NAMING_INFO['reverse_short_param'][p_k] _SCREAMING_SNAKE_CASE =p_v for k in cls.DEFAULTS: if k not in parameters: _SCREAMING_SNAKE_CASE =cls.DEFAULTS[k] return parameters
47
0
'''simple docstring''' from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *
369
'''simple docstring''' from __future__ import annotations UpperCAmelCase = [] def _snake_case ( _SCREAMING_SNAKE_CASE : list[list[int]] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ) -> bool: """simple docstring""" for i in range(len(_SCREAMING_SNAKE_CASE ) ): if board[row][i] == 1: return False for i in range(len(_SCREAMING_SNAKE_CASE ) ): if board[i][column] == 1: return False for i, j in zip(range(_SCREAMING_SNAKE_CASE , -1 , -1 ) , range(_SCREAMING_SNAKE_CASE , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(_SCREAMING_SNAKE_CASE , -1 , -1 ) , range(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ) ): if board[i][j] == 1: return False return True def _snake_case ( _SCREAMING_SNAKE_CASE : list[list[int]] , _SCREAMING_SNAKE_CASE : int ) -> bool: """simple docstring""" if row >= len(_SCREAMING_SNAKE_CASE ): solution.append(_SCREAMING_SNAKE_CASE ) printboard(_SCREAMING_SNAKE_CASE ) print() return True for i in range(len(_SCREAMING_SNAKE_CASE ) ): if is_safe(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCAmelCase = 1 solve(_SCREAMING_SNAKE_CASE , row + 1 ) lowerCAmelCase = 0 return False def _snake_case ( _SCREAMING_SNAKE_CASE : list[list[int]] ) -> None: """simple docstring""" for i in range(len(_SCREAMING_SNAKE_CASE ) ): for j in range(len(_SCREAMING_SNAKE_CASE ) ): if board[i][j] == 1: print("""Q""" , end=""" """ ) else: print(""".""" , end=""" """ ) print() # n=int(input("The no. of queens")) UpperCAmelCase = 8 UpperCAmelCase = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
187
0
"""simple docstring""" from __future__ import annotations _a = [] def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> bool: """simple docstring""" for i in range(len(__snake_case ) ): if board[row][i] == 1: return False for i in range(len(__snake_case ) ): if board[i][column] == 1: return False for i, j in zip(range(__snake_case, -1, -1 ), range(__snake_case, -1, -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(__snake_case, -1, -1 ), range(__snake_case, len(__snake_case ) ) ): if board[i][j] == 1: return False return True def lowerCamelCase__ ( __snake_case, __snake_case ) -> bool: """simple docstring""" if row >= len(__snake_case ): solution.append(__snake_case ) printboard(__snake_case ) print() return True for i in range(len(__snake_case ) ): if is_safe(__snake_case, __snake_case, __snake_case ): _UpperCamelCase = 1 solve(__snake_case, row + 1 ) _UpperCamelCase = 0 return False def lowerCamelCase__ ( __snake_case ) -> None: """simple docstring""" for i in range(len(__snake_case ) ): for j in range(len(__snake_case ) ): if board[i][j] == 1: print('''Q''', end=''' ''' ) else: print('''.''', end=''' ''' ) print() # n=int(input("The no. of queens")) _a = 8 _a = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print("""The total no. of solutions are :""", len(solution))
194
"""simple docstring""" def lowerCamelCase__ ( __snake_case ) -> bool: """simple docstring""" return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') ) def lowerCamelCase__ ( __snake_case ) -> bool: """simple docstring""" _UpperCamelCase = credit_card_number _UpperCamelCase = 0 _UpperCamelCase = len(__snake_case ) - 2 for i in range(__snake_case, -1, -2 ): # double the value of every second digit _UpperCamelCase = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 _UpperCamelCase = cc_number[:i] + str(__snake_case ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__snake_case ) - 1, -1, -2 ): total += int(cc_number[i] ) return total % 10 == 0 def lowerCamelCase__ ( __snake_case ) -> bool: """simple docstring""" _UpperCamelCase = F'''{credit_card_number} is an invalid credit card number because''' if not credit_card_number.isdigit(): print(F'''{error_message} it has nonnumerical characters.''' ) return False if not 13 <= len(__snake_case ) <= 16: print(F'''{error_message} of its length.''' ) return False if not validate_initial_digits(__snake_case ): print(F'''{error_message} of its first two digits.''' ) return False if not luhn_validation(__snake_case ): print(F'''{error_message} it fails the Luhn check.''' ) return False print(F'''{credit_card_number} is a valid credit card number.''' ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number("""4111111111111111""") validate_credit_card_number("""32323""")
194
1
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): lowercase : Tuple = 'pt' elif is_tf_available(): lowercase : Optional[int] = 'tf' else: lowercase : Tuple = 'jax' class lowerCamelCase__ ( __lowercase , unittest.TestCase): '''simple docstring''' _A = ByTaTokenizer _A = False def _lowerCamelCase ( self :Dict ) -> Optional[int]: super().setUp() __UpperCamelCase : Optional[int] = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _lowerCamelCase ( self :Dict ) -> List[Any]: return ByTaTokenizer.from_pretrained("google/byt5-small" ) def _lowerCamelCase ( self :Tuple , **a :List[str] ) -> ByTaTokenizer: return self.tokenizer_class.from_pretrained(self.tmpdirname , **a ) def _lowerCamelCase ( self :Union[str, Any] , a :str , a :Any=False , a :Optional[Any]=2_0 , a :int=5 ) -> Tuple[str, list]: # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for ByT5 because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. __UpperCamelCase : str = [] for i in range(len(a ) ): try: __UpperCamelCase : Optional[int] = tokenizer.decode([i] , clean_up_tokenization_spaces=a ) except UnicodeDecodeError: pass toks.append((i, tok) ) __UpperCamelCase : Tuple = list(filter(lambda a : re.match(r"^[ a-zA-Z]+$" , t[1] ) , a ) ) __UpperCamelCase : Optional[int] = list(filter(lambda a : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=a ) , a ) ) if max_length is not None and len(a ) > max_length: __UpperCamelCase : Union[str, Any] = toks[:max_length] if min_length is not None and len(a ) < min_length and len(a ) > 0: while len(a ) < min_length: __UpperCamelCase : Optional[Any] = toks + toks # toks_str = [t[1] for t in toks] __UpperCamelCase : Dict = [t[0] for t in toks] # Ensure consistency __UpperCamelCase : Optional[int] = tokenizer.decode(a , clean_up_tokenization_spaces=a ) if " " not in output_txt and len(a ) > 1: __UpperCamelCase : Optional[Any] = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=a ) + " " + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=a ) ) if with_prefix_space: __UpperCamelCase : Optional[int] = " " + output_txt __UpperCamelCase : List[Any] = tokenizer.encode(a , add_special_tokens=a ) return output_txt, output_ids def _lowerCamelCase ( self :Optional[Any] ) -> Union[str, Any]: __UpperCamelCase : Optional[Any] = self.ta_base_tokenizer __UpperCamelCase : Union[str, Any] = tokenizer(["hi</s>", "I went to the gym</s>", "</s>"] ) __UpperCamelCase : str = tokenizer(["hi", "I went to the gym", ""] ) self.assertListEqual(batch_with_eos_added["input_ids"] , batch_without_eos_added["input_ids"] ) def _lowerCamelCase ( self :Dict ) -> Union[str, Any]: __UpperCamelCase : Any = self.ta_base_tokenizer __UpperCamelCase : Optional[Any] = "Unicode €." __UpperCamelCase : Union[str, Any] = tokenizer(a ) __UpperCamelCase : Any = [8_8, 1_1_3, 1_0_8, 1_0_2, 1_1_4, 1_0_3, 1_0_4, 3_5, 2_2_9, 1_3_3, 1_7_5, 4_9, 1] self.assertEqual(encoded["input_ids"] , a ) # decoding __UpperCamelCase : Union[str, Any] = tokenizer.decode(a ) self.assertEqual(a , "Unicode €.</s>" ) __UpperCamelCase : Tuple = tokenizer("e è é ê ë" ) __UpperCamelCase : Union[str, Any] = [1_0_4, 3_5, 1_9_8, 1_7_1, 3_5, 1_9_8, 1_7_2, 3_5, 1_9_8, 1_7_3, 3_5, 1_9_8, 1_7_4, 1] self.assertEqual(encoded["input_ids"] , a ) # decoding __UpperCamelCase : List[str] = tokenizer.decode(a ) self.assertEqual(a , "e è é ê ë</s>" ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë" ) ) , "e è é ê ë</s>" ) def _lowerCamelCase ( self :Tuple ) -> Optional[Any]: __UpperCamelCase : str = self.ta_base_tokenizer __UpperCamelCase : List[str] = ["A long paragraph for summarization.", "Another paragraph for summarization."] # fmt: off __UpperCamelCase : Dict = [6_8, 3_5, 1_1_1, 1_1_4, 1_1_3, 1_0_6, 3_5, 1_1_5, 1_0_0, 1_1_7, 1_0_0, 1_0_6, 1_1_7, 1_0_0, 1_1_5, 1_0_7, 3_5, 1_0_5, 1_1_4, 1_1_7, 3_5, 1_1_8, 1_2_0, 1_1_2, 1_1_2, 1_0_0, 1_1_7, 1_0_8, 1_2_5, 1_0_0, 1_1_9, 1_0_8, 1_1_4, 1_1_3, 4_9, 1, 0] # fmt: on __UpperCamelCase : Union[str, Any] = tokenizer(a , padding=a , return_tensors=a ) self.assertIsInstance(a , a ) if FRAMEWORK != "jax": __UpperCamelCase : Optional[int] = list(batch.input_ids.numpy()[0] ) else: __UpperCamelCase : List[str] = list(batch.input_ids.tolist()[0] ) self.assertListEqual(a , a ) self.assertEqual((2, 3_7) , batch.input_ids.shape ) self.assertEqual((2, 3_7) , batch.attention_mask.shape ) def _lowerCamelCase ( self :Any ) -> List[str]: __UpperCamelCase : int = self.ta_base_tokenizer __UpperCamelCase : Any = ["A long paragraph for summarization.", "Another paragraph for summarization."] __UpperCamelCase : List[str] = tokenizer(a , padding=a , return_tensors=a ) # check if input_ids are returned and no decoder_input_ids self.assertIn("input_ids" , a ) self.assertIn("attention_mask" , a ) self.assertNotIn("decoder_input_ids" , a ) self.assertNotIn("decoder_attention_mask" , a ) def _lowerCamelCase ( self :Any ) -> str: __UpperCamelCase : int = self.ta_base_tokenizer __UpperCamelCase : Union[str, Any] = [ "Summary of the text.", "Another summary.", ] __UpperCamelCase : List[Any] = tokenizer( text_target=a , max_length=3_2 , padding="max_length" , truncation=a , return_tensors=a ) self.assertEqual(3_2 , targets["input_ids"].shape[1] ) def _lowerCamelCase ( self :Optional[Any] ) -> Optional[Any]: __UpperCamelCase : Optional[int] = self.ta_base_tokenizer __UpperCamelCase : List[Any] = ["A long paragraph for summarization. </s>"] __UpperCamelCase : Optional[int] = ["Summary of the text. </s>"] # fmt: off __UpperCamelCase : List[str] = [6_8, 3_5, 1_1_1, 1_1_4, 1_1_3, 1_0_6, 3_5, 1_1_5, 1_0_0, 1_1_7, 1_0_0, 1_0_6, 1_1_7, 1_0_0, 1_1_5, 1_0_7, 3_5, 1_0_5, 1_1_4, 1_1_7, 3_5, 1_1_8, 1_2_0, 1_1_2, 1_1_2, 1_0_0, 1_1_7, 1_0_8, 1_2_5, 1_0_0, 1_1_9, 1_0_8, 1_1_4, 1_1_3, 4_9, 3_5, 1] __UpperCamelCase : Dict = [8_6, 1_2_0, 1_1_2, 1_1_2, 1_0_0, 1_1_7, 1_2_4, 3_5, 1_1_4, 1_0_5, 3_5, 1_1_9, 1_0_7, 1_0_4, 3_5, 1_1_9, 1_0_4, 1_2_3, 1_1_9, 4_9, 3_5, 1] # fmt: on __UpperCamelCase : Tuple = tokenizer(a , text_target=a ) self.assertEqual(a , batch["input_ids"][0] ) self.assertEqual(a , batch["labels"][0] ) def _lowerCamelCase ( self :Dict ) -> Any: # safety check on max_len default value so we are sure the test works __UpperCamelCase : Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 4_2 ) # Now let's start the test __UpperCamelCase : Any = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc __UpperCamelCase : Optional[Any] = tempfile.mkdtemp() __UpperCamelCase : List[Any] = " He is very happy, UNwant\u00E9d,running" __UpperCamelCase : Tuple = tokenizer.encode(a , add_special_tokens=a ) tokenizer.save_pretrained(a ) __UpperCamelCase : Union[str, Any] = tokenizer.__class__.from_pretrained(a ) __UpperCamelCase : Dict = after_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) shutil.rmtree(a ) __UpperCamelCase : Tuple = self.get_tokenizers(model_max_length=4_2 ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc __UpperCamelCase : Optional[int] = tempfile.mkdtemp() __UpperCamelCase : Any = " He is very happy, UNwant\u00E9d,running" tokenizer.add_tokens(["bim", "bambam"] ) __UpperCamelCase : List[Any] = tokenizer.additional_special_tokens additional_special_tokens.append("new_additional_special_token" ) tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} ) __UpperCamelCase : Dict = tokenizer.encode(a , add_special_tokens=a ) tokenizer.save_pretrained(a ) __UpperCamelCase : List[Any] = tokenizer.__class__.from_pretrained(a ) __UpperCamelCase : List[Any] = after_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) self.assertIn("new_additional_special_token" , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 4_2 ) __UpperCamelCase : str = tokenizer.__class__.from_pretrained(a , model_max_length=4_3 ) self.assertEqual(tokenizer.model_max_length , 4_3 ) shutil.rmtree(a ) def _lowerCamelCase ( self :Union[str, Any] ) -> List[str]: __UpperCamelCase : List[Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(a ) with open(os.path.join(a , "special_tokens_map.json" ) , encoding="utf-8" ) as json_file: __UpperCamelCase : Optional[int] = json.load(a ) with open(os.path.join(a , "tokenizer_config.json" ) , encoding="utf-8" ) as json_file: __UpperCamelCase : Union[str, Any] = json.load(a ) __UpperCamelCase : Tuple = [f'<extra_id_{i}>' for i in range(1_2_5 )] __UpperCamelCase : str = added_tokens_extra_ids + [ "an_additional_special_token" ] __UpperCamelCase : Dict = added_tokens_extra_ids + [ "an_additional_special_token" ] with open(os.path.join(a , "special_tokens_map.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(a , a ) with open(os.path.join(a , "tokenizer_config.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(a , a ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files __UpperCamelCase : Union[str, Any] = tokenizer_class.from_pretrained( a , ) self.assertIn( "an_additional_special_token" , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ["an_additional_special_token"] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained __UpperCamelCase : List[str] = added_tokens_extra_ids + [AddedToken("a_new_additional_special_token" , lstrip=a )] __UpperCamelCase : Union[str, Any] = tokenizer_class.from_pretrained( a , additional_special_tokens=a , ) self.assertIn("a_new_additional_special_token" , tokenizer.additional_special_tokens ) self.assertEqual( ["a_new_additional_special_token"] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"] ) ) , ) def _lowerCamelCase ( self :Dict ) -> Tuple: __UpperCamelCase : Dict = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(a ) __UpperCamelCase : Optional[Any] = tokenizer_class.from_pretrained(a ) self.assertTrue(tokenizer.decode([2_5_5] ) == "" ) def _lowerCamelCase ( self :Optional[int] ) -> Tuple: pass def _lowerCamelCase ( self :List[str] ) -> List[Any]: pass def _lowerCamelCase ( self :Any ) -> List[Any]: pass def _lowerCamelCase ( self :Union[str, Any] ) -> Tuple: pass def _lowerCamelCase ( self :Optional[int] ) -> int: # The default common tokenizer tests uses invalid tokens for ByT5 that can only accept one-character strings # and special added tokens as tokens __UpperCamelCase : Optional[Any] = self.get_tokenizers(fast=a , do_lower_case=a ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase : Any = ["t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "x", "t", "</s>"] __UpperCamelCase : str = tokenizer.convert_tokens_to_string(a ) self.assertIsInstance(a , a ) def _lowerCamelCase ( self :Tuple ) -> Optional[Any]: __UpperCamelCase : Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase : Optional[int] = [ "bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token", ] __UpperCamelCase : int = 0 __UpperCamelCase : Union[str, Any] = tokenizer.convert_ids_to_tokens( a , skip_special_tokens=a ) for attr in attributes_list: setattr(a , attr + "_id" , a ) self.assertEqual(getattr(a , a ) , a ) self.assertEqual(getattr(a , attr + "_id" ) , a ) setattr(a , attr + "_id" , a ) self.assertEqual(getattr(a , a ) , a ) self.assertEqual(getattr(a , attr + "_id" ) , a ) setattr(a , "additional_special_tokens_ids" , [] ) self.assertListEqual(getattr(a , "additional_special_tokens" ) , [] ) self.assertListEqual(getattr(a , "additional_special_tokens_ids" ) , [] ) setattr(a , "additional_special_tokens_ids" , [token_id_to_test_setters] ) self.assertListEqual(getattr(a , "additional_special_tokens" ) , [token_to_test_setters] ) self.assertListEqual(getattr(a , "additional_special_tokens_ids" ) , [token_id_to_test_setters] )
151
import qiskit def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int = 2) -> qiskit.result.counts.Counts: '''simple docstring''' __UpperCamelCase : List[str] = qubits # Using Aer's simulator __UpperCamelCase : int = qiskit.Aer.get_backend("aer_simulator") # Creating a Quantum Circuit acting on the q register __UpperCamelCase : List[str] = qiskit.QuantumCircuit(_lowerCamelCase , _lowerCamelCase) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0) for i in range(1 , _lowerCamelCase): # Adding CX (CNOT) gate circuit.cx(i - 1 , _lowerCamelCase) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(_lowerCamelCase)) , list(range(_lowerCamelCase))) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator __UpperCamelCase : Any = qiskit.execute(_lowerCamelCase , _lowerCamelCase , shots=1_000) return job.result().get_counts(_lowerCamelCase) if __name__ == "__main__": print(f"Total count for various states are: {quantum_entanglement(3)}")
151
1
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> int: if not numbers: return 0 if not isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ) or not all( isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) snake_case_ = snake_case_ = snake_case_ = numbers[0] for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): # update the maximum and minimum subarray products snake_case_ = numbers[i] if number < 0: snake_case_ , snake_case_ = min_till_now, max_till_now snake_case_ = max(_SCREAMING_SNAKE_CASE , max_till_now * number ) snake_case_ = min(_SCREAMING_SNAKE_CASE , min_till_now * number ) # update the maximum product found till now snake_case_ = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return max_prod
347
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } __SCREAMING_SNAKE_CASE : List[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = {} with open(_SCREAMING_SNAKE_CASE , """r""" ) as file: for line_number, line in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = line.strip() if line: snake_case_ = line.split() snake_case_ = line_number snake_case_ = words[0] snake_case_ = value return result def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: for attribute in key.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape elif weight_type is not None and weight_type == "param": snake_case_ = hf_pointer for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = shape_pointer.shape # let's reduce dimension snake_case_ = value[0] else: snake_case_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": snake_case_ = value elif weight_type == "weight_g": snake_case_ = value elif weight_type == "weight_v": snake_case_ = value elif weight_type == "bias": snake_case_ = value elif weight_type == "param": for attribute in hf_param_name.split(""".""" ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = value else: snake_case_ = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(_SCREAMING_SNAKE_CASE ): snake_case_ = PARAM_MAPPING[full_name.split(""".""" )[-1]] snake_case_ = """param""" if weight_type is not None and weight_type != "param": snake_case_ = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": snake_case_ = """.""".join([key, hf_param_name] ) else: snake_case_ = key snake_case_ = value if """lm_head""" in full_key else value[0] __SCREAMING_SNAKE_CASE : int = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> List[str]: snake_case_ = False for key, mapped_key in MAPPING.items(): snake_case_ = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: snake_case_ = True if "*" in mapped_key: snake_case_ = name.split(_SCREAMING_SNAKE_CASE )[0].split(""".""" )[-2] snake_case_ = mapped_key.replace("""*""" , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: snake_case_ = """weight_g""" elif "weight_v" in name: snake_case_ = """weight_v""" elif "bias" in name: snake_case_ = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj snake_case_ = """weight""" else: snake_case_ = None if hf_dict is not None: rename_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return is_used return is_used def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = [] snake_case_ = fairseq_model.state_dict() snake_case_ = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): snake_case_ = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == """group""" , ) snake_case_ = True else: snake_case_ = load_wavaveca_layer(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(f"""Unused weights: {unused_weights}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = full_name.split("""conv_layers.""" )[-1] snake_case_ = name.split(""".""" ) snake_case_ = int(items[0] ) snake_case_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) snake_case_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False ) -> int: if config_path is not None: snake_case_ = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaConfig() if is_seq_class: snake_case_ = read_txt_into_dict(_SCREAMING_SNAKE_CASE ) snake_case_ = idalabel snake_case_ = WavaVecaForSequenceClassification(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) elif is_finetuned: if dict_path: snake_case_ = Dictionary.load(_SCREAMING_SNAKE_CASE ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq snake_case_ = target_dict.pad_index snake_case_ = target_dict.bos_index snake_case_ = target_dict.eos_index snake_case_ = len(target_dict.symbols ) snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , """vocab.json""" ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) ) return os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE ) snake_case_ = target_dict.indices # fairseq has the <pad> and <s> switched snake_case_ = 0 snake_case_ = 1 with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaCTCTokenizer( _SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=_SCREAMING_SNAKE_CASE , ) snake_case_ = True if config.feat_extract_norm == """layer""" else False snake_case_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , ) snake_case_ = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaForCTC(_SCREAMING_SNAKE_CASE ) else: snake_case_ = WavaVecaForPreTraining(_SCREAMING_SNAKE_CASE ) if is_finetuned or is_seq_class: snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: snake_case_ = argparse.Namespace(task="""audio_pretraining""" ) snake_case_ = fairseq.tasks.setup_task(_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ , snake_case_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=_SCREAMING_SNAKE_CASE ) snake_case_ = model[0].eval() recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , not is_finetuned ) hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) __SCREAMING_SNAKE_CASE : Any = parser.parse_args() __SCREAMING_SNAKE_CASE : List[Any] = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
347
1
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_ : """simple docstring""" def __init__( self , lowerCAmelCase , lowerCAmelCase=13 , lowerCAmelCase=7 , lowerCAmelCase=True , lowerCAmelCase=True , lowerCAmelCase=False , lowerCAmelCase=True , lowerCAmelCase=99 , lowerCAmelCase=32 , lowerCAmelCase=5 , lowerCAmelCase=4 , lowerCAmelCase=37 , lowerCAmelCase="gelu" , lowerCAmelCase=0.1 , lowerCAmelCase=0.1 , lowerCAmelCase=5_12 , lowerCAmelCase=16 , lowerCAmelCase=2 , lowerCAmelCase=0.02 , lowerCAmelCase=3 , lowerCAmelCase=4 , lowerCAmelCase=None , ): """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 def snake_case ( self ): """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_token_type_ids: snake_case = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case = None snake_case = None snake_case = None if self.use_labels: snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case = ids_tensor([self.batch_size] , self.num_choices ) snake_case = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case ( self ): """simple docstring""" return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCAmelCase , initializer_range=self.initializer_range , ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" snake_case = BioGptModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() snake_case = model(lowerCAmelCase , attention_mask=lowerCAmelCase ) snake_case = model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): """simple docstring""" snake_case = BioGptForCausalLM(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() snake_case = model(lowerCAmelCase , attention_mask=lowerCAmelCase , token_type_ids=lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , *lowerCAmelCase ): """simple docstring""" snake_case = BioGptModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() # create attention mask snake_case = torch.ones(input_ids.shape , dtype=torch.long , device=lowerCAmelCase ) snake_case = self.seq_length // 2 snake_case = 0 # first forward pass snake_case ,snake_case = model(lowerCAmelCase , attention_mask=lowerCAmelCase ).to_tuple() # create hypothetical next token and extent to next_input_ids snake_case = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids snake_case = ids_tensor((1,) , lowerCAmelCase ).item() + 1 snake_case = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) snake_case = random_other_next_tokens # append to next input_ids and attn_mask snake_case = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=lowerCAmelCase )] , dim=1 , ) # get two different outputs snake_case = model(lowerCAmelCase , attention_mask=lowerCAmelCase )['last_hidden_state'] snake_case = model(lowerCAmelCase , past_key_values=lowerCAmelCase , attention_mask=lowerCAmelCase )['last_hidden_state'] # select random slice snake_case = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case = output_from_no_past[:, -1, random_slice_idx].detach() snake_case = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCAmelCase , lowerCAmelCase , atol=1E-3 ) ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , *lowerCAmelCase ): """simple docstring""" snake_case = BioGptModel(config=lowerCAmelCase ).to(lowerCAmelCase ).eval() snake_case = torch.ones(input_ids.shape , dtype=torch.long , device=lowerCAmelCase ) # first forward pass snake_case = model(lowerCAmelCase , attention_mask=lowerCAmelCase , use_cache=lowerCAmelCase ) snake_case ,snake_case = outputs.to_tuple() # 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) , 2 ) # append to next input_ids and snake_case = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) snake_case = model(lowerCAmelCase , attention_mask=lowerCAmelCase )['last_hidden_state'] snake_case = model(lowerCAmelCase , attention_mask=lowerCAmelCase , past_key_values=lowerCAmelCase )[ 'last_hidden_state' ] # 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(lowerCAmelCase , lowerCAmelCase , atol=1E-3 ) ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , *lowerCAmelCase , lowerCAmelCase=False ): """simple docstring""" snake_case = BioGptForCausalLM(lowerCAmelCase ) model.to(lowerCAmelCase ) if gradient_checkpointing: model.gradient_checkpointing_enable() snake_case = model(lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def snake_case ( self , lowerCAmelCase , *lowerCAmelCase ): """simple docstring""" snake_case = BioGptModel(lowerCAmelCase ) snake_case = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.0_01 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , *lowerCAmelCase ): """simple docstring""" snake_case = self.num_labels snake_case = BioGptForTokenClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() snake_case = model(lowerCAmelCase , attention_mask=lowerCAmelCase , token_type_ids=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def snake_case ( self ): """simple docstring""" snake_case = self.prepare_config_and_inputs() ( ( snake_case ) ,( snake_case ) ,( snake_case ) ,( 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 lowerCAmelCase_ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): """simple docstring""" _lowerCAmelCase : List[Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) _lowerCAmelCase : str = (BioGptForCausalLM,) if is_torch_available() else () _lowerCAmelCase : str = ( { """feature-extraction""": BioGptModel, """text-classification""": BioGptForSequenceClassification, """text-generation""": BioGptForCausalLM, """token-classification""": BioGptForTokenClassification, """zero-shot""": BioGptForSequenceClassification, } if is_torch_available() else {} ) _lowerCAmelCase : List[str] = False def snake_case ( self ): """simple docstring""" snake_case = BioGptModelTester(self ) snake_case = ConfigTester(self , config_class=lowerCAmelCase , hidden_size=37 ) def snake_case ( self ): """simple docstring""" self.config_tester.run_common_tests() def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case = type self.model_tester.create_and_check_model(*lowerCAmelCase ) def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*lowerCAmelCase ) def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*lowerCAmelCase , gradient_checkpointing=lowerCAmelCase ) def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*lowerCAmelCase ) def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*lowerCAmelCase ) def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*lowerCAmelCase ) @slow def snake_case ( self ): """simple docstring""" snake_case = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(lowerCAmelCase ) snake_case = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) snake_case = 'left' # Define PAD Token = EOS Token = 50256 snake_case = tokenizer.eos_token snake_case = model.config.eos_token_id # use different length sentences to test batching snake_case = [ 'Hello, my dog is a little', 'Today, I', ] snake_case = tokenizer(lowerCAmelCase , return_tensors='pt' , padding=lowerCAmelCase ) snake_case = inputs['input_ids'].to(lowerCAmelCase ) snake_case = model.generate( input_ids=lowerCAmelCase , attention_mask=inputs['attention_mask'].to(lowerCAmelCase ) , ) snake_case = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(lowerCAmelCase ) snake_case = model.generate(input_ids=lowerCAmelCase ) snake_case = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() snake_case = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(lowerCAmelCase ) snake_case = model.generate(input_ids=lowerCAmelCase , max_length=model.config.max_length - num_paddings ) snake_case = tokenizer.batch_decode(lowerCAmelCase , skip_special_tokens=lowerCAmelCase ) snake_case = tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowerCAmelCase ) snake_case = tokenizer.decode(output_padded[0] , skip_special_tokens=lowerCAmelCase ) snake_case = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , [non_padded_sentence, padded_sentence] ) @slow def snake_case ( self ): """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case = BioGptModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) def snake_case ( self ): """simple docstring""" snake_case ,snake_case = self.model_tester.prepare_config_and_inputs_for_common() snake_case = 3 snake_case = input_dict['input_ids'] snake_case = input_ids.ne(1 ).to(lowerCAmelCase ) snake_case = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) snake_case = BioGptForSequenceClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() snake_case = model(lowerCAmelCase , attention_mask=lowerCAmelCase , labels=lowerCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def snake_case ( self ): """simple docstring""" snake_case ,snake_case = self.model_tester.prepare_config_and_inputs_for_common() snake_case = 3 snake_case = 'multi_label_classification' snake_case = input_dict['input_ids'] snake_case = input_ids.ne(1 ).to(lowerCAmelCase ) snake_case = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) snake_case = BioGptForSequenceClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() snake_case = model(lowerCAmelCase , attention_mask=lowerCAmelCase , labels=lowerCAmelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def snake_case ( self ): """simple docstring""" snake_case = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) snake_case = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) snake_case = model(lowerCAmelCase )[0] snake_case = 4_23_84 snake_case = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , lowerCAmelCase ) snake_case = torch.tensor( [[[-9.52_36, -9.89_18, 10.45_57], [-11.04_69, -9.64_23, 8.10_22], [-8.86_64, -7.88_26, 5.53_25]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCAmelCase , atol=1E-4 ) ) @slow def snake_case ( self ): """simple docstring""" snake_case = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) snake_case = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(lowerCAmelCase ) torch.manual_seed(0 ) snake_case = tokenizer('COVID-19 is' , return_tensors='pt' ).to(lowerCAmelCase ) snake_case = model.generate( **lowerCAmelCase , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=lowerCAmelCase , ) snake_case = tokenizer.decode(output_ids[0] , skip_special_tokens=lowerCAmelCase ) snake_case = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(lowerCAmelCase , lowerCAmelCase )
149
"""simple docstring""" import cmath import math def lowerCAmelCase__ ( _UpperCamelCase : float , _UpperCamelCase : float , _UpperCamelCase : float , _UpperCamelCase : float ) -> complex: """simple docstring""" snake_case = math.radians(_UpperCamelCase ) snake_case = math.radians(_UpperCamelCase ) # Convert voltage and current to rectangular form snake_case = cmath.rect(_UpperCamelCase , _UpperCamelCase ) snake_case = cmath.rect(_UpperCamelCase , _UpperCamelCase ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
149
1
'''simple docstring''' from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def __lowercase ( ) -> Dict: '''simple docstring''' _A = HfArgumentParser(__lowercase ) _A = parser.parse_args_into_dataclasses()[0] _A = TensorFlowBenchmark(args=__lowercase ) try: _A = parser.parse_args_into_dataclasses()[0] except ValueError as e: _A = "Arg --no_{0} is no longer used, please use --no-{0} instead." _A = " ".join(str(__lowercase ).split(" " )[:-1] ) _A = "" _A = eval(str(__lowercase ).split(" " )[-1] ) _A = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__lowercase ) if len(__lowercase ) > 0: _A = full_error_msg + begin_error_msg + str(__lowercase ) raise ValueError(__lowercase ) benchmark.run() if __name__ == "__main__": main()
79
import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('''3.8'''): import importlib_metadata else: import importlib.metadata as importlib_metadata def lowercase_ ( _lowerCamelCase : Any , _lowerCamelCase : List[str]=False): try: lowercase__ : Union[str, Any] = os.environ[key] except KeyError: # KEY isn't set, default to `default`. lowercase__ : int = default else: # KEY is set, convert it to True or False. try: lowercase__ : Optional[int] = strtobool(_lowerCamelCase) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f'''If set, {key} must be yes or no.''') return _value UpperCamelCase = parse_flag_from_env('''RUN_SLOW''', default=False) UpperCamelCase = parse_flag_from_env('''RUN_REMOTE''', default=False) UpperCamelCase = parse_flag_from_env('''RUN_LOCAL''', default=True) UpperCamelCase = parse_flag_from_env('''RUN_PACKAGED''', default=True) # Compression UpperCamelCase = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''') UpperCamelCase = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''') UpperCamelCase = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''') # Audio UpperCamelCase = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''), reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''', ) # Beam UpperCamelCase = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''), reason='''test requires apache-beam and a compatible dill version''', ) # Dill-cloudpickle compatibility UpperCamelCase = pytest.mark.skipif( config.DILL_VERSION <= version.parse('''0.3.2'''), reason='''test requires dill>0.3.2 for cloudpickle compatibility''', ) # Windows UpperCamelCase = pytest.mark.skipif( sys.platform == '''win32''', reason='''test should not be run on Windows''', ) def lowercase_ ( _lowerCamelCase : int): try: import faiss # noqa except ImportError: lowercase__ : Optional[Any] = unittest.skip("test requires faiss")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : int): try: import regex # noqa except ImportError: lowercase__ : List[Any] = unittest.skip("test requires regex")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : int): try: import elasticsearch # noqa except ImportError: lowercase__ : Optional[int] = unittest.skip("test requires elasticsearch")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : Union[str, Any]): try: import sqlalchemy # noqa except ImportError: lowercase__ : Optional[int] = unittest.skip("test requires sqlalchemy")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : int): if not config.TORCH_AVAILABLE: lowercase__ : Tuple = unittest.skip("test requires PyTorch")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : Tuple): if not config.TF_AVAILABLE: lowercase__ : Any = unittest.skip("test requires TensorFlow")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : Dict): if not config.JAX_AVAILABLE: lowercase__ : List[str] = unittest.skip("test requires JAX")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : int): if not config.PIL_AVAILABLE: lowercase__ : Dict = unittest.skip("test requires Pillow")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : Tuple): try: import transformers # noqa F401 except ImportError: return unittest.skip("test requires transformers")(_lowerCamelCase) else: return test_case def lowercase_ ( _lowerCamelCase : Optional[Any]): try: import tiktoken # noqa F401 except ImportError: return unittest.skip("test requires tiktoken")(_lowerCamelCase) else: return test_case def lowercase_ ( _lowerCamelCase : Dict): try: import spacy # noqa F401 except ImportError: return unittest.skip("test requires spacy")(_lowerCamelCase) else: return test_case def lowercase_ ( _lowerCamelCase : Optional[int]): def _require_spacy_model(_lowerCamelCase : Optional[int]): try: import spacy # noqa F401 spacy.load(_lowerCamelCase) except ImportError: return unittest.skip("test requires spacy")(_lowerCamelCase) except OSError: return unittest.skip("test requires spacy model '{}'".format(_lowerCamelCase))(_lowerCamelCase) else: return test_case return _require_spacy_model def lowercase_ ( _lowerCamelCase : Dict): try: import pyspark # noqa F401 except ImportError: return unittest.skip("test requires pyspark")(_lowerCamelCase) else: return test_case def lowercase_ ( _lowerCamelCase : List[str]): try: import joblibspark # noqa F401 except ImportError: return unittest.skip("test requires joblibspark")(_lowerCamelCase) else: return test_case def lowercase_ ( _lowerCamelCase : Dict): if not _run_slow_tests or _run_slow_tests == 0: lowercase__ : Tuple = unittest.skip("test is slow")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : int): if not _run_local_tests or _run_local_tests == 0: lowercase__ : str = unittest.skip("test is local")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : Optional[int]): if not _run_packaged_tests or _run_packaged_tests == 0: lowercase__ : List[Any] = unittest.skip("test is packaged")(_lowerCamelCase) return test_case def lowercase_ ( _lowerCamelCase : Tuple): if not _run_remote_tests or _run_remote_tests == 0: lowercase__ : Union[str, Any] = unittest.skip("test requires remote")(_lowerCamelCase) return test_case def lowercase_ ( *_lowerCamelCase : str): def decorate(cls : str): for name, fn in cls.__dict__.items(): if callable(_lowerCamelCase) and name.startswith("test"): for decorator in decorators: lowercase__ : Optional[int] = decorator(_lowerCamelCase) setattr(cls , _lowerCamelCase , _lowerCamelCase) return cls return decorate class snake_case_ ( __A ): pass class snake_case_ ( __A ): __A : List[Any] = 0 __A : str = 1 __A : int = 2 @contextmanager def lowercase_ ( _lowerCamelCase : List[str]=OfflineSimulationMode.CONNECTION_FAILS , _lowerCamelCase : int=1E-16): lowercase__ : int = requests.Session().request def timeout_request(_lowerCamelCase : str , _lowerCamelCase : Dict , _lowerCamelCase : Dict , **_lowerCamelCase : str): # Change the url to an invalid url so that the connection hangs lowercase__ : Any = "https://10.255.255.1" if kwargs.get("timeout") is None: raise RequestWouldHangIndefinitelyError( f'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.''') lowercase__ : Dict = timeout try: return online_request(_lowerCamelCase , _lowerCamelCase , **_lowerCamelCase) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier lowercase__ : Dict = url lowercase__ : Union[str, Any] = e.args[0] lowercase__ : Optional[Any] = (max_retry_error.args[0].replace("10.255.255.1" , f'''OfflineMock[{url}]'''),) lowercase__ : int = (max_retry_error,) raise def raise_connection_error(_lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[Any] , **_lowerCamelCase : Tuple): raise requests.ConnectionError("Offline mode is enabled." , request=_lowerCamelCase) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("requests.Session.send" , _lowerCamelCase): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("requests.Session.request" , _lowerCamelCase): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("datasets.config.HF_DATASETS_OFFLINE" , _lowerCamelCase): yield else: raise ValueError("Please use a value from the OfflineSimulationMode enum.") @contextmanager def lowercase_ ( *_lowerCamelCase : str , **_lowerCamelCase : Tuple): lowercase__ : Dict = str(Path().resolve()) with tempfile.TemporaryDirectory(*_lowerCamelCase , **_lowerCamelCase) as tmp_dir: try: os.chdir(_lowerCamelCase) yield finally: os.chdir(_lowerCamelCase) @contextmanager def lowercase_ ( ): import gc gc.collect() lowercase__ : Union[str, Any] = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def lowercase_ ( ): import gc gc.collect() lowercase__ : int = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def lowercase_ ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Optional[Any]): return deepcopy(_lowerCamelCase).integers(0 , 100 , 10).tolist() == deepcopy(_lowerCamelCase).integers(0 , 100 , 10).tolist() def lowercase_ ( _lowerCamelCase : str): import decorator from requests.exceptions import HTTPError def _wrapper(_lowerCamelCase : str , *_lowerCamelCase : Dict , **_lowerCamelCase : Dict): try: return func(*_lowerCamelCase , **_lowerCamelCase) except HTTPError as err: if str(_lowerCamelCase).startswith("500") or str(_lowerCamelCase).startswith("502"): pytest.xfail(str(_lowerCamelCase)) raise err return decorator.decorator(_wrapper , _lowerCamelCase) class snake_case_ : def __init__( self : int , lowercase_ : Union[str, Any] , lowercase_ : Dict , lowercase_ : List[str] ) -> List[str]: lowercase__ : Tuple = returncode lowercase__ : int = stdout lowercase__ : Union[str, Any] = stderr async def lowercase_ ( _lowerCamelCase : List[str] , _lowerCamelCase : Dict): while True: lowercase__ : Optional[int] = await stream.readline() if line: callback(_lowerCamelCase) else: break async def lowercase_ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : Union[str, Any]=None , _lowerCamelCase : Optional[Any]=None , _lowerCamelCase : int=None , _lowerCamelCase : Optional[Any]=False , _lowerCamelCase : Tuple=False): if echo: print("\nRunning: " , " ".join(_lowerCamelCase)) lowercase__ : Optional[int] = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=_lowerCamelCase , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=_lowerCamelCase , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) lowercase__ : str = [] lowercase__ : List[str] = [] def tee(_lowerCamelCase : str , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[int]=""): lowercase__ : Optional[int] = line.decode("utf-8").rstrip() sink.append(_lowerCamelCase) if not quiet: print(_lowerCamelCase , _lowerCamelCase , file=_lowerCamelCase) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout , lambda _lowerCamelCase: tee(_lowerCamelCase , _lowerCamelCase , sys.stdout , label="stdout:")), _read_stream(p.stderr , lambda _lowerCamelCase: tee(_lowerCamelCase , _lowerCamelCase , sys.stderr , label="stderr:")), ] , timeout=_lowerCamelCase , ) return _RunOutput(await p.wait() , _lowerCamelCase , _lowerCamelCase) def lowercase_ ( _lowerCamelCase : Optional[int] , _lowerCamelCase : List[str]=None , _lowerCamelCase : Dict=None , _lowerCamelCase : int=180 , _lowerCamelCase : Union[str, Any]=False , _lowerCamelCase : Optional[Any]=True): lowercase__ : Any = asyncio.get_event_loop() lowercase__ : Tuple = loop.run_until_complete( _stream_subprocess(_lowerCamelCase , env=_lowerCamelCase , stdin=_lowerCamelCase , timeout=_lowerCamelCase , quiet=_lowerCamelCase , echo=_lowerCamelCase)) lowercase__ : int = " ".join(_lowerCamelCase) if result.returncode > 0: lowercase__ : Any = "\n".join(result.stderr) raise RuntimeError( f'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n''' f'''The combined stderr from workers follows:\n{stderr}''') # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(f'''\'{cmd_str}\' produced no output.''') return result def lowercase_ ( ): lowercase__ : List[str] = os.environ.get("PYTEST_XDIST_WORKER" , "gw0") lowercase__ : str = re.sub(R"^gw" , "" , _lowerCamelCase , 0 , re.M) return int(_lowerCamelCase) def lowercase_ ( ): lowercase__ : Union[str, Any] = 2_9500 lowercase__ : Optional[int] = pytest_xdist_worker_id() return port + uniq_delta
87
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowercase__ : Tuple = { '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: lowercase__ : Dict = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Tuple = [ '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 lowercase__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
370
'''simple docstring''' def _lowerCAmelCase ( __snake_case : str ) -> str: __A : Optional[Any] = [0] * len(__snake_case ) __A : Dict = [] __A : Optional[int] = [1] * len(__snake_case ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__snake_case ) ): if indegree[i] == 0: queue.append(__snake_case ) while queue: __A : int = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __A : str = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(__snake_case ) print(max(__snake_case ) ) # Adjacency list of Graph lowercase__ : Dict = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
190
0
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## A_ = 16 A_ = 32 def UpperCAmelCase__ (snake_case__ : Accelerator , snake_case__ : int = 16 ): """simple docstring""" _snake_case : Optional[Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _snake_case : Any = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(snake_case__ : Any ): # max_length=None => use the model max length (it's actually the default) _snake_case : Any = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _snake_case : List[Any] = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _snake_case : int = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(snake_case__ : int ): # On TPU it's best to pad everything to the same length or training will be very slow. _snake_case : Optional[int] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _snake_case : str = 16 elif accelerator.mixed_precision != "no": _snake_case : Optional[int] = 8 else: _snake_case : Optional[int] = None return tokenizer.pad( snake_case__ , padding="""longest""" , max_length=snake_case__ , pad_to_multiple_of=snake_case__ , return_tensors="""pt""" , ) # Instantiate dataloaders. _snake_case : Optional[int] = DataLoader( tokenized_datasets["""train"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) _snake_case : Dict = DataLoader( tokenized_datasets["""validation"""] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders A_ = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (snake_case__ : List[Any] , snake_case__ : Any ): """simple docstring""" if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , snake_case__ ) == "1": _snake_case : List[Any] = 2 # Initialize accelerator _snake_case : str = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _snake_case : Tuple = config["""lr"""] _snake_case : str = int(config["""num_epochs"""] ) _snake_case : Union[str, Any] = int(config["""seed"""] ) _snake_case : Union[str, Any] = int(config["""batch_size"""] ) _snake_case : List[str] = evaluate.load("""glue""" , """mrpc""" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=snake_case__ ) def inner_training_loop(snake_case__ : Union[str, Any] ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _snake_case : List[Any] = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=snake_case__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _snake_case : Tuple = model.to(accelerator.device ) # Instantiate optimizer _snake_case : str = AdamW(params=model.parameters() , lr=snake_case__ ) _snake_case , _snake_case : Optional[int] = get_dataloaders(snake_case__ , snake_case__ ) # Instantiate scheduler _snake_case : str = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=1_00 , num_training_steps=(len(snake_case__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _snake_case , _snake_case , _snake_case , _snake_case , _snake_case : List[str] = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Now we train the model for epoch in range(snake_case__ ): model.train() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _snake_case : int = model(**snake_case__ ) _snake_case : str = outputs.loss accelerator.backward(snake_case__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _snake_case : int = model(**snake_case__ ) _snake_case : Optional[Any] = outputs.logits.argmax(dim=-1 ) _snake_case , _snake_case : Tuple = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) _snake_case : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , snake_case__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): """simple docstring""" _snake_case : Any = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=snake_case__ , default=snake_case__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) _snake_case : Dict = parser.parse_args() _snake_case : int = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
64
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : list ): """simple docstring""" if len(snake_case__ ) <= 1: return [tuple(snake_case__ )] _snake_case : List[Any] = [] def generate(snake_case__ : int , snake_case__ : list ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case__ ) for i in range(k - 1 ): if k % 2 == 0: # k is even _snake_case , _snake_case : Optional[Any] = arr[k - 1], arr[i] else: # k is odd _snake_case , _snake_case : List[str] = arr[k - 1], arr[0] generate(k - 1 , snake_case__ ) generate(len(snake_case__ ) , snake_case__ ) return res if __name__ == "__main__": A_ = input('''Enter numbers separated by a comma:\n''').strip() A_ = [int(item) for item in user_input.split(''',''')] print(heaps(arr))
64
1
"""simple docstring""" def lowercase (SCREAMING_SNAKE_CASE_ : int = 10_00 ) -> int: SCREAMING_SNAKE_CASE = 2**power SCREAMING_SNAKE_CASE = str(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = list(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = 0 for i in list_num: sum_of_num += int(SCREAMING_SNAKE_CASE_ ) return sum_of_num if __name__ == "__main__": __UpperCamelCase = int(input('''Enter the power of 2: ''').strip()) print('''2 ^ ''', power, ''' = ''', 2**power) __UpperCamelCase = solution(power) print('''Sum of the digits is: ''', result)
38
"""simple docstring""" from collections import deque from .hash_table import HashTable class lowerCAmelCase ( lowerCamelCase_ ): '''simple docstring''' def __init__( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> Dict: super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__ ) def __A ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[Any]: SCREAMING_SNAKE_CASE = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = self.values[key] def __A ( self ) -> List[Any]: return ( sum(self.charge_factor - len(lowerCAmelCase__ ) for slot in self.values ) / self.size_table * self.charge_factor ) def __A ( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> Tuple: if not ( len(self.values[key] ) == self.charge_factor and self.values.count(lowerCAmelCase__ ) == 0 ): return key return super()._collision_resolution(lowerCAmelCase__ , lowerCAmelCase__ )
38
1
import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, 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 : @staticmethod def __magic_name__ ( *__A : Optional[int], **__A : int ): pass @is_pipeline_test @require_vision @require_torch class __UpperCAmelCase ( unittest.TestCase ): UpperCamelCase = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def __magic_name__ ( self : Any, __A : Dict, __A : List[Any], __A : Dict ): UpperCAmelCase : Union[str, Any] = pipeline( '''zero-shot-object-detection''', model='''hf-internal-testing/tiny-random-owlvit-object-detection''' ) UpperCAmelCase : List[str] = [ { '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], } ] return object_detector, examples def __magic_name__ ( self : Dict, __A : int, __A : List[Any] ): UpperCAmelCase : Union[str, Any] = object_detector(examples[0], threshold=0.0 ) UpperCAmelCase : str = len(__A ) self.assertGreater(__A, 0 ) self.assertEqual( __A, [ { '''score''': ANY(__A ), '''label''': ANY(__A ), '''box''': {'''xmin''': ANY(__A ), '''ymin''': ANY(__A ), '''xmax''': ANY(__A ), '''ymax''': ANY(__A )}, } for i in range(__A ) ], ) @require_tf @unittest.skip('''Zero Shot Object Detection not implemented in TF''' ) def __magic_name__ ( self : Any ): pass @require_torch def __magic_name__ ( self : Optional[int] ): UpperCAmelCase : int = pipeline( '''zero-shot-object-detection''', model='''hf-internal-testing/tiny-random-owlvit-object-detection''' ) UpperCAmelCase : List[str] = object_detector( '''./tests/fixtures/tests_samples/COCO/000000039769.png''', candidate_labels=['''cat''', '''remote''', '''couch'''], threshold=0.6_4, ) self.assertEqual( nested_simplify(__A, decimals=4 ), [ {'''score''': 0.7_2_3_5, '''label''': '''cat''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.7_2_1_8, '''label''': '''remote''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.7_1_8_4, '''label''': '''couch''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.6_7_4_8, '''label''': '''remote''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_6_5_6, '''label''': '''cat''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_6_1_4, '''label''': '''couch''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_4_5_6, '''label''': '''remote''', '''box''': {'''xmin''': 4_9_4, '''ymin''': 1_0_5, '''xmax''': 5_2_1, '''ymax''': 1_2_7}}, {'''score''': 0.6_4_2, '''label''': '''remote''', '''box''': {'''xmin''': 6_7, '''ymin''': 2_7_4, '''xmax''': 9_3, '''ymax''': 2_9_7}}, {'''score''': 0.6_4_1_9, '''label''': '''cat''', '''box''': {'''xmin''': 4_9_4, '''ymin''': 1_0_5, '''xmax''': 5_2_1, '''ymax''': 1_2_7}}, ], ) UpperCAmelCase : Optional[int] = object_detector( [ { '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], } ], threshold=0.6_4, ) self.assertEqual( nested_simplify(__A, decimals=4 ), [ [ {'''score''': 0.7_2_3_5, '''label''': '''cat''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.7_2_1_8, '''label''': '''remote''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.7_1_8_4, '''label''': '''couch''', '''box''': {'''xmin''': 2_0_4, '''ymin''': 1_6_7, '''xmax''': 2_3_2, '''ymax''': 1_9_0}}, {'''score''': 0.6_7_4_8, '''label''': '''remote''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_6_5_6, '''label''': '''cat''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_6_1_4, '''label''': '''couch''', '''box''': {'''xmin''': 5_7_1, '''ymin''': 8_3, '''xmax''': 5_9_8, '''ymax''': 1_0_3}}, {'''score''': 0.6_4_5_6, '''label''': '''remote''', '''box''': {'''xmin''': 4_9_4, '''ymin''': 1_0_5, '''xmax''': 5_2_1, '''ymax''': 1_2_7}}, {'''score''': 0.6_4_2, '''label''': '''remote''', '''box''': {'''xmin''': 6_7, '''ymin''': 2_7_4, '''xmax''': 9_3, '''ymax''': 2_9_7}}, {'''score''': 0.6_4_1_9, '''label''': '''cat''', '''box''': {'''xmin''': 4_9_4, '''ymin''': 1_0_5, '''xmax''': 5_2_1, '''ymax''': 1_2_7}}, ] ], ) @require_torch @slow def __magic_name__ ( self : Union[str, Any] ): UpperCAmelCase : Dict = pipeline('''zero-shot-object-detection''' ) UpperCAmelCase : Optional[int] = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''', candidate_labels=['''cat''', '''remote''', '''couch'''], ) self.assertEqual( nested_simplify(__A, decimals=4 ), [ {'''score''': 0.2_8_6_8, '''label''': '''cat''', '''box''': {'''xmin''': 3_2_4, '''ymin''': 2_0, '''xmax''': 6_4_0, '''ymax''': 3_7_3}}, {'''score''': 0.2_7_7, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_2, '''xmax''': 1_7_7, '''ymax''': 1_1_5}}, {'''score''': 0.2_5_3_7, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 5_5, '''xmax''': 3_1_5, '''ymax''': 4_7_2}}, {'''score''': 0.1_4_7_4, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_5, '''ymin''': 7_4, '''xmax''': 3_7_1, '''ymax''': 1_8_7}}, {'''score''': 0.1_2_0_8, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_4_2, '''ymax''': 4_7_6}}, ], ) UpperCAmelCase : Optional[Any] = object_detector( [ { '''image''': '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], }, { '''image''': '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], }, ], ) self.assertEqual( nested_simplify(__A, decimals=4 ), [ [ {'''score''': 0.2_8_6_8, '''label''': '''cat''', '''box''': {'''xmin''': 3_2_4, '''ymin''': 2_0, '''xmax''': 6_4_0, '''ymax''': 3_7_3}}, {'''score''': 0.2_7_7, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_2, '''xmax''': 1_7_7, '''ymax''': 1_1_5}}, {'''score''': 0.2_5_3_7, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 5_5, '''xmax''': 3_1_5, '''ymax''': 4_7_2}}, {'''score''': 0.1_4_7_4, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_5, '''ymin''': 7_4, '''xmax''': 3_7_1, '''ymax''': 1_8_7}}, {'''score''': 0.1_2_0_8, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_4_2, '''ymax''': 4_7_6}}, ], [ {'''score''': 0.2_8_6_8, '''label''': '''cat''', '''box''': {'''xmin''': 3_2_4, '''ymin''': 2_0, '''xmax''': 6_4_0, '''ymax''': 3_7_3}}, {'''score''': 0.2_7_7, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_2, '''xmax''': 1_7_7, '''ymax''': 1_1_5}}, {'''score''': 0.2_5_3_7, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 5_5, '''xmax''': 3_1_5, '''ymax''': 4_7_2}}, {'''score''': 0.1_4_7_4, '''label''': '''remote''', '''box''': {'''xmin''': 3_3_5, '''ymin''': 7_4, '''xmax''': 3_7_1, '''ymax''': 1_8_7}}, {'''score''': 0.1_2_0_8, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_4_2, '''ymax''': 4_7_6}}, ], ], ) @require_tf @unittest.skip('''Zero Shot Object Detection not implemented in TF''' ) def __magic_name__ ( self : Union[str, Any] ): pass @require_torch @slow def __magic_name__ ( self : int ): UpperCAmelCase : Optional[int] = 0.2 UpperCAmelCase : Union[str, Any] = pipeline('''zero-shot-object-detection''' ) UpperCAmelCase : Tuple = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''', candidate_labels=['''cat''', '''remote''', '''couch'''], threshold=__A, ) self.assertEqual( nested_simplify(__A, decimals=4 ), [ {'''score''': 0.2_8_6_8, '''label''': '''cat''', '''box''': {'''xmin''': 3_2_4, '''ymin''': 2_0, '''xmax''': 6_4_0, '''ymax''': 3_7_3}}, {'''score''': 0.2_7_7, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_2, '''xmax''': 1_7_7, '''ymax''': 1_1_5}}, {'''score''': 0.2_5_3_7, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 5_5, '''xmax''': 3_1_5, '''ymax''': 4_7_2}}, ], ) @require_torch @slow def __magic_name__ ( self : Any ): UpperCAmelCase : List[str] = 2 UpperCAmelCase : int = pipeline('''zero-shot-object-detection''' ) UpperCAmelCase : Dict = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''', candidate_labels=['''cat''', '''remote''', '''couch'''], top_k=__A, ) self.assertEqual( nested_simplify(__A, decimals=4 ), [ {'''score''': 0.2_8_6_8, '''label''': '''cat''', '''box''': {'''xmin''': 3_2_4, '''ymin''': 2_0, '''xmax''': 6_4_0, '''ymax''': 3_7_3}}, {'''score''': 0.2_7_7, '''label''': '''remote''', '''box''': {'''xmin''': 4_0, '''ymin''': 7_2, '''xmax''': 1_7_7, '''ymax''': 1_1_5}}, ], )
336
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def a__ ( ) -> tuple[list[int], int]: UpperCAmelCase : str = [randint(-1_000 , 1_000 ) for i in range(10 )] UpperCAmelCase : Any = randint(-5_000 , 5_000 ) return (arr, r) _lowerCamelCase : Any = make_dataset() def a__ ( UpperCAmelCase : list[int] , UpperCAmelCase : int ) -> tuple[int, ...]: for triplet in permutations(UpperCAmelCase , 3 ): if sum(UpperCAmelCase ) == target: return tuple(sorted(UpperCAmelCase ) ) return (0, 0, 0) def a__ ( UpperCAmelCase : list[int] , UpperCAmelCase : int ) -> tuple[int, int, int]: arr.sort() UpperCAmelCase : Tuple = len(UpperCAmelCase ) for i in range(n - 1 ): UpperCAmelCase , UpperCAmelCase : int = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def a__ ( ) -> tuple[float, float]: UpperCAmelCase : Union[str, Any] = ''' from __main__ import dataset, triplet_sum1, triplet_sum2 ''' UpperCAmelCase : Tuple = ''' triplet_sum1(*dataset) ''' UpperCAmelCase : List[str] = ''' triplet_sum2(*dataset) ''' UpperCAmelCase : Tuple = repeat(setup=UpperCAmelCase , stmt=UpperCAmelCase , repeat=5 , number=10_000 ) UpperCAmelCase : str = repeat(setup=UpperCAmelCase , stmt=UpperCAmelCase , repeat=5 , number=10_000 ) return (min(UpperCAmelCase ), min(UpperCAmelCase )) if __name__ == "__main__": from doctest import testmod testmod() _lowerCamelCase : int = solution_times() print(f"""The time for naive implementation is {times[0]}.""") print(f"""The time for optimized implementation is {times[1]}.""")
336
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase: Tuple = logging.get_logger(__name__) lowerCAmelCase: Tuple = { 'facebook/s2t-wav2vec2-large-en-de': ( 'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class a__( lowerCamelCase__ ): lowercase__ = """speech_to_text_2""" lowercase__ = ["""past_key_values"""] lowercase__ = {"""num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : Union[str, Any] , __snake_case : Optional[int]=1_00_00 , __snake_case : Optional[int]=6 , __snake_case : Optional[int]=20_48 , __snake_case : int=4 , __snake_case : List[str]=0.0 , __snake_case : Union[str, Any]=True , __snake_case : Dict="relu" , __snake_case : int=2_56 , __snake_case : List[Any]=0.1 , __snake_case : Optional[int]=0.0 , __snake_case : List[Any]=0.0 , __snake_case : int=0.02 , __snake_case : int=2 , __snake_case : Tuple=True , __snake_case : Optional[Any]=1 , __snake_case : Union[str, Any]=0 , __snake_case : str=2 , __snake_case : str=10_24 , **__snake_case : Dict , ): a : List[str] = vocab_size a : List[str] = d_model a : Any = decoder_ffn_dim a : str = decoder_layers a : Optional[int] = decoder_attention_heads a : Tuple = dropout a : List[Any] = attention_dropout a : List[Any] = activation_dropout a : Dict = activation_function a : int = init_std a : List[str] = decoder_layerdrop a : Optional[int] = use_cache a : Any = decoder_layers a : List[str] = scale_embedding # scale factor will be sqrt(d_model) if True a : List[Any] = max_target_positions super().__init__( pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , decoder_start_token_id=__snake_case , **__snake_case , )
357
'''simple docstring''' import copy import os import cva import numpy as np from matplotlib import pyplot as plt class a__: def __init__( self : Optional[int] ): a : int = '' a : List[str] = '' a : int = [] a : Optional[Any] = 0 a : Optional[Any] = 2_56 a : int = 0 a : Optional[int] = 0 a : str = 0 a : int = 0 def lowercase_ ( self : List[str] , __snake_case : int ): a : Optional[Any] = cva.imread(__snake_case , 0 ) a : int = copy.deepcopy(self.img ) a , a , a : Optional[int] = plt.hist(self.img.ravel() , 2_56 , [0, 2_56] , label='x' ) a : str = np.sum(__snake_case ) for i in range(len(__snake_case ) ): a : List[str] = x[i] / self.k self.sk += prk a : List[Any] = (self.L - 1) * self.sk if self.rem != 0: a : Union[str, Any] = int(last % last ) a : int = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__snake_case ) a : int = int(np.ma.count(self.img ) / self.img[1].size ) a : Dict = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): a : Tuple = self.img[j][i] if num != self.last_list[num]: a : Union[str, Any] = self.last_list[num] cva.imwrite('output_data/output.jpg' , self.img ) def lowercase_ ( self : Union[str, Any] ): plt.hist(self.img.ravel() , 2_56 , [0, 2_56] ) def lowercase_ ( self : Any ): cva.imshow('Output-Image' , self.img ) cva.imshow('Input-Image' , self.original_image ) cva.waitKey(50_00 ) cva.destroyAllWindows() if __name__ == "__main__": lowerCAmelCase: Dict = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') lowerCAmelCase: Optional[Any] = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
96
0
'''simple docstring''' import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class lowercase ( unittest.TestCase ): """simple docstring""" def __init__( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :str = parent def lowerCAmelCase__ ( self ): '''simple docstring''' return {} def a ( ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ :Union[str, Any] = '''<HTML> <HEAD> <TITLE>sample document</TITLE> </HEAD> <BODY BGCOLOR="FFFFFF"> <HR> <a href="http://google.com">Goog</a> <H1>This is one header</H1> <H2>This is a another Header</H2> <P>Travel from <P> <B>SFO to JFK</B> <BR> <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B> <HR> <div style="color:#0000FF"> <h3>Traveler <b> name </b> is <p> John Doe </p> </div>''' UpperCamelCase__ :int = ''' <!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html> ''' return [html_string_a, html_string_a] @require_bsa class lowercase ( A__ , unittest.TestCase ): """simple docstring""" _a = MarkupLMFeatureExtractor if is_bsa_available() else None def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :int = MarkupLMFeatureExtractionTester(self ) @property def lowerCAmelCase__ ( self ): '''simple docstring''' return self.feature_extract_tester.prepare_feat_extract_dict() def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :int = self.feature_extraction_class() # Test not batched input UpperCamelCase__ :int = get_html_strings()[0] UpperCamelCase__ :int = feature_extractor(UpperCamelCase_ ) # fmt: off UpperCamelCase__ :Union[str, Any] = [['''sample document''', '''Goog''', '''This is one header''', '''This is a another Header''', '''Travel from''', '''SFO to JFK''', '''on May 2, 2015 at 2:00 pm. For details go to confirm.com''', '''Traveler''', '''name''', '''is''', '''John Doe''']] UpperCamelCase__ :Optional[Any] = [['''/html/head/title''', '''/html/body/a''', '''/html/body/h1''', '''/html/body/h2''', '''/html/body/p''', '''/html/body/p/p/b[1]''', '''/html/body/p/p/b[2]/i''', '''/html/body/p/p/div/h3''', '''/html/body/p/p/div/h3/b''', '''/html/body/p/p/div/h3''', '''/html/body/p/p/div/h3/p''']] # fmt: on self.assertEqual(encoding.nodes , UpperCamelCase_ ) self.assertEqual(encoding.xpaths , UpperCamelCase_ ) # Test batched UpperCamelCase__ :str = get_html_strings() UpperCamelCase__ :Optional[Any] = feature_extractor(UpperCamelCase_ ) # fmt: off UpperCamelCase__ :List[str] = expected_nodes + [['''My First Heading''', '''My first paragraph.''']] UpperCamelCase__ :int = expected_xpaths + [['''/html/body/h1''', '''/html/body/p''']] self.assertEqual(len(encoding.nodes ) , 2 ) self.assertEqual(len(encoding.xpaths ) , 2 ) self.assertEqual(encoding.nodes , UpperCamelCase_ ) self.assertEqual(encoding.xpaths , UpperCamelCase_ )
97
'''simple docstring''' import re from filelock import FileLock try: import nltk __snake_case = True except (ImportError, ModuleNotFoundError): __snake_case = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt''', quiet=True) def a ( __a ) -> str: '''simple docstring''' re.sub('''<n>''' , '''''' , __a ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(__a ) )
97
1
from math import factorial def lowerCAmelCase_ ( __lowerCAmelCase = 1_00 )-> Optional[Any]: '''simple docstring''' return sum(map(__UpperCamelCase , str(factorial(__UpperCamelCase ) ) ) ) if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
368
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { '''RWKV/rwkv-4-169m-pile''': '''https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-430m-pile''': '''https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json''', '''RWKV/rwkv-4-1b5-pile''': '''https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json''', '''RWKV/rwkv-4-3b-pile''': '''https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-7b-pile''': '''https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json''', '''RWKV/rwkv-4-14b-pile''': '''https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json''', '''RWKV/rwkv-raven-1b5''': '''https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json''', '''RWKV/rwkv-raven-3b''': '''https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json''', '''RWKV/rwkv-raven-7b''': '''https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json''', '''RWKV/rwkv-raven-14b''': '''https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json''', } class __snake_case ( lowerCamelCase__ ): __lowerCamelCase : str = """rwkv""" __lowerCamelCase : str = {"""max_position_embeddings""": """context_length"""} def __init__( self , snake_case__=5_0277 , snake_case__=1024 , snake_case__=4096 , snake_case__=32 , snake_case__=None , snake_case__=None , snake_case__=1e-5 , snake_case__=0 , snake_case__=0 , snake_case__=6 , snake_case__=False , snake_case__=True , **snake_case__ , ) -> List[str]: '''simple docstring''' UpperCAmelCase : int =vocab_size UpperCAmelCase : List[str] =context_length UpperCAmelCase : Any =hidden_size UpperCAmelCase : Tuple =num_hidden_layers UpperCAmelCase : str =attention_hidden_size if attention_hidden_size is not None else hidden_size UpperCAmelCase : List[Any] =intermediate_size if intermediate_size is not None else 4 * hidden_size UpperCAmelCase : Optional[int] =layer_norm_epsilon UpperCAmelCase : int =rescale_every UpperCAmelCase : Any =use_cache UpperCAmelCase : List[str] =bos_token_id UpperCAmelCase : Any =eos_token_id super().__init__( tie_word_embeddings=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ )
78
0
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" if "img_encoder.pos_embed" in name: lowerCamelCase__: List[Any] =name.replace("img_encoder.pos_embed" , "vision_model.embeddings.position_embeddings" ) if "img_encoder.patch_embed.proj" in name: lowerCamelCase__: int =name.replace("img_encoder.patch_embed.proj" , "vision_model.embeddings.patch_embeddings.projection" ) if "img_encoder.patch_embed.norm" in name: lowerCamelCase__: int =name.replace("img_encoder.patch_embed.norm" , "vision_model.embeddings.layernorm" ) if "img_encoder.layers" in name: lowerCamelCase__: int =name.replace("img_encoder.layers" , "vision_model.encoder.stages" ) if "blocks" in name and "res" not in name: lowerCamelCase__: Tuple =name.replace("blocks" , "layers" ) if "attn" in name and "pre_assign" not in name: lowerCamelCase__: Optional[Any] =name.replace("attn" , "self_attn" ) if "proj" in name and "self_attn" in name and "text" not in name: lowerCamelCase__: Dict =name.replace("proj" , "out_proj" ) if "pre_assign_attn.attn.proj" in name: lowerCamelCase__: Optional[int] =name.replace("pre_assign_attn.attn.proj" , "pre_assign_attn.attn.out_proj" ) if "norm1" in name: lowerCamelCase__: List[str] =name.replace("norm1" , "layer_norm1" ) if "norm2" in name and "pre_assign" not in name: lowerCamelCase__: Union[str, Any] =name.replace("norm2" , "layer_norm2" ) if "img_encoder.norm" in name: lowerCamelCase__: List[Any] =name.replace("img_encoder.norm" , "vision_model.layernorm" ) # text encoder if "text_encoder.token_embedding" in name: lowerCamelCase__: Union[str, Any] =name.replace("text_encoder.token_embedding" , "text_model.embeddings.token_embedding" ) if "text_encoder.positional_embedding" in name: lowerCamelCase__: Any =name.replace("text_encoder.positional_embedding" , "text_model.embeddings.position_embedding.weight" ) if "text_encoder.transformer.resblocks." in name: lowerCamelCase__: str =name.replace("text_encoder.transformer.resblocks." , "text_model.encoder.layers." ) if "ln_1" in name: lowerCamelCase__: Tuple =name.replace("ln_1" , "layer_norm1" ) if "ln_2" in name: lowerCamelCase__: Union[str, Any] =name.replace("ln_2" , "layer_norm2" ) if "c_fc" in name: lowerCamelCase__: Optional[Any] =name.replace("c_fc" , "fc1" ) if "c_proj" in name: lowerCamelCase__: List[Any] =name.replace("c_proj" , "fc2" ) if "text_encoder" in name: lowerCamelCase__: List[Any] =name.replace("text_encoder" , "text_model" ) if "ln_final" in name: lowerCamelCase__: Any =name.replace("ln_final" , "final_layer_norm" ) # projection layers if "img_projector.linear_hidden." in name: lowerCamelCase__: Tuple =name.replace("img_projector.linear_hidden." , "visual_projection." ) if "img_projector.linear_out." in name: lowerCamelCase__: Tuple =name.replace("img_projector.linear_out." , "visual_projection.3." ) if "text_projector.linear_hidden" in name: lowerCamelCase__: List[str] =name.replace("text_projector.linear_hidden" , "text_projection" ) if "text_projector.linear_out" in name: lowerCamelCase__: Union[str, Any] =name.replace("text_projector.linear_out" , "text_projection.3" ) return name def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" for key in orig_state_dict.copy().keys(): lowerCamelCase__: str =orig_state_dict.pop(__a ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCamelCase__: Dict =key.split("." ) lowerCamelCase__: Any =int(key_split[2] ), int(key_split[4] ) lowerCamelCase__: str =config.vision_config.hidden_size if "weight" in key: lowerCamelCase__: Dict =val[:dim, :] lowerCamelCase__: Any =val[dim : dim * 2, :] lowerCamelCase__: str =val[-dim:, :] else: lowerCamelCase__: List[str] =val[:dim] lowerCamelCase__: List[str] =val[dim : dim * 2] lowerCamelCase__: str =val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCamelCase__: str =key.split("." ) lowerCamelCase__: Tuple =int(key_split[3] ) lowerCamelCase__: Optional[int] =config.text_config.hidden_size if "weight" in key: lowerCamelCase__: List[str] =val[:dim, :] lowerCamelCase__: List[Any] =val[ dim : dim * 2, : ] lowerCamelCase__: Union[str, Any] =val[-dim:, :] else: lowerCamelCase__: Tuple =val[:dim] lowerCamelCase__: Dict =val[dim : dim * 2] lowerCamelCase__: Tuple =val[-dim:] else: lowerCamelCase__: str =rename_key(__a ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): lowerCamelCase__: int =val.squeeze_() else: lowerCamelCase__: Optional[Any] =val return orig_state_dict def lowerCAmelCase_ ( ) -> Any: """simple docstring""" lowerCamelCase__: Union[str, Any] ="http://images.cocodataset.org/val2017/000000039769.jpg" lowerCamelCase__: str =Image.open(requests.get(__a , stream=__a ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( __a , __a , __a="groupvit-gcc-yfcc" , __a=False ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[int] =GroupViTConfig() lowerCamelCase__: Optional[int] =GroupViTModel(__a ).eval() lowerCamelCase__: Optional[Any] =torch.load(__a , map_location="cpu" )["model"] lowerCamelCase__: Union[str, Any] =convert_state_dict(__a , __a ) lowerCamelCase__: Union[str, Any] =model.load_state_dict(__a , strict=__a ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(__a ) == 0) # verify result lowerCamelCase__: Union[str, Any] =CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32" ) lowerCamelCase__: int =prepare_img() lowerCamelCase__: int =processor(text=["a photo of a cat", "a photo of a dog"] , images=__a , padding=__a , return_tensors="pt" ) with torch.no_grad(): lowerCamelCase__: List[Any] =model(**__a ) if model_name == "groupvit-gcc-yfcc": lowerCamelCase__: Optional[Any] =torch.tensor([[1_3.3_5_2_3, 6.3_6_2_9]] ) elif model_name == "groupvit-gcc-redcaps": lowerCamelCase__: Dict =torch.tensor([[1_6.1_8_7_3, 8.6_2_3_0]] ) else: raise ValueError(F"""Model name {model_name} not supported.""" ) assert torch.allclose(outputs.logits_per_image , __a , atol=1e-3 ) processor.save_pretrained(__a ) model.save_pretrained(__a ) print("Successfully saved processor and model to" , __a ) if push_to_hub: print("Pushing to the hub..." ) processor.push_to_hub(__a , organization="nielsr" ) model.push_to_hub(__a , organization="nielsr" ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to dump the processor and PyTorch model." ) parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to GroupViT checkpoint") parser.add_argument( "--model_name", default="groupvit-gccy-fcc", type=str, help="Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.", ) __A = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
10
"""simple docstring""" # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version lowerCAmelCase__ = get_logger(__name__) class SCREAMING_SNAKE_CASE__ : """simple docstring""" a : Optional[Any] ="dummy_data" a : int ="datasets" a : Tuple =False def __init__( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ = None , snake_case__ = False , snake_case__ = True , snake_case__ = None , ): """simple docstring""" lowerCAmelCase : Tuple = 0 lowerCAmelCase : int = dataset_name lowerCAmelCase : List[Any] = cache_dir lowerCAmelCase : List[str] = use_local_dummy_data lowerCAmelCase : List[str] = config # download_callbacks take a single url as input lowerCAmelCase : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root lowerCAmelCase : Tuple = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general lowerCAmelCase : Union[str, Any] = str(snake_case__ ) # to be downloaded lowerCAmelCase : List[Any] = None lowerCAmelCase : List[Any] = None @property def lowercase__ ( self ): """simple docstring""" if self._dummy_file is None: lowerCAmelCase : Any = self.download_dummy_data() return self._dummy_file @property def lowercase__ ( self ): """simple docstring""" if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("dummy" , self.version_name ) @property def lowercase__ ( self ): """simple docstring""" return os.path.join(self.dummy_data_folder , "dummy_data.zip" ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Optional[Any] = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) lowerCAmelCase : str = cached_path( snake_case__ , cache_dir=self.cache_dir , extract_compressed_file=snake_case__ , force_extract=snake_case__ ) return os.path.join(snake_case__ , self.dummy_file_name ) @property def lowercase__ ( self ): """simple docstring""" return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def lowercase__ ( self ): """simple docstring""" if self._bucket_url is None: lowerCAmelCase : Union[str, Any] = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , "/" ) ) return self._bucket_url @property def lowercase__ ( self ): """simple docstring""" if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , "/" ).split("/" )[:-1] ) def lowercase__ ( self , snake_case__ , *snake_case__ ): """simple docstring""" if self.load_existing_dummy_data: # dummy data is downloaded and tested lowerCAmelCase : int = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned lowerCAmelCase : List[Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(snake_case__ , snake_case__ ): return self.create_dummy_data_dict(snake_case__ , snake_case__ ) elif isinstance(snake_case__ , (list, tuple) ): return self.create_dummy_data_list(snake_case__ , snake_case__ ) else: return self.create_dummy_data_single(snake_case__ , snake_case__ ) def lowercase__ ( self , snake_case__ , *snake_case__ ): """simple docstring""" return self.download_and_extract(snake_case__ ) def lowercase__ ( self , snake_case__ , snake_case__ ): """simple docstring""" return self.download_and_extract(snake_case__ ) def lowercase__ ( self , snake_case__ , *snake_case__ , **snake_case__ ): """simple docstring""" return path def lowercase__ ( self ): """simple docstring""" return {} def lowercase__ ( self , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : List[Any] = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(snake_case__ , snake_case__ ): for single_url in single_urls: download_callback(snake_case__ ) else: lowerCAmelCase : List[str] = single_urls download_callback(snake_case__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(snake_case__ , snake_case__ ): lowerCAmelCase : Tuple = [os.path.join(snake_case__ , urllib.parse.quote_plus(Path(snake_case__ ).name ) ) for x in single_urls] else: lowerCAmelCase : int = single_urls lowerCAmelCase : Any = os.path.join(snake_case__ , urllib.parse.quote_plus(Path(snake_case__ ).name ) ) lowerCAmelCase : Union[str, Any] = value # make sure that values are unique if all(isinstance(snake_case__ , snake_case__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique lowerCAmelCase : Union[str, Any] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def lowercase__ ( self , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : Dict = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one lowerCAmelCase : Optional[Any] = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" , snake_case__ ) ) for url in data_url ) lowerCAmelCase : Any = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): lowerCAmelCase : int = [data_url[0]] * len(snake_case__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(snake_case__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus lowerCAmelCase : Dict = os.path.join(snake_case__ , urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(snake_case__ ) return dummy_data_list def lowercase__ ( self , snake_case__ , snake_case__ ): """simple docstring""" for download_callback in self.download_callbacks: download_callback(snake_case__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus lowerCAmelCase : Tuple = os.path.join(snake_case__ , urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(snake_case__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def lowercase__ ( self ): """simple docstring""" pass def lowercase__ ( self ): """simple docstring""" pass def lowercase__ ( self , snake_case__ ): """simple docstring""" def _iter_archive_members(snake_case__ ): # this preserves the order of the members inside the ZIP archive lowerCAmelCase : str = Path(self.dummy_file ).parent lowerCAmelCase : Optional[Any] = path.relative_to(snake_case__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: lowerCAmelCase : List[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(snake_case__ ) lowerCAmelCase : List[Any] = Path(snake_case__ ) lowerCAmelCase : str = _iter_archive_members(snake_case__ ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(snake_case__ ).as_posix(), file_path.open("rb" ) def lowercase__ ( self , snake_case__ ): """simple docstring""" if not isinstance(snake_case__ , snake_case__ ): lowerCAmelCase : List[Any] = [paths] for path in paths: if os.path.isfile(snake_case__ ): if os.path.basename(snake_case__ ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(snake_case__ ): if os.path.basename(snake_case__ ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(snake_case__ ): if filename.startswith((".", "__") ): continue yield os.path.join(snake_case__ , snake_case__ )
108
0
from __future__ import annotations def a( A : int , A : int ) -> list[str]: """simple docstring""" if partitions <= 0: raise ValueError("partitions must be a positive number!" ) if partitions > number_of_bytes: raise ValueError("partitions can not > number_of_bytes!" ) a = number_of_bytes // partitions a = [] for i in range(A ): a = i * bytes_per_partition + 1 a = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
71
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _lowercase ( lowerCAmelCase ): """simple docstring""" __A = ["image_processor", "tokenizer"] __A = "ViTImageProcessor" __A = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__(self , lowerCamelCase_=None , lowerCamelCase_=None , **lowerCamelCase_ ): """simple docstring""" a = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , lowerCamelCase_ , ) a = kwargs.pop("feature_extractor" ) a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(lowerCamelCase_ , lowerCamelCase_ ) def __call__(self , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , **lowerCamelCase_ ): """simple docstring""" if text is None and visual_prompt is None and images is None: raise ValueError("You have to specify either text, visual prompt or images." ) if text is not None and visual_prompt is not None: raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt." ) if text is not None: a = self.tokenizer(lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ ) if visual_prompt is not None: a = self.image_processor(lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ ) if images is not None: a = self.image_processor(lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ ) if visual_prompt is not None and images is not None: a = { "pixel_values": image_features.pixel_values, "conditional_pixel_values": prompt_features.pixel_values, } return encoding elif text is not None and images is not None: a = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: a = { "conditional_pixel_values": prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**lowerCamelCase_ ) , tensor_type=lowerCamelCase_ ) def UpperCamelCase_ (self , *lowerCamelCase_ , **lowerCamelCase_ ): """simple docstring""" return self.tokenizer.batch_decode(*lowerCamelCase_ , **lowerCamelCase_ ) def UpperCamelCase_ (self , *lowerCamelCase_ , **lowerCamelCase_ ): """simple docstring""" return self.tokenizer.decode(*lowerCamelCase_ , **lowerCamelCase_ ) @property def UpperCamelCase_ (self ): """simple docstring""" warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , lowerCamelCase_ , ) return self.image_processor_class @property def UpperCamelCase_ (self ): """simple docstring""" warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , lowerCamelCase_ , ) return self.image_processor
71
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) __lowerCAmelCase = {'''configuration_beit''': ['''BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BeitConfig''', '''BeitOnnxConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = ['''BeitFeatureExtractor'''] __lowerCAmelCase = ['''BeitImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''BEIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BeitForImageClassification''', '''BeitForMaskedImageModeling''', '''BeitForSemanticSegmentation''', '''BeitModel''', '''BeitPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''FlaxBeitForImageClassification''', '''FlaxBeitForMaskedImageModeling''', '''FlaxBeitModel''', '''FlaxBeitPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
from heapq import heappop, heappush import numpy as np def _SCREAMING_SNAKE_CASE ( a , a , a , a , ) -> tuple[float | int, list[tuple[int, int]]]: __A , __A : int = grid.shape __A : Any = [-1, 1, 0, 0] __A : Optional[Any] = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __A , __A : Optional[int] = [(0, source)], set() __A : Any = np.full((rows, cols) , np.inf ) __A : Any = 0 __A : Any = np.empty((rows, cols) , dtype=a ) __A : Optional[Any] = None while queue: ((__A) , (__A)) : List[str] = heappop(a ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __A : int = [] while (x, y) != source: path.append((x, y) ) __A , __A : Optional[int] = predecessors[x, y] path.append(a ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(a ) ): __A , __A : Union[str, Any] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __A : Optional[int] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(a , (dist + 1, (nx, ny)) ) __A : List[Any] = dist + 1 __A : Union[str, Any] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
280
0
import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType UpperCamelCase , UpperCamelCase , UpperCamelCase = False, False, False @dataclass class _lowerCamelCase : """simple docstring""" snake_case = None snake_case = True snake_case = True snake_case = None # Automatically constructed snake_case = "dict" snake_case = pa.struct({"bytes": pa.binary(), "path": pa.string()} ) snake_case = field(default="Audio" , init=UpperCamelCase , repr=UpperCamelCase ) def __call__( self )->str: '''simple docstring''' return self.pa_type def _snake_case ( self , _SCREAMING_SNAKE_CASE )->dict: '''simple docstring''' try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError('''To support encoding audio data, please install \'soundfile\'.''' ) from err if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {"bytes": None, "path": value} elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes A_ : int = BytesIO() sf.write(_SCREAMING_SNAKE_CASE , value['''array'''] , value['''sampling_rate'''] , format='''wav''' ) return {"bytes": buffer.getvalue(), "path": None} elif value.get('''path''' ) is not None and os.path.isfile(value['''path'''] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith('''pcm''' ): # "PCM" only has raw audio bytes if value.get('''sampling_rate''' ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError('''To use PCM files, please specify a \'sampling_rate\' in Audio object''' ) if value.get('''bytes''' ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) A_ : Dict = np.frombuffer(value['''bytes'''] , dtype=np.intaa ).astype(np.floataa ) / 3_2767 else: A_ : Any = np.memmap(value['''path'''] , dtype='''h''' , mode='''r''' ).astype(np.floataa ) / 3_2767 A_ : Union[str, Any] = BytesIO(bytes() ) sf.write(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , value['''sampling_rate'''] , format='''wav''' ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get('''path''' )} elif value.get('''bytes''' ) is not None or value.get('''path''' ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get('''bytes''' ), "path": value.get('''path''' )} else: raise ValueError( F'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )->dict: '''simple docstring''' if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Audio(decode=True) instead.''' ) A_ , A_ : Optional[int] = (value['''path'''], BytesIO(value['''bytes'''] )) if value['''bytes'''] is not None else (value['''path'''], None) if path is None and file is None: raise ValueError(F'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError('''To support decoding audio files, please install \'librosa\' and \'soundfile\'.''' ) from err A_ : Union[str, Any] = xsplitext(_SCREAMING_SNAKE_CASE )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( '''Decoding \'opus\' files requires system library \'libsndfile\'>=1.0.31, ''' '''You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ''' ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( '''Decoding \'mp3\' files requires system library \'libsndfile\'>=1.1.0, ''' '''You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ''' ) if file is None: A_ : Optional[Any] = token_per_repo_id or {} A_ : int = path.split('''::''' )[-1] try: A_ : Tuple = string_to_dict(_SCREAMING_SNAKE_CASE , config.HUB_DATASETS_URL )['''repo_id'''] A_ : int = token_per_repo_id[repo_id] except (ValueError, KeyError): A_ : int = None with xopen(_SCREAMING_SNAKE_CASE , '''rb''' , use_auth_token=_SCREAMING_SNAKE_CASE ) as f: A_ , A_ : Any = sf.read(_SCREAMING_SNAKE_CASE ) else: A_ , A_ : Optional[int] = sf.read(_SCREAMING_SNAKE_CASE ) A_ : Optional[int] = array.T if self.mono: A_ : int = librosa.to_mono(_SCREAMING_SNAKE_CASE ) if self.sampling_rate and self.sampling_rate != sampling_rate: A_ : List[Any] = librosa.resample(_SCREAMING_SNAKE_CASE , orig_sr=_SCREAMING_SNAKE_CASE , target_sr=self.sampling_rate ) A_ : List[str] = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def _snake_case ( self )->Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value if self.decode: raise ValueError('''Cannot flatten a decoded Audio feature.''' ) return { "bytes": Value('''binary''' ), "path": Value('''string''' ), } def _snake_case ( self , _SCREAMING_SNAKE_CASE )->pa.StructArray: '''simple docstring''' if pa.types.is_string(storage.type ): A_ : Optional[Any] = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.binary() ) A_ : str = pa.StructArray.from_arrays([bytes_array, storage] , ['''bytes''', '''path'''] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): A_ : int = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() ) A_ : Optional[Any] = pa.StructArray.from_arrays([storage, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices('''array''' ): A_ : List[str] = pa.array([Audio().encode_example(_SCREAMING_SNAKE_CASE ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index('''bytes''' ) >= 0: A_ : List[str] = storage.field('''bytes''' ) else: A_ : Optional[int] = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.binary() ) if storage.type.get_field_index('''path''' ) >= 0: A_ : List[str] = storage.field('''path''' ) else: A_ : Optional[int] = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() ) A_ : int = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() ) return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )->pa.StructArray: '''simple docstring''' @no_op_if_value_is_null def path_to_bytes(_SCREAMING_SNAKE_CASE ): with xopen(_SCREAMING_SNAKE_CASE , '''rb''' ) as f: A_ : str = f.read() return bytes_ A_ : Dict = pa.array( [ (path_to_bytes(x['''path'''] ) if x['''bytes'''] is None else x['''bytes''']) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) A_ : Union[str, Any] = pa.array( [os.path.basename(_SCREAMING_SNAKE_CASE ) if path is not None else None for path in storage.field('''path''' ).to_pylist()] , type=pa.string() , ) A_ : Tuple = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null() ) return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type )
65
from manim import * class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" def _snake_case ( self )->Tuple: '''simple docstring''' A_ : Optional[int] = Rectangle(height=0.5 , width=0.5 ) A_ : Union[str, Any] = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) A_ : Any = [mem.copy() for i in range(6 )] A_ : Tuple = [mem.copy() for i in range(6 )] A_ : str = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) A_ : Union[str, Any] = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) A_ : Union[str, Any] = VGroup(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) A_ : Optional[Any] = Text('''CPU''' , font_size=24 ) A_ : Union[str, Any] = Group(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=_SCREAMING_SNAKE_CASE ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_SCREAMING_SNAKE_CASE ) A_ : Optional[int] = [mem.copy() for i in range(1 )] A_ : Any = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) A_ : Dict = Text('''GPU''' , font_size=24 ) A_ : List[str] = Group(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=_SCREAMING_SNAKE_CASE ) gpu.align_to(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) gpu.set_x(gpu.get_x() - 1 ) self.add(_SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = [mem.copy() for i in range(6 )] A_ : List[str] = VGroup(*_SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0 ) A_ : Union[str, Any] = Text('''Model''' , font_size=24 ) A_ : List[Any] = Group(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).arrange(_SCREAMING_SNAKE_CASE , buff=0.5 , aligned_edge=_SCREAMING_SNAKE_CASE ) model.move_to([3, -1.0, 0] ) self.play( Create(_SCREAMING_SNAKE_CASE , run_time=1 ) , Create(_SCREAMING_SNAKE_CASE , run_time=1 ) , Create(_SCREAMING_SNAKE_CASE , run_time=1 ) , ) A_ : int = MarkupText( F'''First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.''' , font_size=24 , ) A_ : Union[str, Any] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) A_ : Any = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(_SCREAMING_SNAKE_CASE , run_time=2.5 ) , Write(_SCREAMING_SNAKE_CASE ) , Write(_SCREAMING_SNAKE_CASE ) ) self.add(_SCREAMING_SNAKE_CASE ) A_ : Dict = [] A_ : int = [] A_ : Optional[Any] = [] for i, rect in enumerate(_SCREAMING_SNAKE_CASE ): A_ : Union[str, Any] = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0.0 ).set_fill(_SCREAMING_SNAKE_CASE , opacity=0.7 ) cpu_target.move_to(_SCREAMING_SNAKE_CASE ) cpu_target.generate_target() A_ : Union[str, Any] = 0.4_6 / 4 A_ : Any = 0.4_6 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.0_2 , direction=_SCREAMING_SNAKE_CASE ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=_SCREAMING_SNAKE_CASE , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=_SCREAMING_SNAKE_CASE , buff=0.0 ) cpu_targs.append(_SCREAMING_SNAKE_CASE ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(_SCREAMING_SNAKE_CASE ) ) second_animations.append(MoveToTarget(_SCREAMING_SNAKE_CASE , run_time=1.5 ) ) self.play(*_SCREAMING_SNAKE_CASE ) self.play(*_SCREAMING_SNAKE_CASE ) self.wait()
65
1
'''simple docstring''' import random def _A ( A__ , A__ , A__ ): """simple docstring""" __lowercase = a[left_index] __lowercase = left_index + 1 for j in range(left_index + 1 , A__ ): if a[j] < pivot: __lowercase , __lowercase = a[i], a[j] i += 1 __lowercase , __lowercase = a[i - 1], a[left_index] return i - 1 def _A ( A__ , A__ , A__ ): """simple docstring""" if left < right: __lowercase = random.randint(A__ , right - 1 ) __lowercase , __lowercase = ( a[left], a[pivot], ) # switches the pivot with the left most bound __lowercase = partition(A__ , A__ , A__ ) quick_sort_random( A__ , A__ , A__ ) # recursive quicksort to the left of the pivot point quick_sort_random( A__ , pivot_index + 1 , A__ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" __lowercase = input('''Enter numbers separated by a comma:\n''' ).strip() __lowercase = [int(A__ ) for item in user_input.split(''',''' )] quick_sort_random(A__ , 0 , len(A__ ) ) print(A__ ) if __name__ == "__main__": main()
104
'''simple docstring''' import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class A ( __UpperCAmelCase ): lowerCamelCase : Union[str, Any] = """MCTCTFeatureExtractor""" lowerCamelCase : Dict = """AutoTokenizer""" def __init__( self , lowerCamelCase__ , lowerCamelCase__ ) -> Any: '''simple docstring''' super().__init__(lowerCamelCase__ , lowerCamelCase__ ) lowercase__ = self.feature_extractor lowercase__ = False def __call__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*lowerCamelCase__ , **lowerCamelCase__ ) if "raw_speech" in kwargs: warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" ) lowercase__ = kwargs.pop("""raw_speech""" ) else: lowercase__ = kwargs.pop("""audio""" , lowerCamelCase__ ) lowercase__ = kwargs.pop("""sampling_rate""" , lowerCamelCase__ ) lowercase__ = kwargs.pop("""text""" , lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: lowercase__ = args[0] lowercase__ = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: lowercase__ = self.feature_extractor(lowerCamelCase__ , *lowerCamelCase__ , sampling_rate=lowerCamelCase__ , **lowerCamelCase__ ) if text is not None: lowercase__ = self.tokenizer(lowerCamelCase__ , **lowerCamelCase__ ) if text is None: return inputs elif audio is None: return encodings else: lowercase__ = encodings["""input_ids"""] return inputs def A__ ( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> int: '''simple docstring''' return self.tokenizer.batch_decode(*lowerCamelCase__ , **lowerCamelCase__ ) def A__ ( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Dict: '''simple docstring''' if self._in_target_context_manager: return self.current_processor.pad(*lowerCamelCase__ , **lowerCamelCase__ ) lowercase__ = kwargs.pop("""input_features""" , lowerCamelCase__ ) lowercase__ = kwargs.pop("""labels""" , lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: lowercase__ = args[0] lowercase__ = args[1:] if input_features is not None: lowercase__ = self.feature_extractor.pad(lowerCamelCase__ , *lowerCamelCase__ , **lowerCamelCase__ ) if labels is not None: lowercase__ = self.tokenizer.pad(lowerCamelCase__ , **lowerCamelCase__ ) if labels is None: return input_features elif input_features is None: return labels else: lowercase__ = labels["""input_ids"""] return input_features def A__ ( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' return self.tokenizer.decode(*lowerCamelCase__ , **lowerCamelCase__ ) @contextmanager def A__ ( self ) -> Any: '''simple docstring''' warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your audio inputs, or in a separate call.""" ) lowercase__ = True lowercase__ = self.tokenizer yield lowercase__ = self.feature_extractor lowercase__ = False
164
0
from typing import Union import fire import torch from tqdm import tqdm def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str = "cpu" , __lowerCAmelCase : Union[str, None] = None ) -> None: """simple docstring""" __lowerCamelCase = torch.load(UpperCAmelCase_ , map_location=UpperCAmelCase_ ) for k, v in tqdm(state_dict.items() ): if not isinstance(UpperCAmelCase_ , torch.Tensor ): raise TypeError('''FP16 conversion only works on paths that are saved state dicts, like pytorch_model.bin''' ) __lowerCamelCase = v.half() if save_path is None: # overwrite src_path __lowerCamelCase = src_path torch.save(UpperCAmelCase_ , UpperCAmelCase_ ) if __name__ == "__main__": fire.Fire(convert)
357
from functools import lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> set: __lowerCamelCase = 2 __lowerCamelCase = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(__lowerCAmelCase ) if n > 1: factors.add(__lowerCAmelCase ) return factors @lru_cache def __magic_name__ ( __lowerCAmelCase : int ) -> int: return len(unique_prime_factors(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : list ) -> bool: return len(set(__lowerCAmelCase ) ) in (0, 1) def __magic_name__ ( __lowerCAmelCase : int ) -> list: __lowerCamelCase = 2 while True: # Increment each value of a generated range __lowerCamelCase = [base + i for i in range(__lowerCAmelCase )] # Run elements through out unique_prime_factors function # Append our target number to the end. __lowerCamelCase = [upf_len(__lowerCAmelCase ) for x in group] checker.append(__lowerCAmelCase ) # If all numbers in the list are equal, return the group variable. if equality(__lowerCAmelCase ): return group # Increment our base variable by 1 base += 1 def __magic_name__ ( __lowerCAmelCase : int = 4 ) -> int: __lowerCamelCase = run(__lowerCAmelCase ) return results[0] if len(__lowerCAmelCase ) else None if __name__ == "__main__": print(solution())
339
0
'''simple docstring''' def _A (lowerCAmelCase__ :int ) -> str: '''simple docstring''' if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError('\'float\' object cannot be interpreted as an integer' ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError('\'str\' object cannot be interpreted as an integer' ) if num == 0: return "0b0" _a = False if num < 0: _a = True _a = -num _a = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase__ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase__ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
168
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a_ : Union[str, Any] = { "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: a_ : Tuple = ["LayoutLMv3TokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : str = [ "LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST", "LayoutLMv3ForQuestionAnswering", "LayoutLMv3ForSequenceClassification", "LayoutLMv3ForTokenClassification", "LayoutLMv3Model", "LayoutLMv3PreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Any = [ "TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLayoutLMv3ForQuestionAnswering", "TFLayoutLMv3ForSequenceClassification", "TFLayoutLMv3ForTokenClassification", "TFLayoutLMv3Model", "TFLayoutLMv3PreTrainedModel", ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Any = ["LayoutLMv3FeatureExtractor"] a_ : List[str] = ["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 a_ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
168
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor A__ : Any = logging.get_logger(__name__) class lowercase__ ( A__ ): def __init__( self : Union[str, Any] , *snake_case__ : Dict , **snake_case__ : Union[str, Any] ): warnings.warn( "The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DonutImageProcessor instead." , __A , ) super().__init__(*__A , **__A )
351
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule A__ : Tuple = {'tokenization_byt5': ['ByT5Tokenizer']} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys A__ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
209
0
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) def _snake_case( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any]=False ) -> List[Any]: '''simple docstring''' A__ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'blocks.{i}.norm1.weight', f'vit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'blocks.{i}.norm1.bias', f'vit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((f'blocks.{i}.attn.proj.weight', f'vit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((f'blocks.{i}.attn.proj.bias', f'vit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'blocks.{i}.norm2.weight', f'vit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'blocks.{i}.norm2.bias', f'vit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc1.weight', f'vit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc1.bias', f'vit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc2.weight', f'vit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc2.bias', f'vit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ('cls_token', 'vit.embeddings.cls_token'), ('patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'), ('patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'), ('pos_embed', 'vit.embeddings.position_embeddings'), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ('pre_logits.fc.weight', 'pooler.dense.weight'), ('pre_logits.fc.bias', 'pooler.dense.bias'), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" A__ = [(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 _snake_case( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> Optional[int]: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: A__ = '' else: A__ = 'vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ = state_dict.pop(f'blocks.{i}.attn.qkv.weight' ) A__ = state_dict.pop(f'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ = in_proj_weight[ : config.hidden_size, : ] A__ = in_proj_bias[: config.hidden_size] A__ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ = in_proj_weight[ -config.hidden_size :, : ] A__ = in_proj_bias[-config.hidden_size :] def _snake_case( SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: '''simple docstring''' A__ = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _snake_case( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[int]: '''simple docstring''' A__ = dct.pop(SCREAMING_SNAKE_CASE__ ) A__ = val def _snake_case( ) -> Any: '''simple docstring''' A__ = 'http://images.cocodataset.org/val2017/000000039769.jpg' A__ = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ) return im @torch.no_grad() def _snake_case( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int ) -> Dict: '''simple docstring''' A__ = ViTConfig() A__ = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": A__ = True A__ = int(vit_name[-12:-10] ) A__ = int(vit_name[-9:-6] ) else: A__ = 1000 A__ = 'huggingface/label-files' A__ = 'imagenet-1k-id2label.json' A__ = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) , 'r' ) ) A__ = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} A__ = idalabel A__ = {v: k for k, v in idalabel.items()} A__ = int(vit_name[-6:-4] ) A__ = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith('tiny' ): A__ = 192 A__ = 768 A__ = 12 A__ = 3 elif vit_name[9:].startswith('small' ): A__ = 384 A__ = 1536 A__ = 12 A__ = 6 else: pass else: if vit_name[4:].startswith('small' ): A__ = 768 A__ = 2304 A__ = 8 A__ = 8 elif vit_name[4:].startswith('base' ): pass elif vit_name[4:].startswith('large' ): A__ = 1024 A__ = 4096 A__ = 24 A__ = 16 elif vit_name[4:].startswith('huge' ): A__ = 1280 A__ = 5120 A__ = 32 A__ = 16 # load original model from timm A__ = timm.create_model(SCREAMING_SNAKE_CASE__ , pretrained=SCREAMING_SNAKE_CASE__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys A__ = timm_model.state_dict() if base_model: remove_classification_head_(SCREAMING_SNAKE_CASE__ ) A__ = create_rename_keys(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) read_in_q_k_v(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # load HuggingFace model if vit_name[-5:] == "in21k": A__ = ViTModel(SCREAMING_SNAKE_CASE__ ).eval() else: A__ = ViTForImageClassification(SCREAMING_SNAKE_CASE__ ).eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: A__ = DeiTImageProcessor(size=config.image_size ) else: A__ = ViTImageProcessor(size=config.image_size ) A__ = image_processor(images=prepare_img() , return_tensors='pt' ) A__ = encoding['pixel_values'] A__ = model(SCREAMING_SNAKE_CASE__ ) if base_model: A__ = timm_model.forward_features(SCREAMING_SNAKE_CASE__ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(SCREAMING_SNAKE_CASE__ , outputs.pooler_output , atol=1E-3 ) else: A__ = timm_model(SCREAMING_SNAKE_CASE__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(SCREAMING_SNAKE_CASE__ , outputs.logits , atol=1E-3 ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(f'Saving model {vit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_patch16_224", type=str, help="Name of the ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) lowercase_ = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
7
from __future__ import annotations from PIL import Image # Define glider example __lowercase = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [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], ] # Define blinker example __lowercase = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :int = [] for i in range(len(SCREAMING_SNAKE_CASE ) ): __UpperCamelCase :Dict = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours __UpperCamelCase :List[str] = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(SCREAMING_SNAKE_CASE ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(SCREAMING_SNAKE_CASE ) - 1: neighbour_count += cells[i + 1][j] if i < len(SCREAMING_SNAKE_CASE ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. __UpperCamelCase :List[str] = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(SCREAMING_SNAKE_CASE ) return next_generation def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :Optional[Any] = [] for _ in range(SCREAMING_SNAKE_CASE ): # Create output image __UpperCamelCase :Dict = Image.new('''RGB''' , (len(cells[0] ), len(SCREAMING_SNAKE_CASE )) ) __UpperCamelCase :Any = img.load() # Save cells to image for x in range(len(SCREAMING_SNAKE_CASE ) ): for y in range(len(cells[0] ) ): __UpperCamelCase :Optional[Any] = 255 - cells[y][x] * 255 __UpperCamelCase :int = (colour, colour, colour) # Save image images.append(SCREAMING_SNAKE_CASE ) __UpperCamelCase :Optional[int] = new_generation(SCREAMING_SNAKE_CASE ) return images if __name__ == "__main__": __lowercase = generate_images(GLIDER, 16) images[0].save('''out.gif''', save_all=True, append_images=images[1:])
43
0
'''simple docstring''' import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.configuration_bert import BertConfig from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 __a = get_tests_dir('fixtures/dummy-config.json') class A__ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : int ) -> Dict: """simple docstring""" _UpperCAmelCase : List[str] = 0 def _lowerCAmelCase ( self : Tuple ) -> Optional[int]: """simple docstring""" self.assertIsNotNone(transformers.models.auto.__spec__ ) self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto" ) ) def _lowerCAmelCase ( self : List[Any] ) -> Any: """simple docstring""" _UpperCAmelCase : Dict = AutoConfig.from_pretrained("bert-base-uncased" ) self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowerCAmelCase ( self : str ) -> Dict: """simple docstring""" _UpperCAmelCase : Tuple = AutoConfig.from_pretrained(lowerCAmelCase__ ) self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowerCAmelCase ( self : Optional[int] ) -> str: """simple docstring""" _UpperCAmelCase : Union[str, Any] = AutoConfig.from_pretrained(lowerCAmelCase__ ) self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowerCAmelCase ( self : Union[str, Any] ) -> str: """simple docstring""" _UpperCAmelCase : List[str] = AutoConfig.for_model("roberta" ) self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ ) def _lowerCAmelCase ( self : List[Any] ) -> Optional[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: # This model name contains bert and roberta, but roberta ends up being picked. _UpperCAmelCase : Optional[int] = os.path.join(lowerCAmelCase__ , "fake-roberta" ) os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) with open(os.path.join(lowerCAmelCase__ , "config.json" ) , "w" ) as f: f.write(json.dumps({} ) ) _UpperCAmelCase : Tuple = AutoConfig.from_pretrained(lowerCAmelCase__ ) self.assertEqual(type(lowerCAmelCase__ ) , lowerCAmelCase__ ) def _lowerCAmelCase ( self : List[str] ) -> Any: """simple docstring""" try: AutoConfig.register("custom" , lowerCAmelCase__ ) # Wrong model type will raise an error with self.assertRaises(lowerCAmelCase__ ): AutoConfig.register("model" , lowerCAmelCase__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCAmelCase__ ): AutoConfig.register("bert" , lowerCAmelCase__ ) # Now that the config is registered, it can be used as any other config with the auto-API _UpperCAmelCase : Any = CustomConfig() with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCAmelCase__ ) _UpperCAmelCase : Any = AutoConfig.from_pretrained(lowerCAmelCase__ ) self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] def _lowerCAmelCase ( self : int ) -> str: """simple docstring""" with self.assertRaisesRegex( lowerCAmelCase__ , "bert-base is not a local folder and is not a valid model identifier" ): _UpperCAmelCase : str = AutoConfig.from_pretrained("bert-base" ) def _lowerCAmelCase ( self : List[Any] ) -> Optional[int]: """simple docstring""" with self.assertRaisesRegex( lowerCAmelCase__ , R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): _UpperCAmelCase : Tuple = AutoConfig.from_pretrained(lowerCAmelCase__ , revision="aaaaaa" ) def _lowerCAmelCase ( self : Any ) -> Tuple: """simple docstring""" with self.assertRaisesRegex( lowerCAmelCase__ , "hf-internal-testing/no-config-test-repo does not appear to have a file named config.json." , ): _UpperCAmelCase : List[Any] = AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo" ) def _lowerCAmelCase ( self : Tuple ) -> Union[str, Any]: """simple docstring""" with self.assertRaises(lowerCAmelCase__ ): _UpperCAmelCase : str = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowerCAmelCase__ ): _UpperCAmelCase : Tuple = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=lowerCAmelCase__ ) _UpperCAmelCase : Optional[Any] = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=lowerCAmelCase__ ) self.assertEqual(config.__class__.__name__ , "NewModelConfig" ) # Test config can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCAmelCase__ ) _UpperCAmelCase : Dict = AutoConfig.from_pretrained(lowerCAmelCase__ , trust_remote_code=lowerCAmelCase__ ) self.assertEqual(reloaded_config.__class__.__name__ , "NewModelConfig" ) def _lowerCAmelCase ( self : Dict ) -> Any: """simple docstring""" class A__ ( UpperCamelCase ): """simple docstring""" UpperCamelCase_ : List[Any] = '''new-model''' try: AutoConfig.register("new-model" , lowerCAmelCase__ ) # If remote code is not set, the default is to use local _UpperCAmelCase : str = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" ) self.assertEqual(config.__class__.__name__ , "NewModelConfigLocal" ) # If remote code is disabled, we load the local one. _UpperCAmelCase : Union[str, Any] = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=lowerCAmelCase__ ) self.assertEqual(config.__class__.__name__ , "NewModelConfigLocal" ) # If remote is enabled, we load from the Hub _UpperCAmelCase : Optional[Any] = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=lowerCAmelCase__ ) self.assertEqual(config.__class__.__name__ , "NewModelConfig" ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"]
17
'''simple docstring''' from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def __UpperCAmelCase ( a_: int ): # A local function to see if a dot lands in the circle. def is_in_circle(a_: float, a_: float ) -> bool: _UpperCAmelCase : Optional[Any] = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle _UpperCAmelCase : str = mean( int(is_in_circle(uniform(-1.0, 1.0 ), uniform(-1.0, 1.0 ) ) ) for _ in range(a_ ) ) # The ratio of the area for circle to square is pi/4. _UpperCAmelCase : Optional[int] = proportion * 4 print(f"""The estimated value of pi is {pi_estimate}""" ) print(f"""The numpy value of pi is {pi}""" ) print(f"""The total error is {abs(pi - pi_estimate )}""" ) def __UpperCAmelCase ( a_: int, a_: Callable[[float], float], a_: float = 0.0, a_: float = 1.0, ): return mean( function_to_integrate(uniform(a_, a_ ) ) for _ in range(a_ ) ) * (max_value - min_value) def __UpperCAmelCase ( a_: int, a_: float = 0.0, a_: float = 1.0 ): def identity_function(a_: float ) -> float: return x _UpperCAmelCase : Union[str, Any] = area_under_curve_estimator( a_, a_, a_, a_ ) _UpperCAmelCase : List[str] = (max_value * max_value - min_value * min_value) / 2 print("******************" ) print(f"""Estimating area under y=x where x varies from {min_value} to {max_value}""" ) print(f"""Estimated value is {estimated_value}""" ) print(f"""Expected value is {expected_value}""" ) print(f"""Total error is {abs(estimated_value - expected_value )}""" ) print("******************" ) def __UpperCAmelCase ( a_: int ): def function_to_integrate(a_: float ) -> float: return sqrt(4.0 - x * x ) _UpperCAmelCase : List[str] = area_under_curve_estimator( a_, a_, 0.0, 2.0 ) print("******************" ) print("Estimating pi using area_under_curve_estimator" ) print(f"""Estimated value is {estimated_value}""" ) print(f"""Expected value is {pi}""" ) print(f"""Total error is {abs(estimated_value - pi )}""" ) print("******************" ) if __name__ == "__main__": import doctest doctest.testmod()
17
1
'''simple docstring''' import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> str: snake_case__ : Optional[int] = old_name if "patch_embed" in old_name: snake_case__ , snake_case__ , snake_case__ : Optional[int] = old_name.split(""".""" ) if layer == "0": snake_case__ : List[Any] = old_name.replace("""0""" , """convolution1""" ) elif layer == "1": snake_case__ : Tuple = old_name.replace("""1""" , """batchnorm_before""" ) elif layer == "3": snake_case__ : Dict = old_name.replace("""3""" , """convolution2""" ) else: snake_case__ : Optional[int] = old_name.replace("""4""" , """batchnorm_after""" ) if "network" in old_name and re.search(r"""\d\.\d""" , _lowerCAmelCase ): snake_case__ : Tuple = r"""\b\d{2}\b""" if bool(re.search(_lowerCAmelCase , _lowerCAmelCase ) ): snake_case__ : Optional[Any] = re.search(r"""\d\.\d\d.""" , _lowerCAmelCase ).group() else: snake_case__ : List[Any] = re.search(r"""\d\.\d.""" , _lowerCAmelCase ).group() if int(match[0] ) < 6: snake_case__ : Optional[Any] = old_name.replace(_lowerCAmelCase , """""" ) snake_case__ : Any = trimmed_name.replace("""network""" , match[0] + """.meta4D_layers.blocks.""" + match[2:-1] ) snake_case__ : Tuple = """intermediate_stages.""" + trimmed_name else: snake_case__ : Optional[int] = old_name.replace(_lowerCAmelCase , """""" ) if int(match[2] ) < num_meta4D_last_stage: snake_case__ : Dict = trimmed_name.replace("""network""" , """meta4D_layers.blocks.""" + match[2] ) else: snake_case__ : Tuple = str(int(match[2] ) - num_meta4D_last_stage ) snake_case__ : List[str] = trimmed_name.replace("""network""" , """meta3D_layers.blocks.""" + layer_index ) if "norm1" in old_name: snake_case__ : Tuple = trimmed_name.replace("""norm1""" , """layernorm1""" ) elif "norm2" in old_name: snake_case__ : Union[str, Any] = trimmed_name.replace("""norm2""" , """layernorm2""" ) elif "fc1" in old_name: snake_case__ : Optional[int] = trimmed_name.replace("""fc1""" , """linear_in""" ) elif "fc2" in old_name: snake_case__ : Dict = trimmed_name.replace("""fc2""" , """linear_out""" ) snake_case__ : Any = """last_stage.""" + trimmed_name elif "network" in old_name and re.search(r""".\d.""" , _lowerCAmelCase ): snake_case__ : Dict = old_name.replace("""network""" , """intermediate_stages""" ) if "fc" in new_name: snake_case__ : Optional[Any] = new_name.replace("""fc""" , """convolution""" ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): snake_case__ : Optional[Any] = new_name.replace("""norm1""" , """batchnorm_before""" ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): snake_case__ : Optional[int] = new_name.replace("""norm2""" , """batchnorm_after""" ) if "proj" in new_name: snake_case__ : str = new_name.replace("""proj""" , """projection""" ) if "dist_head" in new_name: snake_case__ : Any = new_name.replace("""dist_head""" , """distillation_classifier""" ) elif "head" in new_name: snake_case__ : Any = new_name.replace("""head""" , """classifier""" ) elif "patch_embed" in new_name: snake_case__ : List[Any] = """efficientformer.""" + new_name elif new_name == "norm.weight" or new_name == "norm.bias": snake_case__ : Union[str, Any] = new_name.replace("""norm""" , """layernorm""" ) snake_case__ : int = """efficientformer.""" + new_name else: snake_case__ : Optional[int] = """efficientformer.encoder.""" + new_name return new_name def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]: for key in checkpoint.copy().keys(): snake_case__ : Dict = checkpoint.pop(_lowerCAmelCase ) snake_case__ : int = val return checkpoint def __snake_case( ) -> Any: snake_case__ : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case__ : List[str] = Image.open(requests.get(_lowerCAmelCase , stream=_lowerCAmelCase ).raw ) return image def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> str: snake_case__ : Dict = torch.load(_lowerCAmelCase , map_location="""cpu""" )["""model"""] snake_case__ : Any = EfficientFormerConfig.from_json_file(_lowerCAmelCase ) snake_case__ : Any = EfficientFormerForImageClassificationWithTeacher(_lowerCAmelCase ) snake_case__ : List[Any] = """_""".join(checkpoint_path.split("""/""" )[-1].split(""".""" )[0].split("""_""" )[:-1] ) snake_case__ : Optional[Any] = config.depths[-1] - config.num_metaad_blocks + 1 snake_case__ : Optional[int] = convert_torch_checkpoint(_lowerCAmelCase , _lowerCAmelCase ) model.load_state_dict(_lowerCAmelCase ) model.eval() snake_case__ : Any = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } # prepare image snake_case__ : List[Any] = prepare_img() snake_case__ : Dict = 256 snake_case__ : Any = 224 snake_case__ : Any = EfficientFormerImageProcessor( size={"""shortest_edge""": image_size} , crop_size={"""height""": crop_size, """width""": crop_size} , resample=pillow_resamplings["""bicubic"""] , ) snake_case__ : Tuple = processor(images=_lowerCAmelCase , return_tensors="""pt""" ).pixel_values # original processing pipeline snake_case__ : Union[str, Any] = Compose( [ Resize(_lowerCAmelCase , interpolation=pillow_resamplings["""bicubic"""] ), CenterCrop(_lowerCAmelCase ), ToTensor(), Normalize(_lowerCAmelCase , _lowerCAmelCase ), ] ) snake_case__ : Optional[int] = image_transforms(_lowerCAmelCase ).unsqueeze(0 ) assert torch.allclose(_lowerCAmelCase , _lowerCAmelCase ) snake_case__ : Any = model(_lowerCAmelCase ) snake_case__ : Union[str, Any] = outputs.logits snake_case__ : int = (1, 1_000) if "l1" in model_name: snake_case__ : List[Any] = torch.Tensor( [-0.1312, 0.4353, -1.0499, -0.5124, 0.4183, -0.6793, -1.3777, -0.0893, -0.7358, -2.4328] ) assert torch.allclose(logits[0, :10] , _lowerCAmelCase , atol=1e-3 ) assert logits.shape == expected_shape elif "l3" in model_name: snake_case__ : str = torch.Tensor( [-1.3150, -1.5456, -1.2556, -0.8496, -0.7127, -0.7897, -0.9728, -0.3052, 0.3751, -0.3127] ) assert torch.allclose(logits[0, :10] , _lowerCAmelCase , atol=1e-3 ) assert logits.shape == expected_shape elif "l7" in model_name: snake_case__ : List[str] = torch.Tensor( [-1.0283, -1.4131, -0.5644, -1.3115, -0.5785, -1.2049, -0.7528, 0.1992, -0.3822, -0.0878] ) assert logits.shape == expected_shape else: raise ValueError( f"Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7" ) # Save Checkpoints Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) model.save_pretrained(_lowerCAmelCase ) print(f"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}" ) processor.save_pretrained(_lowerCAmelCase ) print(f"Processor successfuly saved at {pytorch_dump_path}" ) if push_to_hub: print("""Pushing model to the hub...""" ) model.push_to_hub( repo_id=f"Bearnardd/{pytorch_dump_path}" , commit_message="""Add model""" , use_temp_dir=_lowerCAmelCase , ) processor.push_to_hub( repo_id=f"Bearnardd/{pytorch_dump_path}" , commit_message="""Add image processor""" , use_temp_dir=_lowerCAmelCase , ) if __name__ == "__main__": __a = argparse.ArgumentParser() # Required parameters parser.add_argument( "--pytorch_model_path", default=None, type=str, required=True, help="Path to EfficientFormer pytorch checkpoint.", ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The json file for EfficientFormer model config.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub") parser.add_argument( "--no-push_to_hub", dest="push_to_hub", action="store_false", help="Do not push model and image processor to the hub", ) parser.set_defaults(push_to_hub=True) __a = parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
35
'''simple docstring''' from manim import * class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" def A ( self : Union[str, Any] ) -> List[str]: UpperCAmelCase : Optional[Any] = Rectangle(height=0.5 , width=0.5 ) UpperCAmelCase : str = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) UpperCAmelCase : Tuple = [mem.copy() for i in range(6 )] UpperCAmelCase : Optional[int] = [mem.copy() for i in range(6 )] UpperCAmelCase : Dict = VGroup(*__snake_case ).arrange(__snake_case , buff=0 ) UpperCAmelCase : Any = VGroup(*__snake_case ).arrange(__snake_case , buff=0 ) UpperCAmelCase : Union[str, Any] = VGroup(__snake_case , __snake_case ).arrange(__snake_case , buff=0 ) UpperCAmelCase : Optional[Any] = Text('''CPU''' , font_size=24 ) UpperCAmelCase : Union[str, Any] = Group(__snake_case , __snake_case ).arrange(__snake_case , buff=0.5 , aligned_edge=__snake_case ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__snake_case ) UpperCAmelCase : Optional[Any] = [mem.copy() for i in range(4 )] UpperCAmelCase : Union[str, Any] = VGroup(*__snake_case ).arrange(__snake_case , buff=0 ) UpperCAmelCase : List[str] = Text('''GPU''' , font_size=24 ) UpperCAmelCase : Dict = Group(__snake_case , __snake_case ).arrange(__snake_case , buff=0.5 , aligned_edge=__snake_case ) gpu.move_to([-1, -1, 0] ) self.add(__snake_case ) UpperCAmelCase : int = [mem.copy() for i in range(6 )] UpperCAmelCase : Union[str, Any] = VGroup(*__snake_case ).arrange(__snake_case , buff=0 ) UpperCAmelCase : List[str] = Text('''Model''' , font_size=24 ) UpperCAmelCase : Tuple = Group(__snake_case , __snake_case ).arrange(__snake_case , buff=0.5 , aligned_edge=__snake_case ) model.move_to([3, -1.0, 0] ) self.add(__snake_case ) UpperCAmelCase : Any = [] for i, rect in enumerate(__snake_case ): rect.set_stroke(__snake_case ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) UpperCAmelCase : Dict = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__snake_case , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__snake_case ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__snake_case , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__snake_case , buff=0.0 ) self.add(__snake_case ) cpu_targs.append(__snake_case ) UpperCAmelCase : int = [mem.copy() for i in range(6 )] UpperCAmelCase : int = VGroup(*__snake_case ).arrange(__snake_case , buff=0 ) UpperCAmelCase : Any = Text('''Loaded Checkpoint''' , font_size=24 ) UpperCAmelCase : Union[str, Any] = Group(__snake_case , __snake_case ).arrange(__snake_case , aligned_edge=__snake_case , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) UpperCAmelCase : Optional[int] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) UpperCAmelCase : str = MarkupText( F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__snake_case , __snake_case ) UpperCAmelCase : Tuple = MarkupText( F"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(__snake_case , DOWN * 2.4 , aligned_edge=key_text.get_left() ) UpperCAmelCase : List[Any] = MarkupText( F"""Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__snake_case ) , Write(__snake_case ) ) self.play(Write(__snake_case , run_time=1 ) , Create(__snake_case , run_time=1 ) ) UpperCAmelCase : Tuple = [] UpperCAmelCase : int = [] for i, rect in enumerate(__snake_case ): UpperCAmelCase : Any = fill.copy().set_fill(__snake_case , opacity=0.7 ) target.move_to(__snake_case ) first_animations.append(GrowFromCenter(__snake_case , run_time=1 ) ) UpperCAmelCase : List[str] = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__snake_case , run_time=1.5 ) ) self.play(*__snake_case ) self.play(*__snake_case ) self.wait()
23
0
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
74
"""simple docstring""" def __SCREAMING_SNAKE_CASE ( A_ ): if not isinstance(A_ , A_ ): lowerCAmelCase__ : int = f'Input value of [number={number}] must be an integer' raise TypeError(A_ ) if number < 0: return False lowerCAmelCase__ : List[Any] = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
74
1
'''simple docstring''' def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ): if not isinstance(UpperCAmelCase , UpperCAmelCase ): raise ValueError('''iterations must be defined as integers''' ) if not isinstance(UpperCAmelCase , UpperCAmelCase ) or not number >= 1: raise ValueError( '''starting number must be and integer and be more than 0''' ) if not iterations >= 1: raise ValueError('''Iterations must be done more than 0 times to play FizzBuzz''' ) lowercase__ : str = '''''' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(UpperCAmelCase ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
198
'''simple docstring''' import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="""%(message)s""") def __UpperCamelCase ( UpperCAmelCase ): return input_array.reshape((input_array.size, 1) ) def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): lowercase__ : Dict = np.nan for i in range(UpperCAmelCase ): lowercase__ : Optional[Any] = features[:, labels == i] lowercase__ : Optional[Any] = data.mean(1 ) # Centralize the data of class i lowercase__ : Dict = data - column_reshape(UpperCAmelCase ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(UpperCAmelCase , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowercase__ : List[str] = np.dot(UpperCAmelCase , centered_data.T ) return covariance_sum / features.shape[1] def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): lowercase__ : Tuple = features.mean(1 ) lowercase__ : Dict = np.nan for i in range(UpperCAmelCase ): lowercase__ : List[str] = features[:, labels == i] lowercase__ : int = data.shape[1] lowercase__ : Optional[int] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(UpperCAmelCase ) - column_reshape(UpperCAmelCase ) , (column_reshape(UpperCAmelCase ) - column_reshape(UpperCAmelCase )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowercase__ : Optional[int] = device_data * np.dot( column_reshape(UpperCAmelCase ) - column_reshape(UpperCAmelCase ) , (column_reshape(UpperCAmelCase ) - column_reshape(UpperCAmelCase )).T , ) return covariance_sum / features.shape[1] def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ): # Check if the features have been loaded if features.any(): lowercase__ : Optional[Any] = features.mean(1 ) # Center the dataset lowercase__ : List[str] = features - np.reshape(UpperCAmelCase , (data_mean.size, 1) ) lowercase__ : Optional[Any] = np.dot(UpperCAmelCase , centered_data.T ) / features.shape[1] lowercase__ , lowercase__ : Tuple = np.linalg.eigh(UpperCAmelCase ) # Take all the columns in the reverse order (-1), and then takes only the first lowercase__ : str = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowercase__ : Tuple = np.dot(filtered_eigenvectors.T , UpperCAmelCase ) logging.info('''Principal Component Analysis computed''' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='''%(message)s''' , force=UpperCAmelCase ) logging.error('''Dataset empty''' ) raise AssertionError def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): assert classes > dimensions # Check if features have been already loaded if features.any: lowercase__ , lowercase__ : Any = eigh( covariance_between_classes(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) , covariance_within_classes(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) , ) lowercase__ : Optional[int] = eigenvectors[:, ::-1][:, :dimensions] lowercase__ , lowercase__ , lowercase__ : Optional[int] = np.linalg.svd(UpperCAmelCase ) lowercase__ : List[str] = svd_matrix[:, 0:dimensions] lowercase__ : str = np.dot(filtered_svd_matrix.T , UpperCAmelCase ) logging.info('''Linear Discriminant Analysis computed''' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='''%(message)s''' , force=UpperCAmelCase ) logging.error('''Dataset empty''' ) raise AssertionError def __UpperCamelCase ( ): # Create dummy dataset with 2 classes and 3 features lowercase__ : List[str] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowercase__ : Optional[Any] = np.array([0, 0, 0, 1, 1] ) lowercase__ : str = 2 lowercase__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(UpperCAmelCase ) as error_info: lowercase__ : int = linear_discriminant_analysis( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) if isinstance(UpperCAmelCase , np.ndarray ): raise AssertionError( '''Did not raise AssertionError for dimensions > classes''' ) assert error_info.type is AssertionError def __UpperCamelCase ( ): lowercase__ : Optional[int] = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowercase__ : int = 2 lowercase__ : Any = np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]] ) with pytest.raises(UpperCAmelCase ) as error_info: lowercase__ : Dict = principal_component_analysis(UpperCAmelCase , UpperCAmelCase ) if not np.allclose(UpperCAmelCase , UpperCAmelCase ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
198
1
'''simple docstring''' from typing import List import numpy as np def __lowerCAmelCase ( UpperCamelCase__ ) -> int: __lowerCamelCase = {key: len(UpperCamelCase__ ) for key, value in gen_kwargs.items() if isinstance(UpperCamelCase__ , UpperCamelCase__ )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( '''Sharding is ambiguous for this dataset: ''' + '''we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n''' + '''\n'''.join(f"""\t- key {key} has length {length}""" for key, length in lists_lengths.items() ) + '''\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, ''' + '''and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.''' ) ) __lowerCamelCase = max(lists_lengths.values() , default=0 ) return max(1 , UpperCamelCase__ ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[range]: __lowerCamelCase = [] for group_idx in range(UpperCamelCase__ ): __lowerCamelCase = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break __lowerCamelCase = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 __lowerCamelCase = range(UpperCamelCase__ , start + num_shards_to_add ) shards_indices_per_group.append(UpperCamelCase__ ) return shards_indices_per_group def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[dict]: __lowerCamelCase = _number_of_shards_in_gen_kwargs(UpperCamelCase__ ) if num_shards == 1: return [dict(UpperCamelCase__ )] else: __lowerCamelCase = _distribute_shards(num_shards=UpperCamelCase__ , max_num_jobs=UpperCamelCase__ ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(UpperCamelCase__ ) ) ] def __lowerCAmelCase ( UpperCamelCase__ ) -> dict: return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , UpperCamelCase__ ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> dict: __lowerCamelCase = {len(UpperCamelCase__ ) for value in gen_kwargs.values() if isinstance(UpperCamelCase__ , UpperCamelCase__ )} __lowerCamelCase = {} for size in list_sizes: __lowerCamelCase = list(range(UpperCamelCase__ ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes __lowerCamelCase = dict(UpperCamelCase__ ) for key, value in shuffled_kwargs.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): __lowerCamelCase = [value[i] for i in indices_per_size[len(UpperCamelCase__ )]] return shuffled_kwargs
369
'''simple docstring''' import collections import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ="▁" __UpperCAmelCase ={"vocab_file": "prophetnet.tokenizer"} __UpperCAmelCase ={ "vocab_file": { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/prophetnet.tokenizer" ), } } __UpperCAmelCase ={ "microsoft/xprophetnet-large-wiki100-cased": {"do_lower_case": False}, } __UpperCAmelCase ={ "microsoft/xprophetnet-large-wiki100-cased": 5_1_2, } def __lowerCAmelCase ( UpperCamelCase__ ) -> List[str]: __lowerCamelCase = collections.OrderedDict() with open(UpperCamelCase__ , '''r''' , encoding='''utf-8''' ) as reader: __lowerCamelCase = reader.readlines() for index, token in enumerate(UpperCamelCase__ ): __lowerCamelCase = token.rstrip('''\n''' ) __lowerCamelCase = index return vocab class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[Any] =VOCAB_FILES_NAMES lowerCamelCase : Any =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : Optional[int] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Union[str, Any] =["input_ids", "attention_mask"] def __init__( self : int , a : List[str] , a : Optional[int]="[SEP]" , a : int="[SEP]" , a : str="[SEP]" , a : List[Any]="[UNK]" , a : List[Any]="[PAD]" , a : str="[CLS]" , a : List[str]="[MASK]" , a : Optional[Dict[str, Any]] = None , **a : str , ): """simple docstring""" __lowerCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=a , eos_token=a , sep_token=a , unk_token=a , pad_token=a , cls_token=a , mask_token=a , sp_model_kwargs=self.sp_model_kwargs , **a , ) try: import sentencepiece as spm except ImportError: logger.warning( '''You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece''' ''' pip install sentencepiece''' ) raise __lowerCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(a ) ) __lowerCamelCase = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # put special tokens and [unused] tokens into the vocab __lowerCamelCase = {'''[PAD]''': 0, '''[CLS]''': 1, '''[SEP]''': 2, '''[UNK]''': 3, '''[MASK]''': 4} for i in range(10 ): __lowerCamelCase = f"""[unused{i}]""" __lowerCamelCase = 5 + i # The first "real" token "," has position 15 in the embedding vocab and position 3 in the spm vocab __lowerCamelCase = 12 __lowerCamelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} for k in self.fairseq_tokens_to_ids.keys(): self.unique_no_split_tokens.append(a ) def __getstate__( self : List[str] ): """simple docstring""" __lowerCamelCase = self.__dict__.copy() __lowerCamelCase = None return state def __setstate__( self : int , a : List[Any] ): """simple docstring""" __lowerCamelCase = d try: import sentencepiece as spm except ImportError: logger.warning( '''You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece''' ''' pip install sentencepiece''' ) raise # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __lowerCamelCase = {} __lowerCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE__ ( self : str , a : List[int] , a : Optional[List[int]] = None , a : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a , token_ids_a=a , already_has_special_tokens=a ) if token_ids_a is None: return ([0] * len(a )) + [1] return ([0] * len(a )) + [1] + ([0] * len(a )) + [1] def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" __lowerCamelCase = [self.sep_token_id] if token_ids_a is None: return len(token_ids_a + sep ) * [0] return len(token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" return len(self.sp_model ) + self.fairseq_offset def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = {self.convert_ids_to_tokens(a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : str ): """simple docstring""" return self.sp_model.encode(a , out_type=a ) def SCREAMING_SNAKE_CASE__ ( self : Dict , a : int ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __lowerCamelCase = self.sp_model.PieceToId(a ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : Union[str, Any] ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : Tuple ): """simple docstring""" __lowerCamelCase = ''''''.join(a ).replace(a , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE__ ( self : int , a : str , a : Optional[str] = None ): """simple docstring""" if not os.path.isdir(a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase = os.path.join( a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a ) elif not os.path.isfile(self.vocab_file ): with open(a , '''wb''' ) as fi: __lowerCamelCase = self.sp_model.serialized_model_proto() fi.write(a ) return (out_vocab_file,) def SCREAMING_SNAKE_CASE__ ( self : Any , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return token_ids_a + [self.sep_token_id] __lowerCamelCase = [self.sep_token_id] return token_ids_a + sep + token_ids_a + sep
237
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = { "kssteven/ibert-roberta-base": "https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json", "kssteven/ibert-roberta-large": "https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json", "kssteven/ibert-roberta-large-mnli": ( "https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json" ), } class lowerCAmelCase_ ( lowerCAmelCase ): """simple docstring""" _lowerCAmelCase : Any = """ibert""" def __init__( self , lowerCAmelCase=3_05_22 , lowerCAmelCase=7_68 , lowerCAmelCase=12 , lowerCAmelCase=12 , lowerCAmelCase=30_72 , lowerCAmelCase="gelu" , lowerCAmelCase=0.1 , lowerCAmelCase=0.1 , lowerCAmelCase=5_12 , lowerCAmelCase=2 , lowerCAmelCase=0.02 , lowerCAmelCase=1E-12 , lowerCAmelCase=1 , lowerCAmelCase=0 , lowerCAmelCase=2 , lowerCAmelCase="absolute" , lowerCAmelCase=False , lowerCAmelCase="none" , **lowerCAmelCase , ): """simple docstring""" super().__init__(pad_token_id=lowerCAmelCase , bos_token_id=lowerCAmelCase , eos_token_id=lowerCAmelCase , **lowerCAmelCase ) snake_case = vocab_size snake_case = hidden_size snake_case = num_hidden_layers snake_case = num_attention_heads snake_case = hidden_act snake_case = intermediate_size snake_case = hidden_dropout_prob snake_case = attention_probs_dropout_prob snake_case = max_position_embeddings snake_case = type_vocab_size snake_case = initializer_range snake_case = layer_norm_eps snake_case = position_embedding_type snake_case = quant_mode snake_case = force_dequant class lowerCAmelCase_ ( lowerCAmelCase ): """simple docstring""" @property def snake_case ( self ): """simple docstring""" if self.task == "multiple-choice": snake_case = {0: 'batch', 1: 'choice', 2: 'sequence'} else: snake_case = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
150
"""simple docstring""" import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all LED models at https://huggingface.co/models?filter=LED SCREAMING_SNAKE_CASE__ = { "vocab_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", }, "merges_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt", }, "tokenizer_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json", }, } SCREAMING_SNAKE_CASE__ = { "allenai/led-base-16384": 16_384, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def lowerCAmelCase__ ( ) -> int: """simple docstring""" snake_case = ( list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) ) ) snake_case = bs[:] snake_case = 0 for b in range(2**8 ): if b not in bs: bs.append(_UpperCamelCase ) cs.append(2**8 + n ) n += 1 snake_case = [chr(_UpperCamelCase ) for n in cs] return dict(zip(_UpperCamelCase , _UpperCamelCase ) ) def lowerCAmelCase__ ( _UpperCamelCase : int ) -> Union[str, Any]: """simple docstring""" snake_case = set() snake_case = word[0] for char in word[1:]: pairs.add((prev_char, char) ) snake_case = char return pairs class lowerCAmelCase_ ( lowerCAmelCase ): """simple docstring""" _lowerCAmelCase : List[str] = VOCAB_FILES_NAMES _lowerCAmelCase : Any = PRETRAINED_VOCAB_FILES_MAP _lowerCAmelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCAmelCase : Union[str, Any] = ["""input_ids""", """attention_mask"""] def __init__( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase="replace" , lowerCAmelCase="<s>" , lowerCAmelCase="</s>" , lowerCAmelCase="</s>" , lowerCAmelCase="<s>" , lowerCAmelCase="<unk>" , lowerCAmelCase="<pad>" , lowerCAmelCase="<mask>" , lowerCAmelCase=False , **lowerCAmelCase , ): """simple docstring""" snake_case = AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else bos_token snake_case = AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else eos_token snake_case = AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else sep_token snake_case = AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else cls_token snake_case = AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else unk_token snake_case = AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it snake_case = AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase , lowerCAmelCase ) else mask_token super().__init__( errors=lowerCAmelCase , bos_token=lowerCAmelCase , eos_token=lowerCAmelCase , unk_token=lowerCAmelCase , sep_token=lowerCAmelCase , cls_token=lowerCAmelCase , pad_token=lowerCAmelCase , mask_token=lowerCAmelCase , add_prefix_space=lowerCAmelCase , **lowerCAmelCase , ) with open(lowerCAmelCase , encoding='utf-8' ) as vocab_handle: snake_case = json.load(lowerCAmelCase ) snake_case = {v: k for k, v in self.encoder.items()} snake_case = errors # how to handle errors in decoding snake_case = bytes_to_unicode() snake_case = {v: k for k, v in self.byte_encoder.items()} with open(lowerCAmelCase , encoding='utf-8' ) as merges_handle: snake_case = merges_handle.read().split('\n' )[1:-1] snake_case = [tuple(merge.split() ) for merge in bpe_merges] snake_case = dict(zip(lowerCAmelCase , range(len(lowerCAmelCase ) ) ) ) snake_case = {} snake_case = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions snake_case = re.compile(R'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def snake_case ( self ): """simple docstring""" return len(self.encoder ) def snake_case ( self ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def snake_case ( self , lowerCAmelCase ): """simple docstring""" if token in self.cache: return self.cache[token] snake_case = tuple(lowerCAmelCase ) snake_case = get_pairs(lowerCAmelCase ) if not pairs: return token while True: snake_case = min(lowerCAmelCase , key=lambda lowerCAmelCase : self.bpe_ranks.get(lowerCAmelCase , float('inf' ) ) ) if bigram not in self.bpe_ranks: break snake_case ,snake_case = bigram snake_case = [] snake_case = 0 while i < len(lowerCAmelCase ): try: snake_case = word.index(lowerCAmelCase , lowerCAmelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) snake_case = j if word[i] == first and i < len(lowerCAmelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 snake_case = tuple(lowerCAmelCase ) snake_case = new_word if len(lowerCAmelCase ) == 1: break else: snake_case = get_pairs(lowerCAmelCase ) snake_case = ' '.join(lowerCAmelCase ) snake_case = word return word def snake_case ( self , lowerCAmelCase ): """simple docstring""" snake_case = [] for token in re.findall(self.pat , lowerCAmelCase ): snake_case = ''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCAmelCase ).split(' ' ) ) return bpe_tokens def snake_case ( self , lowerCAmelCase ): """simple docstring""" return self.encoder.get(lowerCAmelCase , self.encoder.get(self.unk_token ) ) def snake_case ( self , lowerCAmelCase ): """simple docstring""" return self.decoder.get(lowerCAmelCase ) def snake_case ( self , lowerCAmelCase ): """simple docstring""" snake_case = ''.join(lowerCAmelCase ) snake_case = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def snake_case ( self , lowerCAmelCase , lowerCAmelCase = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case = os.path.join( lowerCAmelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) snake_case = os.path.join( lowerCAmelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(lowerCAmelCase , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase , ensure_ascii=lowerCAmelCase ) + '\n' ) snake_case = 0 with open(lowerCAmelCase , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda lowerCAmelCase : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ' Please check that the tokenizer is not corrupted!' ) snake_case = token_index writer.write(' '.join(lowerCAmelCase ) + '\n' ) index += 1 return vocab_file, merge_file def snake_case ( self , lowerCAmelCase , lowerCAmelCase = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case = [self.cls_token_id] snake_case = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def snake_case ( self , lowerCAmelCase , lowerCAmelCase = None , lowerCAmelCase = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCAmelCase , token_ids_a=lowerCAmelCase , already_has_special_tokens=lowerCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(lowerCAmelCase )) + [1] return [1] + ([0] * len(lowerCAmelCase )) + [1, 1] + ([0] * len(lowerCAmelCase )) + [1] def snake_case ( self , lowerCAmelCase , lowerCAmelCase = None ): """simple docstring""" snake_case = [self.sep_token_id] snake_case = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def snake_case ( self , lowerCAmelCase , lowerCAmelCase=False , **lowerCAmelCase ): """simple docstring""" snake_case = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(lowerCAmelCase ) > 0 and not text[0].isspace()): snake_case = ' ' + text return (text, kwargs) def snake_case ( self , lowerCAmelCase , lowerCAmelCase = None , lowerCAmelCase = PaddingStrategy.DO_NOT_PAD , lowerCAmelCase = None , lowerCAmelCase = None , ): """simple docstring""" snake_case = super()._pad( encoded_inputs=lowerCAmelCase , max_length=lowerCAmelCase , padding_strategy=lowerCAmelCase , pad_to_multiple_of=lowerCAmelCase , return_attention_mask=lowerCAmelCase , ) # Load from model defaults if return_attention_mask is None: snake_case = 'attention_mask' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: snake_case = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. snake_case = len(encoded_inputs['global_attention_mask'] ) != len(lowerCAmelCase ) if needs_to_be_padded: snake_case = len(lowerCAmelCase ) - len(encoded_inputs['global_attention_mask'] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` snake_case = ( encoded_inputs['global_attention_mask'] + [-1] * difference ) elif self.padding_side == "left": snake_case = [-1] * difference + encoded_inputs[ 'global_attention_mask' ] else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return encoded_inputs
150
1
def _UpperCamelCase ( UpperCamelCase_ : str , UpperCamelCase_ : str ) -> bool: """simple docstring""" lowerCAmelCase__ = len(UpperCamelCase_ ) + 1 lowerCAmelCase__ = len(UpperCamelCase_ ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. lowerCAmelCase__ = [[0 for i in range(UpperCamelCase_ )] for j in range(UpperCamelCase_ )] # since string of zero length match pattern of zero length lowerCAmelCase__ = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , UpperCamelCase_ ): lowerCAmelCase__ = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , UpperCamelCase_ ): lowerCAmelCase__ = dp[0][j - 2] if pattern[j - 1] == '*' else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , UpperCamelCase_ ): for j in range(1 , UpperCamelCase_ ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": lowerCAmelCase__ = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: lowerCAmelCase__ = 1 elif pattern[j - 2] in (input_string[i - 1], "."): lowerCAmelCase__ = dp[i - 1][j] else: lowerCAmelCase__ = 0 else: lowerCAmelCase__ = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") __snake_case : List[str] = """aab""" __snake_case : Optional[Any] = """c*a*b""" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f'{input_string} matches the given pattern {pattern}') else: print(f'{input_string} does not match with the given pattern {pattern}')
122
import argparse import collections import json import os import re import string import sys import numpy as np __snake_case : Any = re.compile(R"""\b(a|an|the)\b""", re.UNICODE) __snake_case : List[Any] = None def _UpperCamelCase ( ) -> Tuple: """simple docstring""" lowerCAmelCase__ = 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 _UpperCamelCase ( UpperCamelCase_ : Dict ) -> List[str]: """simple docstring""" lowerCAmelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: lowerCAmelCase__ = bool(qa['answers']['text'] ) return qid_to_has_ans def _UpperCamelCase ( UpperCamelCase_ : List[Any] ) -> Any: """simple docstring""" def remove_articles(UpperCamelCase_ : Optional[int] ): return ARTICLES_REGEX.sub(' ' , UpperCamelCase_ ) def white_space_fix(UpperCamelCase_ : Any ): return " ".join(text.split() ) def remove_punc(UpperCamelCase_ : Union[str, Any] ): lowerCAmelCase__ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(UpperCamelCase_ : str ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(UpperCamelCase_ ) ) ) ) def _UpperCamelCase ( UpperCamelCase_ : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" if not s: return [] return normalize_answer(UpperCamelCase_ ).split() def _UpperCamelCase ( UpperCamelCase_ : int , UpperCamelCase_ : List[str] ) -> Tuple: """simple docstring""" return int(normalize_answer(UpperCamelCase_ ) == normalize_answer(UpperCamelCase_ ) ) def _UpperCamelCase ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[Any] ) -> Tuple: """simple docstring""" lowerCAmelCase__ = get_tokens(UpperCamelCase_ ) lowerCAmelCase__ = get_tokens(UpperCamelCase_ ) lowerCAmelCase__ = collections.Counter(UpperCamelCase_ ) & collections.Counter(UpperCamelCase_ ) lowerCAmelCase__ = 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 lowerCAmelCase__ = 1.0 * num_same / len(UpperCamelCase_ ) lowerCAmelCase__ = 1.0 * num_same / len(UpperCamelCase_ ) lowerCAmelCase__ = (2 * precision * recall) / (precision + recall) return fa def _UpperCamelCase ( UpperCamelCase_ : str , UpperCamelCase_ : Optional[int] ) -> List[Any]: """simple docstring""" lowerCAmelCase__ = {} lowerCAmelCase__ = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: lowerCAmelCase__ = qa['id'] lowerCAmelCase__ = [t for t in qa['answers']['text'] if normalize_answer(UpperCamelCase_ )] if not gold_answers: # For unanswerable questions, only correct answer is empty string lowerCAmelCase__ = [''] if qid not in preds: print(F"Missing prediction for {qid}" ) continue lowerCAmelCase__ = preds[qid] # Take max over all gold answers lowerCAmelCase__ = max(compute_exact(UpperCamelCase_ , UpperCamelCase_ ) for a in gold_answers ) lowerCAmelCase__ = max(compute_fa(UpperCamelCase_ , UpperCamelCase_ ) for a in gold_answers ) return exact_scores, fa_scores def _UpperCamelCase ( UpperCamelCase_ : Dict , UpperCamelCase_ : List[Any] , UpperCamelCase_ : str , UpperCamelCase_ : List[Any] ) -> str: """simple docstring""" lowerCAmelCase__ = {} for qid, s in scores.items(): lowerCAmelCase__ = na_probs[qid] > na_prob_thresh if pred_na: lowerCAmelCase__ = float(not qid_to_has_ans[qid] ) else: lowerCAmelCase__ = s return new_scores def _UpperCamelCase ( UpperCamelCase_ : List[str] , UpperCamelCase_ : Any , UpperCamelCase_ : str=None ) -> Union[str, Any]: """simple docstring""" if not qid_list: lowerCAmelCase__ = len(UpperCamelCase_ ) return collections.OrderedDict( [ ('exact', 100.0 * sum(exact_scores.values() ) / total), ('f1', 100.0 * sum(fa_scores.values() ) / total), ('total', total), ] ) else: lowerCAmelCase__ = 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 _UpperCamelCase ( UpperCamelCase_ : Dict , UpperCamelCase_ : str , UpperCamelCase_ : Tuple ) -> Tuple: """simple docstring""" for k in new_eval: lowerCAmelCase__ = new_eval[k] def _UpperCamelCase ( UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Optional[int] ) -> int: """simple docstring""" 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 _UpperCamelCase ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : int , UpperCamelCase_ : str , UpperCamelCase_ : List[str]=None , UpperCamelCase_ : Any=None ) -> List[str]: """simple docstring""" lowerCAmelCase__ = sorted(UpperCamelCase_ , key=lambda UpperCamelCase_ : na_probs[k] ) lowerCAmelCase__ = 0.0 lowerCAmelCase__ = 1.0 lowerCAmelCase__ = 0.0 lowerCAmelCase__ = [1.0] lowerCAmelCase__ = [0.0] lowerCAmelCase__ = 0.0 for i, qid in enumerate(UpperCamelCase_ ): if qid_to_has_ans[qid]: true_pos += scores[qid] lowerCAmelCase__ = true_pos / float(i + 1 ) lowerCAmelCase__ = 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 _UpperCamelCase ( UpperCamelCase_ : str , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str] , UpperCamelCase_ : str , UpperCamelCase_ : Tuple ) -> Tuple: """simple docstring""" if out_image_dir and not os.path.exists(UpperCamelCase_ ): os.makedirs(UpperCamelCase_ ) lowerCAmelCase__ = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return lowerCAmelCase__ = 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' , ) lowerCAmelCase__ = make_precision_recall_eval( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , out_image=os.path.join(UpperCamelCase_ , 'pr_f1.png' ) , title='Precision-Recall curve for F1 score' , ) lowerCAmelCase__ = {k: float(UpperCamelCase_ ) for k, v in qid_to_has_ans.items()} lowerCAmelCase__ = 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 _UpperCamelCase ( UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict , UpperCamelCase_ : Dict ) -> int: """simple docstring""" if not qid_list: return lowerCAmelCase__ = [na_probs[k] for k in qid_list] lowerCAmelCase__ = np.ones_like(UpperCamelCase_ ) / float(len(UpperCamelCase_ ) ) plt.hist(UpperCamelCase_ , weights=UpperCamelCase_ , bins=20 , 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 _UpperCamelCase ( UpperCamelCase_ : Any , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : str ) -> int: """simple docstring""" lowerCAmelCase__ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) lowerCAmelCase__ = num_no_ans lowerCAmelCase__ = cur_score lowerCAmelCase__ = 0.0 lowerCAmelCase__ = 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]: lowerCAmelCase__ = scores[qid] else: if preds[qid]: lowerCAmelCase__ = -1 else: lowerCAmelCase__ = 0 cur_score += diff if cur_score > best_score: lowerCAmelCase__ = cur_score lowerCAmelCase__ = na_probs[qid] return 100.0 * best_score / len(UpperCamelCase_ ), best_thresh def _UpperCamelCase ( UpperCamelCase_ : List[str] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : str , UpperCamelCase_ : int , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str] ) -> str: """simple docstring""" lowerCAmelCase__ , lowerCAmelCase__ = find_best_thresh(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = find_best_thresh(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = best_exact lowerCAmelCase__ = exact_thresh lowerCAmelCase__ = best_fa lowerCAmelCase__ = fa_thresh def _UpperCamelCase ( ) -> Dict: """simple docstring""" with open(OPTS.data_file ) as f: lowerCAmelCase__ = json.load(UpperCamelCase_ ) lowerCAmelCase__ = dataset_json['data'] with open(OPTS.pred_file ) as f: lowerCAmelCase__ = json.load(UpperCamelCase_ ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: lowerCAmelCase__ = json.load(UpperCamelCase_ ) else: lowerCAmelCase__ = {k: 0.0 for k in preds} lowerCAmelCase__ = make_qid_to_has_ans(UpperCamelCase_ ) # maps qid to True/False lowerCAmelCase__ = [k for k, v in qid_to_has_ans.items() if v] lowerCAmelCase__ = [k for k, v in qid_to_has_ans.items() if not v] lowerCAmelCase__ , lowerCAmelCase__ = get_raw_scores(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = apply_no_ans_threshold(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , OPTS.na_prob_thresh ) lowerCAmelCase__ = apply_no_ans_threshold(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , OPTS.na_prob_thresh ) lowerCAmelCase__ = make_eval_dict(UpperCamelCase_ , UpperCamelCase_ ) if has_ans_qids: lowerCAmelCase__ = make_eval_dict(UpperCamelCase_ , UpperCamelCase_ , qid_list=UpperCamelCase_ ) merge_eval(UpperCamelCase_ , UpperCamelCase_ , 'HasAns' ) if no_ans_qids: lowerCAmelCase__ = 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__": __snake_case : int = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("""Agg""") import matplotlib.pyplot as plt main()
122
1
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _UpperCamelCase = 637_8137.0 _UpperCamelCase = 635_6752.31_4245 _UpperCamelCase = 637_8137 def _lowercase ( lowercase__ , lowercase__ , lowercase__ , lowercase__ ): __lowerCAmelCase : Optional[int] = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude __lowerCAmelCase : Optional[Any] = atan((1 - flattening) * tan(radians(__snake_case ) ) ) __lowerCAmelCase : Optional[Any] = atan((1 - flattening) * tan(radians(__snake_case ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius __lowerCAmelCase : Optional[Any] = haversine_distance(__snake_case , __snake_case , __snake_case , __snake_case ) / EQUATORIAL_RADIUS # Intermediate P and Q values __lowerCAmelCase : List[str] = (b_lata + b_lata) / 2 __lowerCAmelCase : Optional[int] = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) __lowerCAmelCase : int = (sin(__snake_case ) ** 2) * (cos(__snake_case ) ** 2) __lowerCAmelCase : Optional[Any] = cos(sigma / 2 ) ** 2 __lowerCAmelCase : Optional[int] = (sigma - sin(__snake_case )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) __lowerCAmelCase : Union[str, Any] = (cos(__snake_case ) ** 2) * (sin(__snake_case ) ** 2) __lowerCAmelCase : Union[str, Any] = sin(sigma / 2 ) ** 2 __lowerCAmelCase : Dict = (sigma + sin(__snake_case )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
275
'''simple docstring''' import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) a_ : List[Any] = logging.get_logger(__name__) a_ : Tuple = OrderedDict( [ ("""audio-spectrogram-transformer""", """ASTFeatureExtractor"""), ("""beit""", """BeitFeatureExtractor"""), ("""chinese_clip""", """ChineseCLIPFeatureExtractor"""), ("""clap""", """ClapFeatureExtractor"""), ("""clip""", """CLIPFeatureExtractor"""), ("""clipseg""", """ViTFeatureExtractor"""), ("""conditional_detr""", """ConditionalDetrFeatureExtractor"""), ("""convnext""", """ConvNextFeatureExtractor"""), ("""cvt""", """ConvNextFeatureExtractor"""), ("""data2vec-audio""", """Wav2Vec2FeatureExtractor"""), ("""data2vec-vision""", """BeitFeatureExtractor"""), ("""deformable_detr""", """DeformableDetrFeatureExtractor"""), ("""deit""", """DeiTFeatureExtractor"""), ("""detr""", """DetrFeatureExtractor"""), ("""dinat""", """ViTFeatureExtractor"""), ("""donut-swin""", """DonutFeatureExtractor"""), ("""dpt""", """DPTFeatureExtractor"""), ("""encodec""", """EncodecFeatureExtractor"""), ("""flava""", """FlavaFeatureExtractor"""), ("""glpn""", """GLPNFeatureExtractor"""), ("""groupvit""", """CLIPFeatureExtractor"""), ("""hubert""", """Wav2Vec2FeatureExtractor"""), ("""imagegpt""", """ImageGPTFeatureExtractor"""), ("""layoutlmv2""", """LayoutLMv2FeatureExtractor"""), ("""layoutlmv3""", """LayoutLMv3FeatureExtractor"""), ("""levit""", """LevitFeatureExtractor"""), ("""maskformer""", """MaskFormerFeatureExtractor"""), ("""mctct""", """MCTCTFeatureExtractor"""), ("""mobilenet_v1""", """MobileNetV1FeatureExtractor"""), ("""mobilenet_v2""", """MobileNetV2FeatureExtractor"""), ("""mobilevit""", """MobileViTFeatureExtractor"""), ("""nat""", """ViTFeatureExtractor"""), ("""owlvit""", """OwlViTFeatureExtractor"""), ("""perceiver""", """PerceiverFeatureExtractor"""), ("""poolformer""", """PoolFormerFeatureExtractor"""), ("""regnet""", """ConvNextFeatureExtractor"""), ("""resnet""", """ConvNextFeatureExtractor"""), ("""segformer""", """SegformerFeatureExtractor"""), ("""sew""", """Wav2Vec2FeatureExtractor"""), ("""sew-d""", """Wav2Vec2FeatureExtractor"""), ("""speech_to_text""", """Speech2TextFeatureExtractor"""), ("""speecht5""", """SpeechT5FeatureExtractor"""), ("""swiftformer""", """ViTFeatureExtractor"""), ("""swin""", """ViTFeatureExtractor"""), ("""swinv2""", """ViTFeatureExtractor"""), ("""table-transformer""", """DetrFeatureExtractor"""), ("""timesformer""", """VideoMAEFeatureExtractor"""), ("""tvlt""", """TvltFeatureExtractor"""), ("""unispeech""", """Wav2Vec2FeatureExtractor"""), ("""unispeech-sat""", """Wav2Vec2FeatureExtractor"""), ("""van""", """ConvNextFeatureExtractor"""), ("""videomae""", """VideoMAEFeatureExtractor"""), ("""vilt""", """ViltFeatureExtractor"""), ("""vit""", """ViTFeatureExtractor"""), ("""vit_mae""", """ViTFeatureExtractor"""), ("""vit_msn""", """ViTFeatureExtractor"""), ("""wav2vec2""", """Wav2Vec2FeatureExtractor"""), ("""wav2vec2-conformer""", """Wav2Vec2FeatureExtractor"""), ("""wavlm""", """Wav2Vec2FeatureExtractor"""), ("""whisper""", """WhisperFeatureExtractor"""), ("""xclip""", """CLIPFeatureExtractor"""), ("""yolos""", """YolosFeatureExtractor"""), ] ) a_ : Optional[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def a_ ( __snake_case : str ) -> Any: """simple docstring""" for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: lowerCamelCase_ =model_type_to_module_name(__snake_case ) lowerCamelCase_ =importlib.import_module(F'''.{module_name}''' , '''transformers.models''' ) try: return getattr(__snake_case , __snake_case ) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(__snake_case , '''__name__''' , __snake_case ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. lowerCamelCase_ =importlib.import_module('''transformers''' ) if hasattr(__snake_case , __snake_case ): return getattr(__snake_case , __snake_case ) return None def a_ ( __snake_case : Union[str, os.PathLike] , __snake_case : Optional[Union[str, os.PathLike]] = None , __snake_case : bool = False , __snake_case : bool = False , __snake_case : Optional[Dict[str, str]] = None , __snake_case : Optional[Union[bool, str]] = None , __snake_case : Optional[str] = None , __snake_case : bool = False , **__snake_case : Union[str, Any] , ) -> List[str]: """simple docstring""" lowerCamelCase_ =get_file_from_repo( __snake_case , __snake_case , cache_dir=__snake_case , force_download=__snake_case , resume_download=__snake_case , proxies=__snake_case , use_auth_token=__snake_case , revision=__snake_case , local_files_only=__snake_case , ) if resolved_config_file is None: logger.info( '''Could not locate the feature extractor configuration file, will try to use the model config instead.''' ) return {} with open(__snake_case , encoding='''utf-8''' ) as reader: return json.load(__snake_case ) class __UpperCamelCase : def __init__( self ): """simple docstring""" raise EnvironmentError( '''AutoFeatureExtractor is designed to be instantiated ''' '''using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(lowerCAmelCase ) def lowercase__ ( cls, lowerCAmelCase, **lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =kwargs.pop('''config''', lowerCAmelCase ) lowerCamelCase_ =kwargs.pop('''trust_remote_code''', lowerCAmelCase ) lowerCamelCase_ =True lowerCamelCase_, lowerCamelCase_ =FeatureExtractionMixin.get_feature_extractor_dict(lowerCAmelCase, **lowerCAmelCase ) lowerCamelCase_ =config_dict.get('''feature_extractor_type''', lowerCAmelCase ) lowerCamelCase_ =None if "AutoFeatureExtractor" in config_dict.get('''auto_map''', {} ): lowerCamelCase_ =config_dict['''auto_map''']['''AutoFeatureExtractor'''] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(lowerCAmelCase, lowerCAmelCase ): lowerCamelCase_ =AutoConfig.from_pretrained(lowerCAmelCase, **lowerCAmelCase ) # It could be in `config.feature_extractor_type`` lowerCamelCase_ =getattr(lowerCAmelCase, '''feature_extractor_type''', lowerCAmelCase ) if hasattr(lowerCAmelCase, '''auto_map''' ) and "AutoFeatureExtractor" in config.auto_map: lowerCamelCase_ =config.auto_map['''AutoFeatureExtractor'''] if feature_extractor_class is not None: lowerCamelCase_ =feature_extractor_class_from_name(lowerCAmelCase ) lowerCamelCase_ =feature_extractor_auto_map is not None lowerCamelCase_ =feature_extractor_class is not None or type(lowerCAmelCase ) in FEATURE_EXTRACTOR_MAPPING lowerCamelCase_ =resolve_trust_remote_code( lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ) if has_remote_code and trust_remote_code: lowerCamelCase_ =get_class_from_dynamic_module( lowerCAmelCase, lowerCAmelCase, **lowerCAmelCase ) lowerCamelCase_ =kwargs.pop('''code_revision''', lowerCAmelCase ) if os.path.isdir(lowerCAmelCase ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(lowerCAmelCase, **lowerCAmelCase ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(lowerCAmelCase, **lowerCAmelCase ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(lowerCAmelCase ) in FEATURE_EXTRACTOR_MAPPING: lowerCamelCase_ =FEATURE_EXTRACTOR_MAPPING[type(lowerCAmelCase )] return feature_extractor_class.from_dict(lowerCAmelCase, **lowerCAmelCase ) raise ValueError( f'''Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a ''' f'''`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def lowercase__ ( lowerCAmelCase, lowerCAmelCase ): """simple docstring""" FEATURE_EXTRACTOR_MAPPING.register(lowerCAmelCase, lowerCAmelCase )
75
0
from math import pi, sqrt def SCREAMING_SNAKE_CASE ( __UpperCamelCase : float ) -> float: if num <= 0: raise ValueError('''math domain error''' ) if num > 171.5: raise OverflowError('''math range error''' ) elif num - int(__UpperCamelCase ) not in (0, 0.5): raise NotImplementedError('''num must be an integer or a half-integer''' ) elif num == 0.5: return sqrt(__UpperCamelCase ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def SCREAMING_SNAKE_CASE ( ) -> None: assert gamma(0.5 ) == sqrt(__UpperCamelCase ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _lowerCamelCase = 1.0 while num: _lowerCamelCase = float(input('Gamma of: ')) print(F"gamma({num}) = {gamma(num)}") print('\nEnter 0 to exit...')
364
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class a ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , __snake_case : int , __snake_case : List[Any]=7 , __snake_case : Any=3 , __snake_case : Any=18 , __snake_case : str=30 , __snake_case : Any=4_00 , __snake_case : Optional[int]=True , __snake_case : str=None , __snake_case : Any=True , __snake_case : List[Any]=None , ): UpperCAmelCase_ = size if size is not None else {'''shortest_edge''': 20} UpperCAmelCase_ = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = num_channels UpperCAmelCase_ = image_size UpperCAmelCase_ = min_resolution UpperCAmelCase_ = max_resolution UpperCAmelCase_ = do_resize UpperCAmelCase_ = size UpperCAmelCase_ = do_center_crop UpperCAmelCase_ = crop_size def lowerCamelCase_ ( self : Any ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class a ( _A , unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = MobileNetVaImageProcessor if is_vision_available() else None def lowerCamelCase_ ( self : Any ): UpperCAmelCase_ = MobileNetVaImageProcessingTester(self ) @property def lowerCamelCase_ ( self : List[str] ): return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase_ ( self : Optional[int] ): UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__snake_case , '''do_resize''' ) ) self.assertTrue(hasattr(__snake_case , '''size''' ) ) self.assertTrue(hasattr(__snake_case , '''do_center_crop''' ) ) self.assertTrue(hasattr(__snake_case , '''crop_size''' ) ) def lowerCamelCase_ ( self : Dict ): UpperCAmelCase_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) UpperCAmelCase_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def lowerCamelCase_ ( self : Optional[int] ): pass def lowerCamelCase_ ( self : Tuple ): # Initialize image_processing UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , Image.Image ) # Test not batched input UpperCAmelCase_ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched UpperCAmelCase_ = image_processing(__snake_case , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase_ ( self : str ): # Initialize image_processing UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , numpify=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , np.ndarray ) # Test not batched input UpperCAmelCase_ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched UpperCAmelCase_ = image_processing(__snake_case , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCamelCase_ ( self : int ): # Initialize image_processing UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , torchify=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , torch.Tensor ) # Test not batched input UpperCAmelCase_ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched UpperCAmelCase_ = image_processing(__snake_case , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
177
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING A__ = logging.get_logger(__name__) A__ = { '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''', } class a ( lowerCamelCase_ ): __lowerCAmelCase : Tuple = """blip_2_vision_model""" def __init__( self :List[Any] ,__lowercase :List[Any]=1_4_0_8 ,__lowercase :Optional[Any]=6_1_4_4 ,__lowercase :Optional[int]=3_9 ,__lowercase :Optional[int]=1_6 ,__lowercase :Optional[Any]=2_2_4 ,__lowercase :Tuple=1_4 ,__lowercase :Optional[Any]="gelu" ,__lowercase :Union[str, Any]=0.0_0001 ,__lowercase :Dict=0.0 ,__lowercase :Union[str, Any]=1e-1_0 ,__lowercase :int=True ,**__lowercase :str ,): super().__init__(**__lowercase ) snake_case__ : str = hidden_size snake_case__ : Tuple = intermediate_size snake_case__ : List[str] = num_hidden_layers snake_case__ : int = num_attention_heads snake_case__ : Tuple = patch_size snake_case__ : Optional[Any] = image_size snake_case__ : Optional[int] = initializer_range snake_case__ : Dict = attention_dropout snake_case__ : int = layer_norm_eps snake_case__ : Tuple = hidden_act snake_case__ : Optional[int] = qkv_bias @classmethod def __lowerCamelCase ( cls :Dict ,__lowercase :Union[str, os.PathLike] ,**__lowercase :str ): cls._set_token_in_kwargs(__lowercase ) snake_case__ , snake_case__ : int = cls.get_config_dict(__lowercase ,**__lowercase ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": snake_case__ : Any = 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(__lowercase ,**__lowercase ) class a ( lowerCamelCase_ ): __lowerCAmelCase : str = """blip_2_qformer""" def __init__( self :Any ,__lowercase :Dict=3_0_5_2_2 ,__lowercase :int=7_6_8 ,__lowercase :List[Any]=1_2 ,__lowercase :List[str]=1_2 ,__lowercase :Optional[Any]=3_0_7_2 ,__lowercase :str="gelu" ,__lowercase :Optional[Any]=0.1 ,__lowercase :Union[str, Any]=0.1 ,__lowercase :Optional[Any]=5_1_2 ,__lowercase :List[Any]=0.02 ,__lowercase :List[str]=1e-1_2 ,__lowercase :Tuple=0 ,__lowercase :Union[str, Any]="absolute" ,__lowercase :List[Any]=2 ,__lowercase :List[str]=1_4_0_8 ,**__lowercase :Optional[Any] ,): super().__init__(pad_token_id=__lowercase ,**__lowercase ) snake_case__ : Tuple = vocab_size snake_case__ : int = hidden_size snake_case__ : Dict = num_hidden_layers snake_case__ : Optional[Any] = num_attention_heads snake_case__ : int = hidden_act snake_case__ : Optional[int] = intermediate_size snake_case__ : Optional[Any] = hidden_dropout_prob snake_case__ : Dict = attention_probs_dropout_prob snake_case__ : Tuple = max_position_embeddings snake_case__ : Any = initializer_range snake_case__ : Optional[int] = layer_norm_eps snake_case__ : int = position_embedding_type snake_case__ : Optional[int] = cross_attention_frequency snake_case__ : Tuple = encoder_hidden_size @classmethod def __lowerCamelCase ( cls :List[Any] ,__lowercase :Union[str, os.PathLike] ,**__lowercase :Dict ): cls._set_token_in_kwargs(__lowercase ) snake_case__ , snake_case__ : Any = cls.get_config_dict(__lowercase ,**__lowercase ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": snake_case__ : 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(__lowercase ,**__lowercase ) class a ( lowerCamelCase_ ): __lowerCAmelCase : Tuple = """blip-2""" __lowerCAmelCase : Any = True def __init__( self :int ,__lowercase :Dict=None ,__lowercase :Tuple=None ,__lowercase :str=None ,__lowercase :Union[str, Any]=3_2 ,**__lowercase :int ): super().__init__(**__lowercase ) if vision_config is None: snake_case__ : List[Any] = {} logger.info('''vision_config is None. initializing the Blip2VisionConfig with default values.''' ) if qformer_config is None: snake_case__ : Tuple = {} logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.''' ) if text_config is None: snake_case__ : str = {} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) snake_case__ : Any = BlipaVisionConfig(**__lowercase ) snake_case__ : Optional[int] = BlipaQFormerConfig(**__lowercase ) snake_case__ : Tuple = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' snake_case__ : Union[str, Any] = CONFIG_MAPPING[text_model_type](**__lowercase ) snake_case__ : Tuple = self.text_config.tie_word_embeddings snake_case__ : List[str] = self.text_config.is_encoder_decoder snake_case__ : Any = num_query_tokens snake_case__ : Dict = self.vision_config.hidden_size snake_case__ : List[Any] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES snake_case__ : Union[str, Any] = 1.0 snake_case__ : int = 0.02 @classmethod def __lowerCamelCase ( cls :Union[str, Any] ,__lowercase :BlipaVisionConfig ,__lowercase :BlipaQFormerConfig ,__lowercase :PretrainedConfig ,**__lowercase :Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**__lowercase ,) def __lowerCamelCase ( self :Optional[Any] ): snake_case__ : str = copy.deepcopy(self.__dict__ ) snake_case__ : Optional[Any] = self.vision_config.to_dict() snake_case__ : Union[str, Any] = self.qformer_config.to_dict() snake_case__ : Any = self.text_config.to_dict() snake_case__ : Any = self.__class__.model_type return output
230
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
0
"""simple docstring""" import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class lowercase_ ( __lowerCAmelCase ): def __get__( self : int , A__ : Union[str, Any] , A__ : Union[str, Any]=None ) -> str: if obj is None: return self if self.fget is None: raise AttributeError('''unreadable attribute''' ) _snake_case = '''__cached_''' + self.fget.__name__ _snake_case = getattr(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) if cached is None: _snake_case = self.fget(lowerCamelCase__ ) setattr(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) return cached def snake_case_(_UpperCamelCase ) -> str: """simple docstring""" _snake_case = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(F"""invalid truth value {val!r}""" ) def snake_case_(_UpperCamelCase ) -> Union[str, Any]: """simple docstring""" if is_torch_fx_proxy(_UpperCamelCase ): return True if is_torch_available(): import torch if isinstance(_UpperCamelCase , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(_UpperCamelCase , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(_UpperCamelCase , (jnp.ndarray, Tracer) ): return True return isinstance(_UpperCamelCase , np.ndarray ) def snake_case_(_UpperCamelCase ) -> Optional[Any]: """simple docstring""" return isinstance(_UpperCamelCase , np.ndarray ) def snake_case_(_UpperCamelCase ) -> int: """simple docstring""" return _is_numpy(_UpperCamelCase ) def snake_case_(_UpperCamelCase ) -> Optional[Any]: """simple docstring""" import torch return isinstance(_UpperCamelCase , torch.Tensor ) def snake_case_(_UpperCamelCase ) -> Any: """simple docstring""" return False if not is_torch_available() else _is_torch(_UpperCamelCase ) def snake_case_(_UpperCamelCase ) -> Tuple: """simple docstring""" import torch return isinstance(_UpperCamelCase , torch.device ) def snake_case_(_UpperCamelCase ) -> Union[str, Any]: """simple docstring""" return False if not is_torch_available() else _is_torch_device(_UpperCamelCase ) def snake_case_(_UpperCamelCase ) -> int: """simple docstring""" import torch if isinstance(_UpperCamelCase , _UpperCamelCase ): if hasattr(_UpperCamelCase , _UpperCamelCase ): _snake_case = getattr(_UpperCamelCase , _UpperCamelCase ) else: return False return isinstance(_UpperCamelCase , torch.dtype ) def snake_case_(_UpperCamelCase ) -> str: """simple docstring""" return False if not is_torch_available() else _is_torch_dtype(_UpperCamelCase ) def snake_case_(_UpperCamelCase ) -> List[Any]: """simple docstring""" import tensorflow as tf return isinstance(_UpperCamelCase , tf.Tensor ) def snake_case_(_UpperCamelCase ) -> str: """simple docstring""" return False if not is_tf_available() else _is_tensorflow(_UpperCamelCase ) def snake_case_(_UpperCamelCase ) -> int: """simple docstring""" import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(_UpperCamelCase , '''is_symbolic_tensor''' ): return tf.is_symbolic_tensor(_UpperCamelCase ) return type(_UpperCamelCase ) == tf.Tensor def snake_case_(_UpperCamelCase ) -> Optional[Any]: """simple docstring""" return False if not is_tf_available() else _is_tf_symbolic_tensor(_UpperCamelCase ) def snake_case_(_UpperCamelCase ) -> Tuple: """simple docstring""" import jax.numpy as jnp # noqa: F811 return isinstance(_UpperCamelCase , jnp.ndarray ) def snake_case_(_UpperCamelCase ) -> Union[str, Any]: """simple docstring""" return False if not is_flax_available() else _is_jax(_UpperCamelCase ) def snake_case_(_UpperCamelCase ) -> List[str]: """simple docstring""" if isinstance(_UpperCamelCase , (dict, UserDict) ): return {k: to_py_obj(_UpperCamelCase ) for k, v in obj.items()} elif isinstance(_UpperCamelCase , (list, tuple) ): return [to_py_obj(_UpperCamelCase ) for o in obj] elif is_tf_tensor(_UpperCamelCase ): return obj.numpy().tolist() elif is_torch_tensor(_UpperCamelCase ): return obj.detach().cpu().tolist() elif is_jax_tensor(_UpperCamelCase ): return np.asarray(_UpperCamelCase ).tolist() elif isinstance(_UpperCamelCase , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def snake_case_(_UpperCamelCase ) -> Tuple: """simple docstring""" if isinstance(_UpperCamelCase , (dict, UserDict) ): return {k: to_numpy(_UpperCamelCase ) for k, v in obj.items()} elif isinstance(_UpperCamelCase , (list, tuple) ): return np.array(_UpperCamelCase ) elif is_tf_tensor(_UpperCamelCase ): return obj.numpy() elif is_torch_tensor(_UpperCamelCase ): return obj.detach().cpu().numpy() elif is_jax_tensor(_UpperCamelCase ): return np.asarray(_UpperCamelCase ) else: return obj class lowercase_ ( __lowerCAmelCase ): def UpperCamelCase_ ( self : List[Any] ) -> Dict: _snake_case = fields(self ) # Safety and consistency checks if not len(lowerCamelCase__ ): raise ValueError(f"""{self.__class__.__name__} has no fields.""" ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(f"""{self.__class__.__name__} should not have more than one required field.""" ) _snake_case = getattr(self , class_fields[0].name ) _snake_case = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(lowerCamelCase__ ): if isinstance(lowerCamelCase__ , lowerCamelCase__ ): _snake_case = first_field.items() _snake_case = True else: try: _snake_case = iter(lowerCamelCase__ ) _snake_case = True except TypeError: _snake_case = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(lowerCamelCase__ ): if ( not isinstance(lowerCamelCase__ , (list, tuple) ) or not len(lowerCamelCase__ ) == 2 or not isinstance(element[0] , lowerCamelCase__ ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute _snake_case = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f"""Cannot set key/value for {element}. It needs to be a tuple (key, value).""" ) break setattr(self , element[0] , element[1] ) if element[1] is not None: _snake_case = element[1] elif first_field is not None: _snake_case = first_field else: for field in class_fields: _snake_case = getattr(self , field.name ) if v is not None: _snake_case = v def __delitem__( self : Optional[int] , *A__ : str , **A__ : Optional[int] ) -> str: raise Exception(f"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.""" ) def UpperCamelCase_ ( self : List[Any] , *A__ : Any , **A__ : Any ) -> Optional[int]: raise Exception(f"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance.""" ) def UpperCamelCase_ ( self : List[str] , *A__ : Dict , **A__ : Dict ) -> Dict: raise Exception(f"""You cannot use ``pop`` on a {self.__class__.__name__} instance.""" ) def UpperCamelCase_ ( self : Tuple , *A__ : Any , **A__ : int ) -> str: raise Exception(f"""You cannot use ``update`` on a {self.__class__.__name__} instance.""" ) def __getitem__( self : str , A__ : Optional[Any] ) -> Tuple: if isinstance(lowerCamelCase__ , lowerCamelCase__ ): _snake_case = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self : List[Any] , A__ : Optional[int] , A__ : Optional[Any] ) -> Optional[Any]: if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(lowerCamelCase__ , lowerCamelCase__ ) super().__setattr__(lowerCamelCase__ , lowerCamelCase__ ) def __setitem__( self : str , A__ : Optional[int] , A__ : Tuple ) -> List[str]: super().__setitem__(lowerCamelCase__ , lowerCamelCase__ ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(lowerCamelCase__ , lowerCamelCase__ ) def UpperCamelCase_ ( self : Optional[Any] ) -> Tuple[Any]: return tuple(self[k] for k in self.keys() ) class lowercase_ ( __lowerCAmelCase , __lowerCAmelCase ): @classmethod def UpperCamelCase_ ( cls : List[Any] , A__ : List[Any] ) -> List[Any]: raise ValueError( f"""{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}""" ) class lowercase_ ( __lowerCAmelCase ): UpperCamelCase_ : List[Any] = "longest" UpperCamelCase_ : str = "max_length" UpperCamelCase_ : Any = "do_not_pad" class lowercase_ ( __lowerCAmelCase ): UpperCamelCase_ : str = "pt" UpperCamelCase_ : List[Any] = "tf" UpperCamelCase_ : Union[str, Any] = "np" UpperCamelCase_ : Optional[Any] = "jax" class lowercase_ : def __init__( self : Optional[int] , A__ : List[ContextManager] ) -> List[Any]: _snake_case = context_managers _snake_case = ExitStack() def __enter__( self : List[str] ) -> List[str]: for context_manager in self.context_managers: self.stack.enter_context(lowerCamelCase__ ) def __exit__( self : Tuple , *A__ : Tuple , **A__ : List[str] ) -> Dict: self.stack.__exit__(*lowerCamelCase__ , **lowerCamelCase__ ) def snake_case_(_UpperCamelCase ) -> Tuple: """simple docstring""" _snake_case = infer_framework(_UpperCamelCase ) if framework == "tf": _snake_case = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": _snake_case = inspect.signature(model_class.forward ) # PyTorch models else: _snake_case = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def snake_case_(_UpperCamelCase ) -> Union[str, Any]: """simple docstring""" _snake_case = model_class.__name__ _snake_case = infer_framework(_UpperCamelCase ) if framework == "tf": _snake_case = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": _snake_case = inspect.signature(model_class.forward ) # PyTorch models else: _snake_case = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def snake_case_(_UpperCamelCase , _UpperCamelCase = "" , _UpperCamelCase = "." ) -> str: """simple docstring""" def _flatten_dict(_UpperCamelCase , _UpperCamelCase="" , _UpperCamelCase="." ): for k, v in d.items(): _snake_case = str(_UpperCamelCase ) + delimiter + str(_UpperCamelCase ) if parent_key else k if v and isinstance(_UpperCamelCase , _UpperCamelCase ): yield from flatten_dict(_UpperCamelCase , _UpperCamelCase , delimiter=_UpperCamelCase ).items() else: yield key, v return dict(_flatten_dict(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) ) @contextmanager def snake_case_(_UpperCamelCase , _UpperCamelCase = False ) -> Union[str, Any]: """simple docstring""" if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def snake_case_(_UpperCamelCase , _UpperCamelCase=None ) -> Optional[int]: """simple docstring""" if is_numpy_array(_UpperCamelCase ): return np.transpose(_UpperCamelCase , axes=_UpperCamelCase ) elif is_torch_tensor(_UpperCamelCase ): return array.T if axes is None else array.permute(*_UpperCamelCase ) elif is_tf_tensor(_UpperCamelCase ): import tensorflow as tf return tf.transpose(_UpperCamelCase , perm=_UpperCamelCase ) elif is_jax_tensor(_UpperCamelCase ): return jnp.transpose(_UpperCamelCase , axes=_UpperCamelCase ) else: raise ValueError(F"""Type not supported for transpose: {type(_UpperCamelCase )}.""" ) def snake_case_(_UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]: """simple docstring""" if is_numpy_array(_UpperCamelCase ): return np.reshape(_UpperCamelCase , _UpperCamelCase ) elif is_torch_tensor(_UpperCamelCase ): return array.reshape(*_UpperCamelCase ) elif is_tf_tensor(_UpperCamelCase ): import tensorflow as tf return tf.reshape(_UpperCamelCase , _UpperCamelCase ) elif is_jax_tensor(_UpperCamelCase ): return jnp.reshape(_UpperCamelCase , _UpperCamelCase ) else: raise ValueError(F"""Type not supported for reshape: {type(_UpperCamelCase )}.""" ) def snake_case_(_UpperCamelCase , _UpperCamelCase=None ) -> Union[str, Any]: """simple docstring""" if is_numpy_array(_UpperCamelCase ): return np.squeeze(_UpperCamelCase , axis=_UpperCamelCase ) elif is_torch_tensor(_UpperCamelCase ): return array.squeeze() if axis is None else array.squeeze(dim=_UpperCamelCase ) elif is_tf_tensor(_UpperCamelCase ): import tensorflow as tf return tf.squeeze(_UpperCamelCase , axis=_UpperCamelCase ) elif is_jax_tensor(_UpperCamelCase ): return jnp.squeeze(_UpperCamelCase , axis=_UpperCamelCase ) else: raise ValueError(F"""Type not supported for squeeze: {type(_UpperCamelCase )}.""" ) def snake_case_(_UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" if is_numpy_array(_UpperCamelCase ): return np.expand_dims(_UpperCamelCase , _UpperCamelCase ) elif is_torch_tensor(_UpperCamelCase ): return array.unsqueeze(dim=_UpperCamelCase ) elif is_tf_tensor(_UpperCamelCase ): import tensorflow as tf return tf.expand_dims(_UpperCamelCase , axis=_UpperCamelCase ) elif is_jax_tensor(_UpperCamelCase ): return jnp.expand_dims(_UpperCamelCase , axis=_UpperCamelCase ) else: raise ValueError(F"""Type not supported for expand_dims: {type(_UpperCamelCase )}.""" ) def snake_case_(_UpperCamelCase ) -> Union[str, Any]: """simple docstring""" if is_numpy_array(_UpperCamelCase ): return np.size(_UpperCamelCase ) elif is_torch_tensor(_UpperCamelCase ): return array.numel() elif is_tf_tensor(_UpperCamelCase ): import tensorflow as tf return tf.size(_UpperCamelCase ) elif is_jax_tensor(_UpperCamelCase ): return array.size else: raise ValueError(F"""Type not supported for expand_dims: {type(_UpperCamelCase )}.""" ) def snake_case_(_UpperCamelCase , _UpperCamelCase ) -> str: """simple docstring""" for key, value in auto_map.items(): if isinstance(_UpperCamelCase , (tuple, list) ): _snake_case = [F"""{repo_id}--{v}""" if (v is not None and '''--''' not in v) else v for v in value] elif value is not None and "--" not in value: _snake_case = F"""{repo_id}--{value}""" return auto_map def snake_case_(_UpperCamelCase ) -> int: """simple docstring""" for base_class in inspect.getmro(_UpperCamelCase ): _snake_case = base_class.__module__ _snake_case = base_class.__name__ if module.startswith('''tensorflow''' ) or module.startswith('''keras''' ) or name == "TFPreTrainedModel": return "tf" elif module.startswith('''torch''' ) or name == "PreTrainedModel": return "pt" elif module.startswith('''flax''' ) or module.startswith('''jax''' ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(F"""Could not infer framework from class {model_class}.""" )
357
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowercase_ ( __lowercase , unittest.TestCase ): UpperCamelCase_ : Union[str, Any] = CLIPTokenizer UpperCamelCase_ : Optional[int] = CLIPTokenizerFast UpperCamelCase_ : Dict = True UpperCamelCase_ : Union[str, Any] = {} UpperCamelCase_ : Optional[Any] = False def UpperCamelCase_ ( self : Union[str, Any] ) -> Dict: super().setUp() # fmt: off _snake_case = ['''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 _snake_case = dict(zip(A__ , range(len(A__ ) ) ) ) _snake_case = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>'''] _snake_case = {'''unk_token''': '''<unk>'''} _snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(A__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(A__ ) ) def UpperCamelCase_ ( self : List[Any] , **A__ : int ) -> Union[str, Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **A__ ) def UpperCamelCase_ ( self : Any , **A__ : Tuple ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **A__ ) def UpperCamelCase_ ( self : Optional[Any] , A__ : str ) -> str: _snake_case = '''lower newer''' _snake_case = '''lower newer''' return input_text, output_text def UpperCamelCase_ ( self : Union[str, Any] ) -> Optional[int]: _snake_case = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) _snake_case = '''lower newer''' _snake_case = ['''lo''', '''w''', '''er</w>''', '''n''', '''e''', '''w''', '''er</w>'''] _snake_case = tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) _snake_case = tokens + [tokenizer.unk_token] _snake_case = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , A__ ) @require_ftfy def UpperCamelCase_ ( self : Any ) -> Optional[int]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _snake_case = self.tokenizer_class.from_pretrained(A__ , **A__ ) _snake_case = self.rust_tokenizer_class.from_pretrained(A__ , **A__ ) _snake_case = '''A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.''' _snake_case = tokenizer_s.tokenize(A__ ) _snake_case = tokenizer_r.tokenize(A__ ) self.assertListEqual(A__ , A__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways _snake_case = '''xa\u0303y''' + ''' ''' + '''x\xe3y''' _snake_case = tokenizer_s.tokenize(A__ ) _snake_case = tokenizer_r.tokenize(A__ ) self.assertListEqual(A__ , A__ ) # Test that the tokenization is identical on unicode of space type _snake_case = [ '''\u0009''', # (horizontal tab, '\t') '''\u000B''', # (vertical tab) '''\u000C''', # (form feed) '''\u0020''', # (space, ' ') '''\u200E''', # (left-to-right mark):w '''\u200F''', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: _snake_case = tokenizer_s.tokenize(A__ ) _snake_case = tokenizer_r.tokenize(A__ ) self.assertListEqual(A__ , A__ ) # Test that the tokenization is identical on unicode of line break type _snake_case = [ '''\u000A''', # (line feed, '\n') '''\r\n''', # (carriage return and line feed, '\r\n') '''\u000D''', # (carriage return, '\r') '''\r''', # (carriage return, '\r') '''\u000D''', # (carriage return, '\r') '''\u2028''', # (line separator) '''\u2029''', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: _snake_case = tokenizer_s.tokenize(A__ ) _snake_case = tokenizer_r.tokenize(A__ ) self.assertListEqual(A__ , A__ ) def UpperCamelCase_ ( self : List[Any] ) -> Optional[Any]: # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _snake_case = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name` _snake_case = f"""{text_of_1_token} {text_of_1_token}""" _snake_case = self.rust_tokenizer_class.from_pretrained( A__ , use_fast=A__ , ) _snake_case = 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__ )) , ) _snake_case = f""" {text}""" _snake_case = self.rust_tokenizer_class.from_pretrained( A__ , use_fast=A__ , ) _snake_case = 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__ )) , ) def UpperCamelCase_ ( self : Union[str, Any] ) -> Optional[Any]: # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(A__ ) as context: self.rust_tokenizer_class.from_pretrained('''robot-test/old-clip-tokenizer''' ) self.assertTrue( context.exception.args[0].startswith( '''The `backend_tokenizer` provided does not match the expected format.''' ) ) @require_ftfy def UpperCamelCase_ ( self : Dict ) -> Union[str, Any]: super().test_tokenization_python_rust_equals() def UpperCamelCase_ ( self : str ) -> Optional[int]: # CLIP always lower cases letters pass
278
0
import itertools import math def __UpperCamelCase ( _A ): 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(__a ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __UpperCamelCase ( ): lowerCAmelCase_ = 2 while True: if is_prime(__a ): yield num num += 1 def __UpperCamelCase ( _A = 10001 ): return next(itertools.islice(prime_generator() , nth - 1 , __a ) ) if __name__ == "__main__": print(f"{solution() = }")
278
from collections.abc import Callable class UpperCAmelCase_ : """simple docstring""" def __init__( self , _a = None ) -> None: # Stores actual heap items. _a : list = [] # Stores indexes of each item for supporting updates and deletion. _a : dict = {} # Stores current size of heap. _a : Tuple = 0 # Stores function used to evaluate the score of an item on which basis ordering # will be done. _a : Dict = key or (lambda _a : x) def __lowercase ( self , _a ) -> int | None: return int((i - 1) / 2 ) if i > 0 else None def __lowercase ( self , _a ) -> int | None: _a : Optional[int] = int(2 * i + 1 ) return left if 0 < left < self.size else None def __lowercase ( self , _a ) -> int | None: _a : int = int(2 * i + 2 ) return right if 0 < right < self.size else None def __lowercase ( self , _a , _a ) -> None: _a , _a : Union[str, Any] = ( self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]], ) # Then swap the items in the list. _a , _a : List[Any] = self.arr[j], self.arr[i] def __lowercase ( self , _a , _a ) -> bool: return self.arr[i][1] < self.arr[j][1] def __lowercase ( self , _a ) -> int: _a : Dict = self._left(_a ) _a : str = self._right(_a ) _a : str = i if left is not None and not self._cmp(_a , _a ): _a : Optional[Any] = left if right is not None and not self._cmp(_a , _a ): _a : Any = right return valid_parent def __lowercase ( self , _a ) -> None: _a : List[str] = self._parent(_a ) while parent is not None and not self._cmp(_a , _a ): self._swap(_a , _a ) _a , _a : Any = parent, self._parent(_a ) def __lowercase ( self , _a ) -> None: _a : List[Any] = self._get_valid_parent(_a ) while valid_parent != index: self._swap(_a , _a ) _a , _a : int = valid_parent, self._get_valid_parent(_a ) def __lowercase ( self , _a , _a ) -> None: if item not in self.pos_map: return _a : str = self.pos_map[item] _a : List[Any] = [item, self.key(_a )] # Make sure heap is right in both up and down direction. # Ideally only one of them will make any change. self._heapify_up(_a ) self._heapify_down(_a ) def __lowercase ( self , _a ) -> None: if item not in self.pos_map: return _a : Tuple = self.pos_map[item] del self.pos_map[item] _a : Tuple = self.arr[self.size - 1] _a : str = index self.size -= 1 # Make sure heap is right in both up and down direction. Ideally only one # of them will make any change- so no performance loss in calling both. if self.size > index: self._heapify_up(_a ) self._heapify_down(_a ) def __lowercase ( self , _a , _a ) -> None: _a : Union[str, Any] = len(self.arr ) if arr_len == self.size: self.arr.append([item, self.key(_a )] ) else: _a : Optional[int] = [item, self.key(_a )] _a : Tuple = self.size self.size += 1 self._heapify_up(self.size - 1 ) def __lowercase ( self ) -> tuple | None: return self.arr[0] if self.size else None def __lowercase ( self ) -> tuple | None: _a : Tuple = self.get_top() if top_item_tuple: self.delete_item(top_item_tuple[0] ) return top_item_tuple def __UpperCAmelCase ( ) -> None: """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
235
0
'''simple docstring''' import inspect import unittest from transformers import MobileNetVaConfig 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 transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __UpperCamelCase ( snake_case_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_A , 'tf_padding' ) ) self.parent.assertTrue(hasattr(_A , 'depth_multiplier' ) ) class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=3 , __a=32 , __a=0.25 , __a=8 , __a=True , __a=1024 , __a=32 , __a="relu6" , __a=0.1 , __a=0.02 , __a=True , __a=True , __a=10 , __a=None , ): '''simple docstring''' __a : Optional[int] = parent __a : List[str] = batch_size __a : Optional[int] = num_channels __a : int = image_size __a : Optional[Any] = depth_multiplier __a : str = min_depth __a : Any = tf_padding __a : str = int(last_hidden_size * depth_multiplier ) __a : List[Any] = output_stride __a : Optional[int] = hidden_act __a : str = classifier_dropout_prob __a : Any = use_labels __a : Optional[Any] = is_training __a : Tuple = num_labels __a : Tuple = initializer_range __a : Optional[int] = scope def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Union[str, Any] = None __a : int = None if self.use_labels: __a : Tuple = 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 : List[str] = self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self ): '''simple docstring''' return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self , __a , __a , __a , __a ): '''simple docstring''' __a : Any = MobileNetVaModel(config=_A ) model.to(_A ) model.eval() __a : List[Any] = 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 __UpperCAmelCase ( self , __a , __a , __a , __a ): '''simple docstring''' __a : Any = self.num_labels __a : str = MobileNetVaForImageClassification(_A ) model.to(_A ) model.eval() __a : Union[str, Any] = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.prepare_config_and_inputs() __a : Dict = config_and_inputs __a : List[str] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __UpperCamelCase ( snake_case_ , snake_case_ , unittest.TestCase ): A_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () A_ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = MobileNetVaModelTester(self ) __a : Tuple = MobileNetVaConfigTester(self , config_class=_A , has_text_modality=_A ) def __UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='MobileNetV1 does not use inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='MobileNetV1 does not support input and output embeddings' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='MobileNetV1 does not output attentions' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass def __UpperCAmelCase ( self ): '''simple docstring''' __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 : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : int = [*signature.parameters.keys()] __a : int = ['pixel_values'] self.assertListEqual(arg_names[:1] , _A ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def __UpperCAmelCase ( self ): '''simple docstring''' def check_hidden_states_output(__a , __a , __a ): __a : Dict = model_class(_A ) model.to(_A ) model.eval() with torch.no_grad(): __a : Optional[Any] = model(**self._prepare_for_class(_A , _A ) ) __a : str = outputs.hidden_states __a : Dict = 26 self.assertEqual(len(_A ) , _A ) __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Union[str, Any] = True check_hidden_states_output(_A , _A , _A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Optional[int] = True check_hidden_states_output(_A , _A , _A ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Tuple = MobileNetVaModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def lowerCamelCase (): __a : str = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return ( MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224' ) if is_vision_available() else None ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : Tuple = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224' ).to(_A ) __a : int = self.default_image_processor __a : List[Any] = prepare_img() __a : List[Any] = image_processor(images=_A , return_tensors='pt' ).to(_A ) # forward pass with torch.no_grad(): __a : int = model(**_A ) # verify the logits __a : Dict = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , _A ) __a : Tuple = torch.tensor([-4.1739, -1.1233, 3.1205] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1E-4 ) )
350
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __lowercase : List[Any] = { 'susnato/ernie-m-base_pytorch': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json', 'susnato/ernie-m-large_pytorch': 'https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json', } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "ernie_m" A_ = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self , __a = 25_0002 , __a = 768 , __a = 12 , __a = 12 , __a = 3072 , __a = "gelu" , __a = 0.1 , __a = 0.1 , __a = 514 , __a = 0.02 , __a = 1 , __a = 1E-0_5 , __a=None , __a=False , __a=0.0 , **__a , ): '''simple docstring''' super().__init__(pad_token_id=__a , **__a ) __a : int = vocab_size __a : Dict = hidden_size __a : str = num_hidden_layers __a : Dict = num_attention_heads __a : List[str] = intermediate_size __a : Union[str, Any] = hidden_act __a : List[Any] = hidden_dropout_prob __a : str = attention_probs_dropout_prob __a : Any = max_position_embeddings __a : int = initializer_range __a : Dict = layer_norm_eps __a : int = classifier_dropout __a : Dict = is_decoder __a : int = act_dropout
294
0
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : Dict =logging.get_logger(__name__) _UpperCAmelCase : Any ={ """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/config.json""", """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/config.json""", } class snake_case__( UpperCAmelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = """xlnet""" SCREAMING_SNAKE_CASE__ : Optional[int] = ["""mems"""] SCREAMING_SNAKE_CASE__ : str = { """n_token""": """vocab_size""", # Backward compatibility """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , __lowercase=3_2_0_0_0 , __lowercase=1_0_2_4 , __lowercase=2_4 , __lowercase=1_6 , __lowercase=4_0_9_6 , __lowercase="gelu" , __lowercase=True , __lowercase="bi" , __lowercase=0.02 , __lowercase=1e-12 , __lowercase=0.1 , __lowercase=5_1_2 , __lowercase=None , __lowercase=True , __lowercase=False , __lowercase=False , __lowercase=-1 , __lowercase=False , __lowercase="last" , __lowercase=True , __lowercase="tanh" , __lowercase=0.1 , __lowercase=5 , __lowercase=5 , __lowercase=5 , __lowercase=1 , __lowercase=2 , **__lowercase , ) -> Optional[int]: lowerCAmelCase_ : List[str] = vocab_size lowerCAmelCase_ : Optional[int] = d_model lowerCAmelCase_ : Tuple = n_layer lowerCAmelCase_ : List[Any] = n_head if d_model % n_head != 0: raise ValueError(f"""'d_model % n_head' ({d_model % n_head}) should be equal to 0""" ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( f"""`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})""" ) lowerCAmelCase_ : Any = d_model // n_head lowerCAmelCase_ : List[Any] = ff_activation lowerCAmelCase_ : int = d_inner lowerCAmelCase_ : Union[str, Any] = untie_r lowerCAmelCase_ : int = attn_type lowerCAmelCase_ : int = initializer_range lowerCAmelCase_ : Tuple = layer_norm_eps lowerCAmelCase_ : List[Any] = dropout lowerCAmelCase_ : Tuple = mem_len lowerCAmelCase_ : int = reuse_len lowerCAmelCase_ : List[Any] = bi_data lowerCAmelCase_ : Tuple = clamp_len lowerCAmelCase_ : List[Any] = same_length lowerCAmelCase_ : int = summary_type lowerCAmelCase_ : str = summary_use_proj lowerCAmelCase_ : Union[str, Any] = summary_activation lowerCAmelCase_ : Any = summary_last_dropout lowerCAmelCase_ : Optional[Any] = start_n_top lowerCAmelCase_ : Optional[Any] = end_n_top lowerCAmelCase_ : Union[str, Any] = bos_token_id lowerCAmelCase_ : Tuple = pad_token_id lowerCAmelCase_ : str = eos_token_id if "use_cache" in kwargs: warnings.warn( '''The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`''' ''' instead.''' , __lowercase , ) lowerCAmelCase_ : Union[str, Any] = kwargs['''use_cache'''] lowerCAmelCase_ : List[str] = use_mems_eval lowerCAmelCase_ : List[Any] = use_mems_train super().__init__(pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) @property def lowercase_ ( self ) -> List[Any]: logger.info(f"""The model {self.model_type} is one of the few models that has no sequence length limit.""" ) return -1 @max_position_embeddings.setter def lowercase_ ( self , __lowercase ) -> Optional[int]: # Message copied from Transformer-XL documentation raise NotImplementedError( f"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
262
import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def lowerCAmelCase ( lowerCAmelCase_ )-> Union[str, Any]: return EnvironmentCommand() class snake_case__( UpperCAmelCase__ ): '''simple docstring''' @staticmethod def lowercase_ ( __lowercase ) -> List[Any]: lowerCAmelCase_ : List[str] = parser.add_parser('''env''' ) download_parser.set_defaults(func=__lowercase ) def lowercase_ ( self ) -> int: lowerCAmelCase_ : Optional[Any] = huggingface_hub.__version__ lowerCAmelCase_ : str = '''not installed''' lowerCAmelCase_ : str = '''NA''' if is_torch_available(): import torch lowerCAmelCase_ : Any = torch.__version__ lowerCAmelCase_ : str = torch.cuda.is_available() lowerCAmelCase_ : List[str] = '''not installed''' if is_transformers_available(): import transformers lowerCAmelCase_ : Any = transformers.__version__ lowerCAmelCase_ : Optional[Any] = '''not installed''' if is_accelerate_available(): import accelerate lowerCAmelCase_ : List[Any] = accelerate.__version__ lowerCAmelCase_ : List[str] = '''not installed''' if is_xformers_available(): import xformers lowerCAmelCase_ : Optional[Any] = xformers.__version__ lowerCAmelCase_ : int = { '''`diffusers` version''': version, '''Platform''': platform.platform(), '''Python version''': platform.python_version(), '''PyTorch version (GPU?)''': f"""{pt_version} ({pt_cuda_available})""", '''Huggingface_hub version''': hub_version, '''Transformers version''': transformers_version, '''Accelerate version''': accelerate_version, '''xFormers version''': xformers_version, '''Using GPU in script?''': '''<fill in>''', '''Using distributed or parallel set-up in script?''': '''<fill in>''', } print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n''' ) print(self.format_dict(__lowercase ) ) return info @staticmethod def lowercase_ ( __lowercase ) -> str: return "\n".join([f"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"
262
1
"""simple docstring""" import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow __SCREAMING_SNAKE_CASE =False class UpperCamelCase ( unittest.TestCase ): def _UpperCAmelCase ( self ,__UpperCamelCase=32 ) -> Union[str, Any]: '''simple docstring''' set_seed(0 ) lowercase_ : str = UNetaDModel(sample_size=lowerCamelCase_ ,in_channels=3 ,out_channels=3 ) lowercase_ : int = torch.optim.SGD(model.parameters() ,lr=0.0001 ) return model, optimizer @slow def _UpperCAmelCase ( self ) -> List[Any]: '''simple docstring''' lowercase_ : str = 'cpu' # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable lowercase_ : str = DDPMScheduler( num_train_timesteps=1000 ,beta_start=0.0001 ,beta_end=0.02 ,beta_schedule='linear' ,clip_sample=lowerCamelCase_ ,) lowercase_ : List[str] = DDIMScheduler( num_train_timesteps=1000 ,beta_start=0.0001 ,beta_end=0.02 ,beta_schedule='linear' ,clip_sample=lowerCamelCase_ ,) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) lowercase_ : Any = [torch.randn((4, 3, 32, 32) ).clip(-1 ,1 ).to(lowerCamelCase_ ) for _ in range(4 )] lowercase_ : Dict = [torch.randn((4, 3, 32, 32) ).to(lowerCamelCase_ ) for _ in range(4 )] lowercase_ : Any = [torch.randint(0 ,1000 ,(4,) ).long().to(lowerCamelCase_ ) for _ in range(4 )] # train with a DDPM scheduler lowercase_ , lowercase_ : Any = self.get_model_optimizer(resolution=32 ) model.train().to(lowerCamelCase_ ) for i in range(4 ): optimizer.zero_grad() lowercase_ : Union[str, Any] = ddpm_scheduler.add_noise(clean_images[i] ,noise[i] ,timesteps[i] ) lowercase_ : Dict = model(lowerCamelCase_ ,timesteps[i] ).sample lowercase_ : Union[str, Any] = torch.nn.functional.mse_loss(lowerCamelCase_ ,noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM lowercase_ , lowercase_ : Optional[Any] = self.get_model_optimizer(resolution=32 ) model.train().to(lowerCamelCase_ ) for i in range(4 ): optimizer.zero_grad() lowercase_ : int = ddim_scheduler.add_noise(clean_images[i] ,noise[i] ,timesteps[i] ) lowercase_ : Any = model(lowerCamelCase_ ,timesteps[i] ).sample lowercase_ : int = torch.nn.functional.mse_loss(lowerCamelCase_ ,noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(lowerCamelCase_ ,lowerCamelCase_ ,atol=1e-5 ) ) self.assertTrue(torch.allclose(lowerCamelCase_ ,lowerCamelCase_ ,atol=1e-5 ) )
361
"""simple docstring""" # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def lowercase__( *__SCREAMING_SNAKE_CASE : Tuple ): with open(__SCREAMING_SNAKE_CASE , 'r' ) as fh: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_EX ) try: print(*__SCREAMING_SNAKE_CASE ) finally: fcntl.flock(__SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) __SCREAMING_SNAKE_CASE =int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) __SCREAMING_SNAKE_CASE =torch.device("cuda", local_rank) __SCREAMING_SNAKE_CASE =socket.gethostname() __SCREAMING_SNAKE_CASE =F"[{hostname}-{local_rank}]" try: # test distributed dist.init_process_group("nccl") dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank __SCREAMING_SNAKE_CASE =dist.get_rank() __SCREAMING_SNAKE_CASE =dist.get_world_size() printflock(F"{gpu} is OK (global rank: {rank}/{world_size})") dist.barrier() if rank == 0: printflock(F"pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}") except Exception: printflock(F"{gpu} is broken") raise
321
0
def UpperCamelCase ( __magic_name__ : int ) -> bool: """simple docstring""" lowercase__ = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
305
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__ = pytest.mark.integration @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" a = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__UpperCAmelCase ) for x in np.arange(30 ).tolist()]} ) return dset def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" import faiss a = self._create_dummy_dataset() a = dset.map( lambda __UpperCAmelCase , __UpperCAmelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__UpperCAmelCase , keep_in_memory=__UpperCAmelCase ) a = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) a , a = 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 __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" import faiss a = 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 , ) a , a = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" import faiss a = 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 ) a , a = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = 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 __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" from elasticsearch import Elasticsearch a = 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: a = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} a = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=__UpperCAmelCase ) a , a = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" import faiss a = 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 a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries a = np.eye(5 , dtype=np.floataa )[::-1] a , a = index.search_batch(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search_batch , queries[0] ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" import faiss a = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) a = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__UpperCAmelCase ): a = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" import faiss a = faiss.IndexFlat(5 ) a = FaissIndex(custom_index=__UpperCAmelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" import faiss a = 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 ) a = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def _a ( a :Dict ) -> Any: import faiss a = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) a = '''index.faiss''' a = F"""mock://{index_name}""" index.save(a , storage_options=mockfs.storage_options ) a = FaissIndex.load(a , storage_options=mockfs.storage_options ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(a ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" 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: a = Elasticsearch() a = {'''acknowledged''': True} a = ElasticSearchIndex(es_client=__UpperCAmelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase ) # batched queries with timeout a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase , request_timeout=30 ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase )
0
0
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __a ( unittest.TestCase ): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=18 , lowerCAmelCase__=30 , lowerCAmelCase__=400 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , ) -> List[Any]: '''simple docstring''' lowercase__: Tuple = size if size is not None else {'height': 18, 'width': 18} lowercase__: Tuple = parent lowercase__: str = batch_size lowercase__: Union[str, Any] = num_channels lowercase__: Tuple = image_size lowercase__: List[str] = min_resolution lowercase__: str = max_resolution lowercase__: Optional[int] = do_resize lowercase__: Optional[Any] = size lowercase__: int = apply_ocr def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __a ( __UpperCamelCase , unittest.TestCase ): __lowercase : Dict = LayoutLMvaImageProcessor if is_pytesseract_available() else None def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: '''simple docstring''' lowercase__: List[str] = LayoutLMvaImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE__ ( self ) -> int: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' lowercase__: Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase__ , 'do_resize' ) ) self.assertTrue(hasattr(lowerCAmelCase__ , 'size' ) ) self.assertTrue(hasattr(lowerCAmelCase__ , 'apply_ocr' ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: '''simple docstring''' lowercase__: List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) lowercase__: Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' # Initialize image_processing lowercase__: int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase__: Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input lowercase__: Dict = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , lowerCAmelCase__ ) self.assertIsInstance(encoding.boxes , lowerCAmelCase__ ) # Test batched lowercase__: Any = image_processing(lowerCAmelCase__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' # Initialize image_processing lowercase__: List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase__: str = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , numpify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , np.ndarray ) # Test not batched input lowercase__: Optional[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowercase__: Tuple = image_processing(lowerCAmelCase__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: '''simple docstring''' # Initialize image_processing lowercase__: List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase__: int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ , torchify=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , torch.Tensor ) # Test not batched input lowercase__: Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched lowercase__: int = image_processing(lowerCAmelCase__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: '''simple docstring''' # with apply_OCR = True lowercase__: Dict = LayoutLMvaImageProcessor() from datasets import load_dataset lowercase__: str = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) lowercase__: List[str] = Image.open(ds[0]['file'] ).convert('RGB' ) lowercase__: Any = image_processing(lowerCAmelCase__ , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 lowercase__: Union[str, Any] = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 lowercase__: Optional[int] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , lowerCAmelCase__ ) self.assertListEqual(encoding.boxes , lowerCAmelCase__ ) # with apply_OCR = False lowercase__: Optional[int] = LayoutLMvaImageProcessor(apply_ocr=lowerCAmelCase__ ) lowercase__: int = image_processing(lowerCAmelCase__ , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
288
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class __a : def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=13 , lowerCAmelCase__=30 , lowerCAmelCase__=2 , lowerCAmelCase__=3 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=32 , lowerCAmelCase__=2 , lowerCAmelCase__=4 , lowerCAmelCase__=37 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=10 , lowerCAmelCase__=0.0_2 , lowerCAmelCase__=3 , lowerCAmelCase__=None , lowerCAmelCase__=2 , ) -> List[str]: '''simple docstring''' lowercase__: List[str] = parent lowercase__: Tuple = batch_size lowercase__: Optional[Any] = image_size lowercase__: int = patch_size lowercase__: Union[str, Any] = num_channels lowercase__: Dict = is_training lowercase__: Any = use_labels lowercase__: Optional[int] = hidden_size lowercase__: Tuple = num_hidden_layers lowercase__: List[str] = num_attention_heads lowercase__: Any = intermediate_size lowercase__: Union[str, Any] = hidden_act lowercase__: Union[str, Any] = hidden_dropout_prob lowercase__: Optional[Any] = attention_probs_dropout_prob lowercase__: str = type_sequence_label_size lowercase__: List[str] = initializer_range lowercase__: Optional[Any] = scope lowercase__: Dict = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) lowercase__: List[str] = (image_size // patch_size) ** 2 lowercase__: Tuple = num_patches + 2 def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[int]: '''simple docstring''' lowercase__: List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__: int = None if self.use_labels: lowercase__: str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__: List[str] = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: '''simple docstring''' return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCAmelCase__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: '''simple docstring''' lowercase__: List[str] = TFDeiTModel(config=lowerCAmelCase__ ) lowercase__: Any = model(lowerCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' lowercase__: Any = TFDeiTForMaskedImageModeling(config=lowerCAmelCase__ ) lowercase__: int = model(lowerCAmelCase__ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images lowercase__: Tuple = 1 lowercase__: Optional[int] = TFDeiTForMaskedImageModeling(lowerCAmelCase__ ) lowercase__: int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase__: str = model(lowerCAmelCase__ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' lowercase__: Any = self.type_sequence_label_size lowercase__: Optional[Any] = TFDeiTForImageClassification(lowerCAmelCase__ ) lowercase__: List[Any] = model(lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowercase__: Optional[Any] = 1 lowercase__: Union[str, Any] = TFDeiTForImageClassification(lowerCAmelCase__ ) lowercase__: List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase__: str = model(lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: '''simple docstring''' lowercase__: Dict = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__: Dict = config_and_inputs lowercase__: Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class __a ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): __lowercase : Union[str, Any] = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) __lowercase : Union[str, Any] = ( { 'feature-extraction': TFDeiTModel, 'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) __lowercase : Union[str, Any] = False __lowercase : Tuple = False __lowercase : int = False __lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: '''simple docstring''' lowercase__: List[Any] = TFDeiTModelTester(self ) lowercase__: int = ConfigTester(self , config_class=lowerCAmelCase__ , has_text_modality=lowerCAmelCase__ , hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: '''simple docstring''' lowercase__ , lowercase__: int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__: Tuple = model_class(lowerCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) lowercase__: Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase__ , tf.keras.layers.Dense ) ) def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]: '''simple docstring''' lowercase__ , lowercase__: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__: Any = model_class(lowerCAmelCase__ ) lowercase__: Any = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__: Dict = [*signature.parameters.keys()] lowercase__: Any = ['pixel_values'] self.assertListEqual(arg_names[:1] , lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: '''simple docstring''' lowercase__: Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> List[str]: '''simple docstring''' lowercase__: Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: '''simple docstring''' lowercase__: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False ) -> List[Any]: '''simple docstring''' lowercase__: Union[str, Any] = super()._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ , return_labels=lowerCAmelCase__ ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: '''simple docstring''' for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__: Union[str, Any] = TFDeiTModel.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) def snake_case_ ( ) -> Tuple: lowercase__: Any = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class __a ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple: '''simple docstring''' return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self ) -> Dict: '''simple docstring''' lowercase__: str = TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ) lowercase__: str = self.default_image_processor lowercase__: Dict = prepare_img() lowercase__: Optional[int] = image_processor(images=lowerCAmelCase__ , return_tensors='tf' ) # forward pass lowercase__: int = model(**lowerCAmelCase__ ) # verify the logits lowercase__: Tuple = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase__ ) lowercase__: List[Any] = tf.constant([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , lowerCAmelCase__ , atol=1E-4 ) )
288
1
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 snake_case : Dict = pytest.mark.integration @require_faiss class _snake_case ( lowercase__ ): def SCREAMING_SNAKE_CASE__ ( self ): a :str = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(_A ) for x in np.arange(30 ).tolist()]} ) return dset def SCREAMING_SNAKE_CASE__ ( self ): import faiss a :Dataset = self._create_dummy_dataset() a :Union[str, Any] = dset.map( lambda _lowerCamelCase , _lowerCamelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=_A , keep_in_memory=_A ) a :int = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) a :List[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 SCREAMING_SNAKE_CASE__ ( self ): import faiss a :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 , ) a :Any = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def SCREAMING_SNAKE_CASE__ ( self ): import faiss a :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=_A ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) a :Dict = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def SCREAMING_SNAKE_CASE__ ( self ): a :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(_A , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def SCREAMING_SNAKE_CASE__ ( self ): from elasticsearch import Elasticsearch a :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: a :int = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) a :List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} a :Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=_A ) a :Tuple = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class _snake_case ( lowercase__ ): def SCREAMING_SNAKE_CASE__ ( self ): import faiss a :int = 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 a :str = np.zeros(5 , dtype=np.floataa ) a :Optional[int] = 1 a :str = index.search(_A ) self.assertRaises(_A , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries a :Optional[Any] = np.eye(5 , dtype=np.floataa )[::-1] a :str = index.search_batch(_A ) self.assertRaises(_A , index.search_batch , queries[0] ) a :List[Any] = [scores[0] for scores in total_scores] a :List[str] = [indices[0] for indices in total_indices] self.assertGreater(np.min(_A ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , _A ) def SCREAMING_SNAKE_CASE__ ( self ): import faiss a :str = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) a :str = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(_A ): a :Dict = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def SCREAMING_SNAKE_CASE__ ( self ): import faiss a :Any = faiss.IndexFlat(5 ) a :Optional[Any] = FaissIndex(custom_index=_A ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def SCREAMING_SNAKE_CASE__ ( self ): import faiss a :Optional[int] = 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=_A ) as tmp_file: index.save(tmp_file.name ) a :Optional[int] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) a :Dict = np.zeros(5 , dtype=np.floataa ) a :Tuple = 1 a :Optional[Any] = index.search(_A ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def __lowerCamelCase ( UpperCAmelCase_ : Tuple ): """simple docstring""" import faiss a :Union[str, Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) a :Dict = 'index.faiss' a :Optional[Any] = F'''mock://{index_name}''' index.save(UpperCAmelCase_ , storage_options=mockfs.storage_options ) a :Tuple = FaissIndex.load(UpperCAmelCase_ , storage_options=mockfs.storage_options ) a :Union[str, Any] = np.zeros(5 , dtype=np.floataa ) a :List[str] = 1 a :Dict = index.search(UpperCAmelCase_ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class _snake_case ( lowercase__ ): def SCREAMING_SNAKE_CASE__ ( self ): 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: a :Any = Elasticsearch() a :Union[str, Any] = {'acknowledged': True} a :Tuple = ElasticSearchIndex(es_client=_A ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query a :str = 'foo' a :str = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} a :Dict = index.search(_A ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout a :str = 'foo' a :Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} a :Dict = index.search(_A , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries a :Optional[Any] = ['foo', 'bar', 'foobar'] a :Optional[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} a :Optional[Any] = index.search_batch(_A ) a :Tuple = [scores[0] for scores in total_scores] a :List[str] = [indices[0] for indices in total_indices] self.assertGreater(np.min(_A ) , 0 ) self.assertListEqual([1, 1, 1] , _A ) # batched queries with timeout a :Union[str, Any] = ['foo', 'bar', 'foobar'] a :Tuple = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} a :Dict = index.search_batch(_A , request_timeout=30 ) a :Optional[int] = [scores[0] for scores in total_scores] a :Union[str, Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(_A ) , 0 ) self.assertListEqual([1, 1, 1] , _A )
94
'''simple docstring''' import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): lowerCAmelCase :List[str] = yaml.safe_load( '''\ name: "" allow_empty: false allow_empty_text: true subsections: - name: "Dataset Card for X" # First-level markdown heading allow_empty: false allow_empty_text: true subsections: - name: "Table of Contents" allow_empty: false allow_empty_text: false subsections: null - name: "Dataset Description" allow_empty: false allow_empty_text: false subsections: - name: "Dataset Summary" allow_empty: false allow_empty_text: false subsections: null - name: "Supported Tasks and Leaderboards" allow_empty: true allow_empty_text: true subsections: null - name: Languages allow_empty: false allow_empty_text: true subsections: null ''' ) lowerCAmelCase :List[Any] = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } lowerCAmelCase :Union[str, Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase :List[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. #### Extra Ignored Subsection ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase :Tuple = { '''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''': []}, ], }, ], } ], } lowerCAmelCase :Optional[Any] = '''\ --- --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase :Optional[int] = ( '''The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.''' ) lowerCAmelCase :Tuple = '''\ # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase :Union[str, Any] = ( '''The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.''' ) lowerCAmelCase :Dict = '''\ --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase :Dict = '''The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.''' lowerCAmelCase :Optional[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase :int = '''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).''' lowerCAmelCase :int = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ''' lowerCAmelCase :List[str] = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.''' lowerCAmelCase :List[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Languages Language Text ''' lowerCAmelCase :List[str] = '''The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.''' lowerCAmelCase :int = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages ''' lowerCAmelCase :Dict = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.''' lowerCAmelCase :Tuple = '''\ --- language: - zh - en --- ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase :Optional[Any] = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.''' lowerCAmelCase :Any = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text # Dataset Card My Dataset ''' lowerCAmelCase :Dict = '''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.''' lowerCAmelCase :Tuple = '''\ --- language: - zh - en --- # Dataset Card My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase :str = '''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.''' lowerCAmelCase :Any = '''''' lowerCAmelCase :Any = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.''' lowerCAmelCase :List[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase :str = '''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 lowerCamelCase ( lowerCAmelCase : str , lowerCAmelCase : Optional[int] ): """simple docstring""" assert ReadMe.from_string(lowerCAmelCase , lowerCAmelCase ).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 lowerCamelCase ( lowerCAmelCase : Optional[int] , lowerCAmelCase : Dict ): """simple docstring""" with pytest.raises(lowerCAmelCase , match=re.escape(expected_error.format(path='root' ) ) ): __magic_name__ : str = ReadMe.from_string(lowerCAmelCase , lowerCAmelCase ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase ( lowerCAmelCase : List[str] , lowerCAmelCase : Optional[int] ): """simple docstring""" with pytest.raises(lowerCAmelCase , match=re.escape(expected_error.format(path='root' ) ) ): ReadMe.from_string(lowerCAmelCase , lowerCAmelCase ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase ( lowerCAmelCase : Tuple ): """simple docstring""" ReadMe.from_string(lowerCAmelCase , lowerCAmelCase , suppress_parsing_errors=lowerCAmelCase ) @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def lowerCamelCase ( lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__ : Optional[Any] = Path(lowerCAmelCase ) / 'README.md' with open(lowerCAmelCase , 'w+' ) as readme_file: readme_file.write(lowerCAmelCase ) __magic_name__ : Optional[int] = ReadMe.from_readme(lowerCAmelCase , lowerCAmelCase ).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 lowerCamelCase ( lowerCAmelCase : Tuple , lowerCAmelCase : List[Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__ : Union[str, Any] = Path(lowerCAmelCase ) / 'README.md' with open(lowerCAmelCase , 'w+' ) as readme_file: readme_file.write(lowerCAmelCase ) __magic_name__ : str = expected_error.format(path=lowerCAmelCase ) with pytest.raises(lowerCAmelCase , match=re.escape(lowerCAmelCase ) ): __magic_name__ : int = ReadMe.from_readme(lowerCAmelCase , lowerCAmelCase ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase ( lowerCAmelCase : int , lowerCAmelCase : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__ : Optional[int] = Path(lowerCAmelCase ) / 'README.md' with open(lowerCAmelCase , 'w+' ) as readme_file: readme_file.write(lowerCAmelCase ) __magic_name__ : Any = expected_error.format(path=lowerCAmelCase ) with pytest.raises(lowerCAmelCase , match=re.escape(lowerCAmelCase ) ): ReadMe.from_readme(lowerCAmelCase , lowerCAmelCase ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase ( lowerCAmelCase : Union[str, Any] ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__ : Any = Path(lowerCAmelCase ) / 'README.md' with open(lowerCAmelCase , 'w+' ) as readme_file: readme_file.write(lowerCAmelCase ) ReadMe.from_readme(lowerCAmelCase , lowerCAmelCase , suppress_parsing_errors=lowerCAmelCase )
331
0
"""simple docstring""" import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) lowerCAmelCase_ : Tuple = '''\ Text data. Second line of data.''' lowerCAmelCase_ : int = '''file''' @pytest.fixture(scope="""session""" ) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") UpperCAmelCase = bytes(lowerCAmelCase , """utf-8""" ) with zstd.open(lowerCAmelCase , """wb""" ) as f: f.write(lowerCAmelCase ) return path @pytest.fixture def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir , lowerCAmelCase ) , """w""" ) as f: f.write(lowerCAmelCase ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} UpperCAmelCase = input_paths[compression_format] UpperCAmelCase = tmp_path / """cache""" UpperCAmelCase = DownloadConfig(cache_dir=lowerCAmelCase , extract_compressed_file=lowerCAmelCase ) UpperCAmelCase = cached_path(lowerCAmelCase , download_config=lowerCAmelCase ) with open(lowerCAmelCase ) as f: UpperCAmelCase = f.read() with open(lowerCAmelCase ) as f: UpperCAmelCase = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = """custom_cache""" UpperCAmelCase = """custom_extracted_dir""" UpperCAmelCase = tmp_path / """custom_extracted_path""" if default_extracted: UpperCAmelCase = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , lowerCAmelCase ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(lowerCAmelCase ) ) UpperCAmelCase = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) UpperCAmelCase = xz_file UpperCAmelCase = ( DownloadConfig(extract_compressed_file=lowerCAmelCase ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=lowerCAmelCase ) ) UpperCAmelCase = cached_path(lowerCAmelCase , download_config=lowerCAmelCase ) assert Path(lowerCAmelCase ).parent.parts[-2:] == expected def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' # absolute path UpperCAmelCase = str(Path(lowerCAmelCase ).resolve() ) assert cached_path(lowerCAmelCase ) == text_file # relative path UpperCAmelCase = str(Path(lowerCAmelCase ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(lowerCAmelCase ) == text_file def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' # absolute path UpperCAmelCase = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(lowerCAmelCase ): cached_path(lowerCAmelCase ) # relative path UpperCAmelCase = """./__missing_file__.txt""" with pytest.raises(lowerCAmelCase ): cached_path(lowerCAmelCase ) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = get_from_cache(F'''tmp://{tmpfs_file}''' ) with open(lowerCAmelCase ) as f: UpperCAmelCase = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , lowerCAmelCase ) def _lowerCAmelCase ( ): '''simple docstring''' with pytest.raises(lowerCAmelCase ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , lowerCAmelCase ) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(lowerCAmelCase ): http_get("""https://huggingface.co""" , temp_file=lowerCAmelCase ) with pytest.raises(lowerCAmelCase ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , lowerCAmelCase ) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(lowerCAmelCase ): ftp_get("""ftp://huggingface.co""" , temp_file=lowerCAmelCase ) with pytest.raises(lowerCAmelCase ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , lowerCAmelCase ) def _lowerCAmelCase ( lowerCAmelCase ): '''simple docstring''' UpperCAmelCase = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(lowerCAmelCase ): fsspec_get("""s3://huggingface.co""" , temp_file=lowerCAmelCase ) with pytest.raises(lowerCAmelCase ): fsspec_head("""s3://huggingface.co""" )
248
"""simple docstring""" import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class UpperCamelCase_ ( a_ ): def __init__( self , *snake_case__ , snake_case__=None , snake_case__=None , **snake_case__ ) -> Optional[Any]: """simple docstring""" super().__init__(*snake_case__ , **snake_case__ ) UpperCAmelCase = eval_examples UpperCAmelCase = post_process_function def UpperCamelCase_ ( self , snake_case__=None , snake_case__=None , snake_case__=None , snake_case__ = "eval" ) -> List[Any]: """simple docstring""" UpperCAmelCase = self.eval_dataset if eval_dataset is None else eval_dataset UpperCAmelCase = self.get_eval_dataloader(snake_case__ ) UpperCAmelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. UpperCAmelCase = self.compute_metrics UpperCAmelCase = None UpperCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop UpperCAmelCase = time.time() try: UpperCAmelCase = eval_loop( snake_case__ , description="""Evaluation""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=snake_case__ , metric_key_prefix=snake_case__ , ) finally: UpperCAmelCase = compute_metrics UpperCAmelCase = self.args.eval_batch_size * self.args.world_size if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( snake_case__ , snake_case__ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default UpperCAmelCase = self.post_process_function(snake_case__ , snake_case__ , output.predictions ) UpperCAmelCase = self.compute_metrics(snake_case__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): UpperCAmelCase = metrics.pop(snake_case__ ) metrics.update(output.metrics ) else: UpperCAmelCase = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(snake_case__ ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) UpperCAmelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , snake_case__ ) return metrics def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__=None , snake_case__ = "test" ) -> Dict: """simple docstring""" UpperCAmelCase = self.get_test_dataloader(snake_case__ ) # Temporarily disable metric computation, we will do it in the loop here. UpperCAmelCase = self.compute_metrics UpperCAmelCase = None UpperCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop UpperCAmelCase = time.time() try: UpperCAmelCase = eval_loop( snake_case__ , description="""Prediction""" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=snake_case__ , metric_key_prefix=snake_case__ , ) finally: UpperCAmelCase = compute_metrics UpperCAmelCase = self.args.eval_batch_size * self.args.world_size if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( snake_case__ , snake_case__ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output UpperCAmelCase = self.post_process_function(snake_case__ , snake_case__ , output.predictions , """predict""" ) UpperCAmelCase = self.compute_metrics(snake_case__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): UpperCAmelCase = metrics.pop(snake_case__ ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=snake_case__ )
248
1