code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from functools import lru_cache def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> set: lowerCamelCase__ : List[Any] = 2 lowerCamelCase__ : str = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(UpperCamelCase ) if n > 1: factors.add(UpperCamelCase ) return factors @lru_cache def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> int: return len(unique_prime_factors(UpperCamelCase ) ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> bool: return len(set(UpperCamelCase ) ) in (0, 1) def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> list: lowerCamelCase__ : Any = 2 while True: # Increment each value of a generated range lowerCamelCase__ : List[Any] = [base + i for i in range(UpperCamelCase )] # Run elements through out unique_prime_factors function # Append our target number to the end. lowerCamelCase__ : Dict = [upf_len(UpperCamelCase ) for x in group] checker.append(UpperCamelCase ) # If all numbers in the list are equal, return the group variable. if equality(UpperCamelCase ): return group # Increment our base variable by 1 base += 1 def SCREAMING_SNAKE_CASE_ (UpperCamelCase = 4 ) -> int: lowerCamelCase__ : List[Any] = run(UpperCamelCase ) return results[0] if len(UpperCamelCase ) else None if __name__ == "__main__": print(solution())
41
"""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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple, _lowerCamelCase : List[str]=13, _lowerCamelCase : Optional[Any]=7, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : int=True, _lowerCamelCase : List[str]=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : int=99, _lowerCamelCase : Optional[int]=32, _lowerCamelCase : Tuple=5, _lowerCamelCase : Tuple=4, _lowerCamelCase : str=37, _lowerCamelCase : Union[str, Any]="gelu", _lowerCamelCase : int=0.1, _lowerCamelCase : List[Any]=0.1, _lowerCamelCase : Dict=5_12, _lowerCamelCase : List[Any]=16, _lowerCamelCase : Any=2, _lowerCamelCase : Any=0.02, _lowerCamelCase : Dict=4, ): '''simple docstring''' __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_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_choices def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __A = None if self.use_attention_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 = 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 _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Dict = True A_ : Tuple = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = FlaxRoFormerModelTester(self ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''', from_pt=_lowerCamelCase ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase ) @require_flax class snake_case ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __A = jnp.array([[0, 1, 2, 3, 4, 5]] ) __A = model(_lowerCamelCase )[0] __A = 5_00_00 __A = (1, 6, vocab_size) self.assertEqual(output.shape, _lowerCamelCase ) __A = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase : Any = { "configuration_chinese_clip": [ "CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "ChineseCLIPConfig", "ChineseCLIPOnnxConfig", "ChineseCLIPTextConfig", "ChineseCLIPVisionConfig", ], "processing_chinese_clip": ["ChineseCLIPProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = ["ChineseCLIPFeatureExtractor"] lowercase : List[Any] = ["ChineseCLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Any = [ "CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "ChineseCLIPModel", "ChineseCLIPPreTrainedModel", "ChineseCLIPTextModel", "ChineseCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys lowercase : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
42
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase ( __UpperCamelCase = 1_0_0_0_0_0_0 , __UpperCamelCase = 1_0 ): """simple docstring""" __A = defaultdict(__UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __A = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __A = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(__UpperCamelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 1_0 ) if __name__ == "__main__": print(F'''{solution() = }''')
266
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = { '''google/realm-cc-news-pretrained-embedder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-encoder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-scorer''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-openqa''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json''' ), '''google/realm-orqa-nq-openqa''': '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json''', '''google/realm-orqa-nq-reader''': '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json''', '''google/realm-orqa-wq-openqa''': '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json''', '''google/realm-orqa-wq-reader''': '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json''', # See all REALM models at https://huggingface.co/models?filter=realm } class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' a__ : Any = """realm""" def __init__( self , __lowercase=30_522 , __lowercase=768 , __lowercase=128 , __lowercase=12 , __lowercase=12 , __lowercase=8 , __lowercase=3_072 , __lowercase="gelu_new" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=512 , __lowercase=2 , __lowercase=0.02 , __lowercase=1E-1_2 , __lowercase=256 , __lowercase=10 , __lowercase=1E-3 , __lowercase=5 , __lowercase=320 , __lowercase=13_353_718 , __lowercase=5_000 , __lowercase=1 , __lowercase=0 , __lowercase=2 , **__lowercase , ) -> Tuple: super().__init__(pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase) # Common config __UpperCamelCase :Union[str, Any] = vocab_size __UpperCamelCase :int = max_position_embeddings __UpperCamelCase :List[Any] = hidden_size __UpperCamelCase :List[str] = retriever_proj_size __UpperCamelCase :int = num_hidden_layers __UpperCamelCase :str = num_attention_heads __UpperCamelCase :List[str] = num_candidates __UpperCamelCase :List[Any] = intermediate_size __UpperCamelCase :List[str] = hidden_act __UpperCamelCase :List[Any] = hidden_dropout_prob __UpperCamelCase :int = attention_probs_dropout_prob __UpperCamelCase :List[Any] = initializer_range __UpperCamelCase :Dict = type_vocab_size __UpperCamelCase :List[str] = layer_norm_eps # Reader config __UpperCamelCase :List[Any] = span_hidden_size __UpperCamelCase :int = max_span_width __UpperCamelCase :List[str] = reader_layer_norm_eps __UpperCamelCase :Optional[int] = reader_beam_size __UpperCamelCase :Optional[Any] = reader_seq_len # Retrieval config __UpperCamelCase :str = num_block_records __UpperCamelCase :Any = searcher_beam_size
43
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : Optional[int]=2, _lowerCamelCase : Optional[int]=3, _lowerCamelCase : int=64, _lowerCamelCase : List[str]=None ): '''simple docstring''' __A = np.random.default_rng(_lowerCamelCase ) __A = length __A = rng.normal(size=(length,) ).astype(np.floataa ) __A = a * self.x + b + rng.normal(scale=0.1, size=(length,) ).astype(np.floataa ) def __len__( self : str ): '''simple docstring''' return self.length def __getitem__( self : Dict, _lowerCamelCase : Optional[int] ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple=0, _lowerCamelCase : Any=0, _lowerCamelCase : Optional[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Optional[Any]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a[0] + self.b[0] class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : str, _lowerCamelCase : Optional[Any]=0, _lowerCamelCase : Any=0, _lowerCamelCase : List[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[str]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a + self.b def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase = 1_6 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __A = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __A = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __A = load_dataset('''csv''' , data_files=__UpperCamelCase ) __A = datasets['''train'''].unique('''label''' ) __A = {v: i for i, v in enumerate(__UpperCamelCase )} def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding='''max_length''' ) if "label" in examples: __A = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __A = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(__UpperCamelCase ): # 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(__UpperCamelCase , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' ) return tokenizer.pad(__UpperCamelCase , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __A = DataLoader(tokenized_datasets['''train'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2 ) __A = DataLoader(tokenized_datasets['''validation'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
266
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Optional[Any] = "bert-generation" def __init__( self , a__=50358 , a__=1024 , a__=24 , a__=16 , a__=4096 , a__="gelu" , a__=0.1 , a__=0.1 , a__=512 , a__=0.0_2 , a__=1e-12 , a__=0 , a__=2 , a__=1 , a__="absolute" , a__=True , **a__ , ): super().__init__(pad_token_id=a__ , bos_token_id=a__ , eos_token_id=a__ , **a__ ) _lowerCAmelCase : List[str] = vocab_size _lowerCAmelCase : Dict = hidden_size _lowerCAmelCase : int = num_hidden_layers _lowerCAmelCase : Dict = num_attention_heads _lowerCAmelCase : Tuple = hidden_act _lowerCAmelCase : Optional[int] = intermediate_size _lowerCAmelCase : str = hidden_dropout_prob _lowerCAmelCase : Optional[int] = attention_probs_dropout_prob _lowerCAmelCase : List[Any] = max_position_embeddings _lowerCAmelCase : Union[str, Any] = initializer_range _lowerCAmelCase : Optional[int] = layer_norm_eps _lowerCAmelCase : Optional[Any] = position_embedding_type _lowerCAmelCase : Optional[Any] = use_cache
44
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowercase_ = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' lowercase_ = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' lowercase_ = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), id='''references''' ), } ), ) def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[List[List[str]]], _lowerCamelCase : List[List[str]], _lowerCamelCase : int = 1, _lowerCamelCase : int = 4, ): '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCamelCase, hypotheses=_lowerCamelCase, min_len=_lowerCamelCase, max_len=_lowerCamelCase ) }
266
0
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=13 , _a=2 , _a=24 , _a=16 , _a=True , _a=True , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=10 , _a=0.02 , _a=None , _a=2 , _a=2 , ): __a = parent __a = batch_size __a = patch_size __a = max_length __a = num_mel_bins __a = is_training __a = use_labels __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 = type_sequence_label_size __a = initializer_range __a = scope __a = frequency_stride __a = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __a = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 __a = (self.max_length - self.patch_size) // self.time_stride + 1 __a = frequency_out_dimension * time_out_dimension __a = num_patches + 2 def __UpperCAmelCase ( self ): __a = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, input_values, labels def __UpperCAmelCase ( self ): return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_a , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def __UpperCAmelCase ( self , _a , _a , _a ): __a = ASTModel(config=_a ) model.to(_a ) model.eval() __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_values''': input_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : Optional[int] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) __UpperCAmelCase : Union[str, Any] = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : str = False __UpperCAmelCase : Any = False __UpperCAmelCase : List[str] = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def __UpperCAmelCase ( self ): __a = ASTModelTester(self ) __a = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def __UpperCAmelCase ( self ): pass def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def __UpperCAmelCase ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_a ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ['''input_values'''] self.assertListEqual(arg_names[:1] , _a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ASTModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowercase ( ) -> int: __a = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) __a , __a = torchaudio.load(lowerCAmelCase__ ) return audio, sampling_rate @require_torch @require_torchaudio class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCAmelCase ( self ): return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def __UpperCAmelCase ( self ): __a = self.default_feature_extractor __a = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(_a ) __a = self.default_feature_extractor __a , __a = prepare_audio() __a = audio.squeeze().numpy() __a = feature_extractor(_a , sampling_rate=_a , return_tensors='''pt''' ).to(_a ) # forward pass with torch.no_grad(): __a = model(**_a ) # verify the logits __a = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , _a ) __a = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1E-4 ) )
45
"""simple docstring""" class snake_case : '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : list[int] ): '''simple docstring''' __A = len(_lowerCamelCase ) __A = [0] * len_array if len_array > 0: __A = array[0] for i in range(1, _lowerCamelCase ): __A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : int ): '''simple docstring''' __A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_lowerCamelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
266
0
"""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 lowercase ( _UpperCAmelCase ): _SCREAMING_SNAKE_CASE = 'naver-clova-ix/donut-base-finetuned-docvqa' _SCREAMING_SNAKE_CASE = ( '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.' ) _SCREAMING_SNAKE_CASE = 'document_qa' _SCREAMING_SNAKE_CASE = AutoProcessor _SCREAMING_SNAKE_CASE = VisionEncoderDecoderModel _SCREAMING_SNAKE_CASE = ['image', 'text'] _SCREAMING_SNAKE_CASE = ['text'] def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: if not is_vision_available(): raise ValueError("""Pillow must be installed to use the DocumentQuestionAnsweringTool.""" ) super().__init__(*lowercase , **lowercase ) def _snake_case ( self , lowercase , lowercase ) -> Dict: lowerCAmelCase = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" lowerCAmelCase = task_prompt.replace("""{user_input}""" , lowercase ) lowerCAmelCase = self.pre_processor.tokenizer( lowercase , add_special_tokens=lowercase , return_tensors="""pt""" ).input_ids lowerCAmelCase = self.pre_processor(lowercase , return_tensors="""pt""" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def _snake_case ( self , lowercase ) -> Optional[Any]: 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=lowercase , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=lowercase , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=lowercase , ).sequences def _snake_case ( self , lowercase ) -> Union[str, Any]: lowerCAmelCase = self.pre_processor.batch_decode(lowercase )[0] lowerCAmelCase = sequence.replace(self.pre_processor.tokenizer.eos_token , """""" ) lowerCAmelCase = sequence.replace(self.pre_processor.tokenizer.pad_token , """""" ) lowerCAmelCase = re.sub(r"""<.*?>""" , """""" , lowercase , count=1 ).strip() # remove first task start token lowerCAmelCase = self.pre_processor.tokenajson(lowercase ) return sequence["answer"]
46
"""simple docstring""" import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ = logging.get_logger(__name__) lowercase_ = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } lowercase_ = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } lowercase_ = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCAmelCase ( ): """simple docstring""" __A = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __A = bs[:] __A = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 __A = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase , __UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = set() __A = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __A = char return pairs class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : Tuple = VOCAB_FILES_NAMES A_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : Dict, _lowerCamelCase : Optional[Any], _lowerCamelCase : List[str], _lowerCamelCase : Dict="replace", _lowerCamelCase : Any="<s>", _lowerCamelCase : Optional[int]="</s>", _lowerCamelCase : Dict="</s>", _lowerCamelCase : List[Any]="<s>", _lowerCamelCase : List[str]="<unk>", _lowerCamelCase : str="<pad>", _lowerCamelCase : Any="<mask>", _lowerCamelCase : Any=False, **_lowerCamelCase : Tuple, ): '''simple docstring''' __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else bos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else eos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else sep_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else cls_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else unk_token __A = 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 __A = 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: __A = json.load(_lowerCamelCase ) __A = {v: k for k, v in self.encoder.items()} __A = errors # how to handle errors in decoding __A = bytes_to_unicode() __A = {v: k for k, v in self.byte_encoder.items()} with open(_lowerCamelCase, encoding='''utf-8''' ) as merges_handle: __A = merges_handle.read().split('''\n''' )[1:-1] __A = [tuple(merge.split() ) for merge in bpe_merges] __A = dict(zip(_lowerCamelCase, range(len(_lowerCamelCase ) ) ) ) __A = {} __A = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __A = 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.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return len(self.encoder ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return dict(self.encoder, **self.added_tokens_encoder ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[Any] ): '''simple docstring''' if token in self.cache: return self.cache[token] __A = tuple(_lowerCamelCase ) __A = get_pairs(_lowerCamelCase ) if not pairs: return token while True: __A = min(_lowerCamelCase, key=lambda _lowerCamelCase : self.bpe_ranks.get(_lowerCamelCase, float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __A , __A = bigram __A = [] __A = 0 while i < len(_lowerCamelCase ): try: __A = word.index(_lowerCamelCase, _lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __A = 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 __A = tuple(_lowerCamelCase ) __A = new_word if len(_lowerCamelCase ) == 1: break else: __A = get_pairs(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = word return word def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Dict ): '''simple docstring''' __A = [] for token in re.findall(self.pat, _lowerCamelCase ): __A = ''''''.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 _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : Dict ): '''simple docstring''' return self.encoder.get(_lowerCamelCase, self.encoder.get(self.unk_token ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Any ): '''simple docstring''' return self.decoder.get(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' __A = ''''''.join(_lowerCamelCase ) __A = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''', errors=self.errors ) return text def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : str, _lowerCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __A = 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''' ) __A = 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!''' ) __A = token_index writer.write(''' '''.join(_lowerCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None, _lowerCamelCase : bool = 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 _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Union[str, Any], _lowerCamelCase : List[str]=False, **_lowerCamelCase : List[Any] ): '''simple docstring''' __A = 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()): __A = ''' ''' + text return (text, kwargs) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : "Conversation" ): '''simple docstring''' __A = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = self.encode(_lowerCamelCase ) if len(_lowerCamelCase ) > self.model_max_length: __A = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
266
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor lowerCamelCase : Optional[Any] = logging.get_logger(__name__) class A__ ( A__ ): def __init__( self : str , *_a : Optional[int] , **_a : Dict ) -> None: '''simple docstring''' warnings.warn( 'The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use FlavaImageProcessor instead.' , _a , ) super().__init__(*_a , **_a )
47
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging lowercase_ = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase ( ): """simple docstring""" __A = '''https://pypi.org/pypi/diffusers/json''' __A = json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys() return sorted(__UpperCamelCase , key=lambda __UpperCamelCase : version.Version(__UpperCamelCase ) ) def lowerCAmelCase ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__UpperCamelCase ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = Path(__UpperCamelCase ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" init_hf_modules() __A = Path(__UpperCamelCase ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import .xxx` __A = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Unique-ify return list(set(__UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = False __A = [module_file] __A = [] # Let's recurse through all relative imports while not no_change: __A = [] for f in files_to_check: new_imports.extend(get_relative_imports(__UpperCamelCase ) ) __A = Path(__UpperCamelCase ).parent __A = [str(module_path / m ) for m in new_imports] __A = [f for f in new_import_files if f not in all_relative_imports] __A = [f'{f}.py' for f in new_import_files] __A = len(__UpperCamelCase ) == 0 all_relative_imports.extend(__UpperCamelCase ) return all_relative_imports def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import xxx` __A = re.findall('''^\s*import\s+(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Only keep the top-level module __A = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all __A = list(set(__UpperCamelCase ) ) __A = [] for imp in imports: try: importlib.import_module(__UpperCamelCase ) except ImportError: missing_packages.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' f'{", ".join(__UpperCamelCase )}. Run `pip install {" ".join(__UpperCamelCase )}`' ) return get_relative_imports(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" __A = module_path.replace(os.path.sep , '''.''' ) __A = importlib.import_module(__UpperCamelCase ) if class_name is None: return find_pipeline_class(__UpperCamelCase ) return getattr(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" from ..pipelines import DiffusionPipeline __A = dict(inspect.getmembers(__UpperCamelCase , inspect.isclass ) ) __A = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __UpperCamelCase ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:' f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in' f' {loaded_module}.' ) __A = cls return pipeline_class def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , ): """simple docstring""" __A = str(__UpperCamelCase ) __A = os.path.join(__UpperCamelCase , __UpperCamelCase ) if os.path.isfile(__UpperCamelCase ): __A = module_file_or_url __A = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: __A = get_diffusers_versions() # cut ".dev0" __A = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: __A = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(f'Defaulting to latest_version: {revision}.' ) elif revision in available_versions: __A = f'v{revision}' elif revision == "main": __A = revision else: raise ValueError( f'`custom_revision`: {revision} does not exist. Please make sure to choose one of' f' {", ".join(available_versions + ["main"] )}.' ) # community pipeline on GitHub __A = COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase , pipeline=__UpperCamelCase ) try: __A = cached_download( __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = '''git''' __A = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise else: try: # Load from URL or cache if already cached __A = hf_hub_download( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise # Check we have all the requirements in our environment __A = check_imports(__UpperCamelCase ) # Now we move the module inside our cached dynamic modules. __A = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__UpperCamelCase ) __A = Path(__UpperCamelCase ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__UpperCamelCase , submodule_path / module_file ) for module_needed in modules_needed: __A = f'{module_needed}.py' shutil.copy(os.path.join(__UpperCamelCase , __UpperCamelCase ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__UpperCamelCase , __UpperCamelCase ): __A = use_auth_token elif use_auth_token is True: __A = HfFolder.get_token() else: __A = None __A = model_info(__UpperCamelCase , revision=__UpperCamelCase , token=__UpperCamelCase ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. __A = submodule_path / commit_hash __A = full_submodule + os.path.sep + commit_hash create_dynamic_module(__UpperCamelCase ) if not (submodule_path / module_file).exists(): shutil.copy(__UpperCamelCase , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __UpperCamelCase , f'{module_needed}.py' , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return os.path.join(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , **__UpperCamelCase , ): """simple docstring""" __A = get_cached_module_file( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return get_class_in_module(__UpperCamelCase , final_module.replace('''.py''' , '''''' ) )
266
0
from __future__ import annotations def A ( _SCREAMING_SNAKE_CASE ) -> bool: lowerCamelCase : int = str(_SCREAMING_SNAKE_CASE ) return len(_SCREAMING_SNAKE_CASE ) == 9 and set(_SCREAMING_SNAKE_CASE ) == set("123456789" ) def A ( ) -> int | None: for base_num in range(9999 ,4999 ,-1 ): lowerCamelCase : int = 10_0002 * base_num if is_9_pandigital(_SCREAMING_SNAKE_CASE ): return candidate for base_num in range(333 ,99 ,-1 ): lowerCamelCase : str = 100_2003 * base_num if is_9_pandigital(_SCREAMING_SNAKE_CASE ): return candidate return None if __name__ == "__main__": print(f'''{solution() = }''')
48
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[int] ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''], model_result['''ss'''] ): __A = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sgugger/tiny-distilbert-classification''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, only_pretrain_model=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, torchscript=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''', '''Cant do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, fpaa=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) # set architectures equal to `None` __A = None __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''', '''Can\'t do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], fpaa=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, save_to_csv=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], inference_time_csv_file=os.path.join(_lowerCamelCase, '''inf_time.csv''' ), train_memory_csv_file=os.path.join(_lowerCamelCase, '''train_mem.csv''' ), inference_memory_csv_file=os.path.join(_lowerCamelCase, '''inf_mem.csv''' ), train_time_csv_file=os.path.join(_lowerCamelCase, '''train_time.csv''' ), env_info_csv_file=os.path.join(_lowerCamelCase, '''env.csv''' ), multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''env.csv''' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_lowerCamelCase : List[Any] ): self.assertTrue(hasattr(_lowerCamelCase, '''sequential''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''cumulative''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''current''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], log_filename=os.path.join(_lowerCamelCase, '''log.txt''' ), log_print=_lowerCamelCase, trace_memory_line_by_line=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''log.txt''' ) ).exists() )
266
0
from typing import TYPE_CHECKING from ....utils import _LazyModule __snake_case :Any = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys __snake_case :str = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
49
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast 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 lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = PegasusTokenizer A_ : int = PegasusTokenizerFast A_ : Optional[Any] = True A_ : Union[str, Any] = True def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def _SCREAMING_SNAKE_CASE ( self : int, **_lowerCamelCase : List[Any] ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = '''</s>''' __A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ), _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ), _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], '''<pad>''' ) self.assertEqual(vocab_keys[1], '''</s>''' ) self.assertEqual(vocab_keys[-1], '''v''' ) self.assertEqual(len(_lowerCamelCase ), 11_03 ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 11_03 ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __A = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' __A = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 __A = '''To ensure a smooth flow of bank resolutions.''' __A = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 1_50, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # fmt: off __A = {'''input_ids''': [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 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], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 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]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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='''google/bigbird-pegasus-large-arxiv''', revision='''ba85d0851d708441f91440d509690f1ab6353415''', ) @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = PegasusTokenizer A_ : Union[str, Any] = PegasusTokenizerFast A_ : Any = True A_ : str = True def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase, offset=0, mask_token_sent=_lowerCamelCase, mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], **_lowerCamelCase : Dict ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : List[str] ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 10_00, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) __A = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase, [1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1], )
266
0
_UpperCAmelCase : Dict = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
50
"""simple docstring""" import re def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return [char.split() for char in re.split(r'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" try: __A = split_input(__UpperCamelCase ) if upper: __A = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __A = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return to_simple_case(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" try: __A = to_simple_case(__UpperCamelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''_''' ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
266
0
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 snake_case_ : Dict = logging.get_logger(__name__) snake_case_ : int = { "google/vit-base-patch16-224": "https://huggingface.co/vit-base-patch16-224/resolve/main/config.json", # See all ViT models at https://huggingface.co/models?filter=vit } class __snake_case ( a ): UpperCAmelCase__ : Dict = '''vit''' def __init__( self : Any , _snake_case : List[Any]=768 , _snake_case : Any=12 , _snake_case : List[Any]=12 , _snake_case : Union[str, Any]=3072 , _snake_case : Dict="gelu" , _snake_case : List[str]=0.0 , _snake_case : List[Any]=0.0 , _snake_case : Optional[Any]=0.0_2 , _snake_case : Tuple=1e-12 , _snake_case : Dict=224 , _snake_case : Tuple=16 , _snake_case : int=3 , _snake_case : List[str]=True , _snake_case : Optional[int]=16 , **_snake_case : Tuple , ): """simple docstring""" super().__init__(**_snake_case) 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_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = image_size UpperCAmelCase_ = patch_size UpperCAmelCase_ = num_channels UpperCAmelCase_ = qkv_bias UpperCAmelCase_ = encoder_stride class __snake_case ( a ): UpperCAmelCase__ : Optional[Any] = version.parse('''1.11''' ) @property def lowerCamelCase ( self : Optional[int]): """simple docstring""" return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ]) @property def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" return 1e-4
51
"""simple docstring""" from __future__ import annotations class snake_case : '''simple docstring''' def __init__( self : int, _lowerCamelCase : List[Any]=None ): '''simple docstring''' __A = data __A = None def __repr__( self : Union[str, Any] ): '''simple docstring''' __A = [] __A = self while temp: string_rep.append(f'{temp.data}' ) __A = temp.next return "->".join(_lowerCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not elements_list: raise Exception('''The Elements List is empty''' ) __A = __A = Node(elements_list[0] ) for i in range(1 , len(__UpperCamelCase ) ): __A = Node(elements_list[i] ) __A = current.next return head def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if head_node is not None and isinstance(__UpperCamelCase , __UpperCamelCase ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase ( ): """simple docstring""" from doctest import testmod testmod() __A = make_linked_list([1_4, 5_2, 1_4, 1_2, 4_3] ) print('''Linked List:''' ) print(__UpperCamelCase ) print('''Elements in Reverse:''' ) print_reverse(__UpperCamelCase ) if __name__ == "__main__": main()
266
0
def A_ ( _lowerCAmelCase ) -> str: UpperCamelCase : Tuple = 0 # if input_string is "aba" than new_input_string become "a|b|a" UpperCamelCase : Any = "" UpperCamelCase : List[Any] = "" # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(_lowerCAmelCase ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring UpperCamelCase , UpperCamelCase : List[str] = 0, 0 # length[i] shows the length of palindromic substring with center i UpperCamelCase : Any = [1 for i in range(len(_lowerCAmelCase ) )] # for each character in new_string find corresponding palindromic string UpperCamelCase : Optional[Any] = 0 for j in range(len(_lowerCAmelCase ) ): UpperCamelCase : str = 1 if j > r else min(length[l + r - j] // 2 , r - j + 1 ) while ( j - k >= 0 and j + k < len(_lowerCAmelCase ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 UpperCamelCase : Optional[Any] = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: UpperCamelCase : List[str] = j - k + 1 # noqa: E741 UpperCamelCase : Union[str, Any] = j + k - 1 # update max_length and start position if max_length < length[j]: UpperCamelCase : Union[str, Any] = length[j] UpperCamelCase : List[Any] = j # create that string UpperCamelCase : Optional[Any] = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
52
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : int = ["input_features", "attention_mask"] def __init__( self : Optional[Any], _lowerCamelCase : Union[str, Any]=80, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Any=80, _lowerCamelCase : List[str]=0.0, _lowerCamelCase : int=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Optional[int]=True, **_lowerCamelCase : List[str], ): '''simple docstring''' super().__init__(feature_size=_lowerCamelCase, sampling_rate=_lowerCamelCase, padding_value=_lowerCamelCase, **_lowerCamelCase ) __A = num_mel_bins __A = do_ceptral_normalize __A = normalize_means __A = normalize_vars __A = True def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : np.ndarray, ): '''simple docstring''' __A = waveform * (2**15) # Kaldi compliance: 16-bit signed integers __A = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ) __A = ta_kaldi.fbank(_lowerCamelCase, num_mel_bins=self.num_mel_bins, sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray, _lowerCamelCase : int, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : float = 0.0, ): '''simple docstring''' # make sure we normalize float32 arrays if normalize_means: __A = x[:input_length].mean(axis=0 ) __A = np.subtract(_lowerCamelCase, _lowerCamelCase ) if normalize_vars: __A = x[:input_length].std(axis=0 ) __A = np.divide(_lowerCamelCase, _lowerCamelCase ) if input_length < x.shape[0]: __A = padding_value # make sure array is in float32 __A = x.astype(np.floataa ) return x def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[np.ndarray], _lowerCamelCase : Optional[np.ndarray] = None ): '''simple docstring''' __A = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_lowerCamelCase, _lowerCamelCase, self.normalize_means, self.normalize_vars, self.padding_value ) for x, n in zip(_lowerCamelCase, _lowerCamelCase ) ] def __call__( self : Optional[Any], _lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], _lowerCamelCase : Union[bool, str, PaddingStrategy] = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : bool = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[Union[str, TensorType]] = None, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[bool] = None, **_lowerCamelCase : Optional[Any], ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __A = isinstance(_lowerCamelCase, np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __A = is_batched_numpy or ( isinstance(_lowerCamelCase, (list, tuple) ) and (isinstance(raw_speech[0], (np.ndarray, tuple, list) )) ) if is_batched: __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_lowerCamelCase, np.ndarray ): __A = np.asarray(_lowerCamelCase, dtype=np.floataa ) elif isinstance(_lowerCamelCase, np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __A = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __A = [raw_speech] # extract fbank features __A = [self._extract_fbank_features(_lowerCamelCase ) for waveform in raw_speech] # convert into correct format for padding __A = BatchFeature({'''input_features''': features} ) __A = self.pad( _lowerCamelCase, padding=_lowerCamelCase, max_length=_lowerCamelCase, truncation=_lowerCamelCase, pad_to_multiple_of=_lowerCamelCase, return_attention_mask=_lowerCamelCase, **_lowerCamelCase, ) # make sure list is in array format __A = padded_inputs.get('''input_features''' ) if isinstance(input_features[0], _lowerCamelCase ): __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for feature in input_features] __A = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __A = [np.asarray(_lowerCamelCase, dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: __A = ( np.array(_lowerCamelCase, dtype=np.intaa ) if self._get_padding_strategies(_lowerCamelCase, max_length=_lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) __A = self.normalize( padded_inputs['''input_features'''], attention_mask=_lowerCamelCase ) if return_tensors is not None: __A = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs
266
0
'''simple docstring''' def lowercase__ ( __lowercase : int = 50000000 ) -> int: """simple docstring""" __UpperCamelCase = set() __UpperCamelCase = int((limit - 24) ** (1 / 2) ) __UpperCamelCase = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , __lowercase ) ) ) for primea in primes: __UpperCamelCase = primea * primea for primea in primes: __UpperCamelCase = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: __UpperCamelCase = primea * primea * primea * primea __UpperCamelCase = square + cube + tetr if total >= limit: break ret.add(__lowercase ) return len(__lowercase ) if __name__ == "__main__": print(f'{solution() = }')
53
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : Optional[Any], _lowerCamelCase : Union[str, Any]=13, _lowerCamelCase : Any=3, _lowerCamelCase : Optional[int]=2_24, _lowerCamelCase : str=30, _lowerCamelCase : Dict=4_00, _lowerCamelCase : Union[str, Any]=True, _lowerCamelCase : Any=None, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Any=[0.5, 0.5, 0.5], _lowerCamelCase : List[str]=[0.5, 0.5, 0.5], ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_normalize __A = image_mean __A = image_std def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = ViTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = EfficientFormerImageProcessorTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), )
266
0
"""simple docstring""" import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SwinConfig() __SCREAMING_SNAKE_CASE = swin_name.split("_" ) __SCREAMING_SNAKE_CASE = name_split[1] __SCREAMING_SNAKE_CASE = int(name_split[4] ) __SCREAMING_SNAKE_CASE = int(name_split[3][-1] ) if model_size == "tiny": __SCREAMING_SNAKE_CASE = 96 __SCREAMING_SNAKE_CASE = (2, 2, 6, 2) __SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": __SCREAMING_SNAKE_CASE = 96 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": __SCREAMING_SNAKE_CASE = 128 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: __SCREAMING_SNAKE_CASE = 192 __SCREAMING_SNAKE_CASE = (2, 2, 18, 2) __SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "in22k" in swin_name: __SCREAMING_SNAKE_CASE = 2_1841 else: __SCREAMING_SNAKE_CASE = 1000 __SCREAMING_SNAKE_CASE = "huggingface/label-files" __SCREAMING_SNAKE_CASE = "imagenet-1k-id2label.json" __SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) , "r" ) ) __SCREAMING_SNAKE_CASE = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = idalabel __SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = img_size __SCREAMING_SNAKE_CASE = num_classes __SCREAMING_SNAKE_CASE = embed_dim __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = num_heads __SCREAMING_SNAKE_CASE = window_size return config def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' 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 "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: __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 == "norm.weight": __SCREAMING_SNAKE_CASE = "layernorm.weight" if name == "norm.bias": __SCREAMING_SNAKE_CASE = "layernorm.bias" if "head" in name: __SCREAMING_SNAKE_CASE = name.replace("head" , "classifier" ) else: __SCREAMING_SNAKE_CASE = "swin." + name return name def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): __SCREAMING_SNAKE_CASE = orig_state_dict.pop(lowerCAmelCase_ ) if "mask" in key: continue elif "qkv" in key: __SCREAMING_SNAKE_CASE = key.split("." ) __SCREAMING_SNAKE_CASE = int(key_split[1] ) __SCREAMING_SNAKE_CASE = int(key_split[3] ) __SCREAMING_SNAKE_CASE = model.swin.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: ] else: __SCREAMING_SNAKE_CASE = val return orig_state_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = timm.create_model(lowerCAmelCase_ , pretrained=lowerCAmelCase_ ) timm_model.eval() __SCREAMING_SNAKE_CASE = get_swin_config(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = SwinForImageClassification(lowerCAmelCase_ ) model.eval() __SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = "http://images.cocodataset.org/val2017/000000039769.jpg" __SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("microsoft/{}".format(swin_name.replace("_" , "-" ) ) ) __SCREAMING_SNAKE_CASE = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) __SCREAMING_SNAKE_CASE = image_processor(images=lowerCAmelCase_ , return_tensors="pt" ) __SCREAMING_SNAKE_CASE = timm_model(inputs["pixel_values"] ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ).logits assert torch.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1E-3 ) print(f"""Saving model {swin_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 __name__ == "__main__": a__ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swin_name''', default='''swin_tiny_patch4_window7_224''', type=str, help='''Name of the Swin 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.''' ) a__ : Union[str, Any] = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
54
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' def __init__( self : Optional[int], *_lowerCamelCase : Union[str, Any], **_lowerCamelCase : Dict ): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''', _lowerCamelCase, ) super().__init__(*_lowerCamelCase, **_lowerCamelCase )
266
0
'''simple docstring''' import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError("""At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training""") # TF training parameters a_ : Optional[Any] = False a_ : int = False def __snake_case ( UpperCAmelCase_ : Namespace ): return TrainCommand(UpperCAmelCase_ ) class snake_case ( lowercase ): """simple docstring""" @staticmethod def snake_case ( UpperCamelCase ): """simple docstring""" lowerCamelCase_ = parser.add_parser("train" , help="CLI tool to train a model on a task." ) train_parser.add_argument( "--train_data" , type=UpperCamelCase , required=UpperCamelCase , help="path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences." , ) train_parser.add_argument( "--column_label" , type=UpperCamelCase , default=0 , help="Column of the dataset csv file with example labels." ) train_parser.add_argument( "--column_text" , type=UpperCamelCase , default=1 , help="Column of the dataset csv file with example texts." ) train_parser.add_argument( "--column_id" , type=UpperCamelCase , default=2 , help="Column of the dataset csv file with example ids." ) train_parser.add_argument( "--skip_first_row" , action="store_true" , help="Skip the first row of the csv file (headers)." ) train_parser.add_argument("--validation_data" , type=UpperCamelCase , default="" , help="path to validation dataset." ) train_parser.add_argument( "--validation_split" , type=UpperCamelCase , default=0.1 , help="if validation dataset is not provided, fraction of train dataset to use as validation dataset." , ) train_parser.add_argument("--output" , type=UpperCamelCase , default="./" , help="path to saved the trained model." ) train_parser.add_argument( "--task" , type=UpperCamelCase , default="text_classification" , help="Task to train the model on." ) train_parser.add_argument( "--model" , type=UpperCamelCase , default="bert-base-uncased" , help="Model's name or path to stored model." ) train_parser.add_argument("--train_batch_size" , type=UpperCamelCase , default=32 , help="Batch size for training." ) train_parser.add_argument("--valid_batch_size" , type=UpperCamelCase , default=64 , help="Batch size for validation." ) train_parser.add_argument("--learning_rate" , type=UpperCamelCase , default=3e-5 , help="Learning rate." ) train_parser.add_argument("--adam_epsilon" , type=UpperCamelCase , default=1e-08 , help="Epsilon for Adam optimizer." ) train_parser.set_defaults(func=UpperCamelCase ) def __init__( self , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = logging.get_logger("transformers-cli/training" ) lowerCamelCase_ = "tf" if is_tf_available() else "torch" os.makedirs(args.output , exist_ok=UpperCamelCase ) lowerCamelCase_ = args.output lowerCamelCase_ = args.column_label lowerCamelCase_ = args.column_text lowerCamelCase_ = args.column_id self.logger.info(f'''Loading {args.task} pipeline for {args.model}''' ) if args.task == "text_classification": lowerCamelCase_ = TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'''Loading dataset from {args.train_data}''' ) lowerCamelCase_ = Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) lowerCamelCase_ = None if args.validation_data: self.logger.info(f'''Loading validation dataset from {args.validation_data}''' ) lowerCamelCase_ = Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) lowerCamelCase_ = args.validation_split lowerCamelCase_ = args.train_batch_size lowerCamelCase_ = args.valid_batch_size lowerCamelCase_ = args.learning_rate lowerCamelCase_ = args.adam_epsilon def snake_case ( self ): """simple docstring""" if self.framework == "tf": return self.run_tf() return self.run_torch() def snake_case ( self ): """simple docstring""" raise NotImplementedError def snake_case ( self ): """simple docstring""" self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
55
"""simple docstring""" 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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : List[Any]=7, _lowerCamelCase : int=3, _lowerCamelCase : Optional[Any]=18, _lowerCamelCase : Any=30, _lowerCamelCase : str=4_00, _lowerCamelCase : int=True, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str=True, ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = apply_ocr def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[int] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = LayoutLMvaImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = 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 : Union[str, Any] ): '''simple docstring''' __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'''height''': 18, '''width''': 18} ) __A = 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 : Optional[Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = 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 __A = 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 : Any ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = 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 __A = 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 __A = 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 __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = 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 __A = 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 __A = 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 : List[str] ): '''simple docstring''' # with apply_OCR = True __A = LayoutLMvaImageProcessor() from datasets import load_dataset __A = load_dataset('''hf-internal-testing/fixtures_docvqa''', split='''test''' ) __A = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ), len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __A = [['''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 __A = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words, _lowerCamelCase ) self.assertListEqual(encoding.boxes, _lowerCamelCase ) # with apply_OCR = False __A = LayoutLMvaImageProcessor(apply_ocr=_lowerCamelCase ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) )
266
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() a : List[Any] = logging.get_logger(__name__) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase=False ) -> List[Any]: '''simple docstring''' snake_case_ = [] # fmt: off # stem: rename_keys.append(('''cls_token''', '''vit.embeddings.cls_token''') ) rename_keys.append(('''pos_embed''', '''vit.embeddings.position_embeddings''') ) rename_keys.append(('''patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias''') ) # backbone rename_keys.append(('''patch_embed.backbone.stem.conv.weight''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight''') ) rename_keys.append(('''patch_embed.backbone.stem.norm.weight''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight''') ) rename_keys.append(('''patch_embed.backbone.stem.norm.bias''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias''') ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight") ) rename_keys.append((F"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias", F"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias") ) # transformer encoder 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") ) 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" snake_case_ = [(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'''), ] ) # fmt: on return rename_keys def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase=False ) -> Optional[Any]: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: snake_case_ = '''''' else: snake_case_ = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ = state_dict.pop(F"blocks.{i}.attn.qkv.weight" ) snake_case_ = state_dict.pop(F"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict snake_case_ = in_proj_weight[ : config.hidden_size, : ] snake_case_ = in_proj_bias[: config.hidden_size] snake_case_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ = in_proj_weight[ -config.hidden_size :, : ] snake_case_ = in_proj_bias[-config.hidden_size :] def __magic_name__ ( __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' snake_case_ = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(__UpperCAmelCase, __UpperCAmelCase ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' snake_case_ = dct.pop(__UpperCAmelCase ) snake_case_ = val def __magic_name__ ( ) -> Tuple: '''simple docstring''' snake_case_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' snake_case_ = Image.open(requests.get(__UpperCAmelCase, stream=__UpperCAmelCase ).raw ) return im @torch.no_grad() def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase=False ) -> int: '''simple docstring''' snake_case_ = BitConfig( global_padding='''same''', layer_type='''bottleneck''', depths=(3, 4, 9), out_features=['''stage3'''], embedding_dynamic_padding=__UpperCAmelCase, ) snake_case_ = ViTHybridConfig(backbone_config=__UpperCAmelCase, image_size=384, num_labels=1000 ) snake_case_ = False # load original model from timm snake_case_ = timm.create_model(__UpperCAmelCase, pretrained=__UpperCAmelCase ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case_ = timm_model.state_dict() if base_model: remove_classification_head_(__UpperCAmelCase ) snake_case_ = create_rename_keys(__UpperCAmelCase, __UpperCAmelCase ) for src, dest in rename_keys: rename_key(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) read_in_q_k_v(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) snake_case_ = '''huggingface/label-files''' snake_case_ = '''imagenet-1k-id2label.json''' snake_case_ = json.load(open(hf_hub_download(__UpperCAmelCase, __UpperCAmelCase, repo_type='''dataset''' ), '''r''' ) ) snake_case_ = {int(__UpperCAmelCase ): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": snake_case_ = ViTHybridModel(__UpperCAmelCase ).eval() else: snake_case_ = ViTHybridForImageClassification(__UpperCAmelCase ).eval() model.load_state_dict(__UpperCAmelCase ) # create image processor snake_case_ = create_transform(**resolve_data_config({}, model=__UpperCAmelCase ) ) snake_case_ = transform.transforms snake_case_ = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } snake_case_ = ViTHybridImageProcessor( do_resize=__UpperCAmelCase, size={'''shortest_edge''': timm_transforms[0].size}, resample=pillow_resamplings[timm_transforms[0].interpolation.value], do_center_crop=__UpperCAmelCase, crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]}, do_normalize=__UpperCAmelCase, image_mean=timm_transforms[-1].mean.tolist(), image_std=timm_transforms[-1].std.tolist(), ) snake_case_ = prepare_img() snake_case_ = transform(__UpperCAmelCase ).unsqueeze(0 ) snake_case_ = processor(__UpperCAmelCase, return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(__UpperCAmelCase, __UpperCAmelCase ) # verify logits with torch.no_grad(): snake_case_ = model(__UpperCAmelCase ) snake_case_ = outputs.logits print('''Predicted class:''', logits.argmax(-1 ).item() ) if base_model: snake_case_ = timm_model.forward_features(__UpperCAmelCase ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(__UpperCAmelCase, outputs.pooler_output, atol=1e-3 ) else: snake_case_ = timm_model(__UpperCAmelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__UpperCAmelCase, outputs.logits, atol=1e-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(__UpperCAmelCase ).mkdir(exist_ok=__UpperCAmelCase ) print(F"Saving model {vit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__UpperCAmelCase ) print(F"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(__UpperCAmelCase ) if push_to_hub: print(F"Pushing model and processor to the hub {vit_name}" ) model.push_to_hub(F"ybelkada/{vit_name}" ) processor.push_to_hub(F"ybelkada/{vit_name}" ) if __name__ == "__main__": a : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_r50_s16_384', type=str, help='Name of the hybrid 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.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to upload the model to the HuggingFace hub.' ) a : Optional[int] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
56
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): '''simple docstring''' A_ : List[str] = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = False ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = True ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def lowerCAmelCase ( ): """simple docstring""" try: hide_cursor() yield finally: show_cursor()
266
0
"""simple docstring""" import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort A : int = logging.get_logger(__name__) A : Optional[int] = { "tensor(bool)": np.bool_, "tensor(int8)": np.inta, "tensor(uint8)": np.uinta, "tensor(int16)": np.intaa, "tensor(uint16)": np.uintaa, "tensor(int32)": np.intaa, "tensor(uint32)": np.uintaa, "tensor(int64)": np.intaa, "tensor(uint64)": np.uintaa, "tensor(float16)": np.floataa, "tensor(float)": np.floataa, "tensor(double)": np.floataa, } class _UpperCamelCase : '''simple docstring''' def __init__( self , __a=None , **__a ): logger.info("`diffusers.OnnxRuntimeModel` is experimental and might change in the future." ) __lowerCAmelCase = model __lowerCAmelCase = kwargs.get("model_save_dir" , __a ) __lowerCAmelCase = kwargs.get("latest_model_name" , __a ) def __call__( self , **__a ): __lowerCAmelCase = {k: np.array(__a ) for k, v in kwargs.items()} return self.model.run(__a , __a ) @staticmethod def snake_case ( __a , __a=None , __a=None ): if provider is None: logger.info("No onnxruntime provider specified, using CPUExecutionProvider" ) __lowerCAmelCase = "CPUExecutionProvider" return ort.InferenceSession(__a , providers=[provider] , sess_options=__a ) def snake_case ( self , __a , __a = None , **__a ): __lowerCAmelCase = file_name if file_name is not None else ONNX_WEIGHTS_NAME __lowerCAmelCase = self.model_save_dir.joinpath(self.latest_model_name ) __lowerCAmelCase = Path(__a ).joinpath(__a ) try: shutil.copyfile(__a , __a ) except shutil.SameFileError: pass # copy external weights (for models >2GB) __lowerCAmelCase = self.model_save_dir.joinpath(__a ) if src_path.exists(): __lowerCAmelCase = Path(__a ).joinpath(__a ) try: shutil.copyfile(__a , __a ) except shutil.SameFileError: pass def snake_case ( self , __a , **__a , ): if os.path.isfile(__a ): logger.error(f"Provided path ({save_directory}) should be a directory, not a file" ) return os.makedirs(__a , exist_ok=__a ) # saving model weights/files self._save_pretrained(__a , **__a ) @classmethod def snake_case ( cls , __a , __a = None , __a = None , __a = False , __a = None , __a = None , __a = None , __a = None , **__a , ): __lowerCAmelCase = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(__a ): __lowerCAmelCase = OnnxRuntimeModel.load_model( os.path.join(__a , __a ) , provider=__a , sess_options=__a ) __lowerCAmelCase = Path(__a ) # load model from hub else: # download model __lowerCAmelCase = hf_hub_download( repo_id=__a , filename=__a , use_auth_token=__a , revision=__a , cache_dir=__a , force_download=__a , ) __lowerCAmelCase = Path(__a ).parent __lowerCAmelCase = Path(__a ).name __lowerCAmelCase = OnnxRuntimeModel.load_model(__a , provider=__a , sess_options=__a ) return cls(model=__a , **__a ) @classmethod def snake_case ( cls , __a , __a = True , __a = None , __a = None , **__a , ): __lowerCAmelCase = None if len(str(__a ).split("@" ) ) == 2: __lowerCAmelCase , __lowerCAmelCase = model_id.split("@" ) return cls._from_pretrained( model_id=__a , revision=__a , cache_dir=__a , force_download=__a , use_auth_token=__a , **__a , )
57
"""simple docstring""" import argparse import struct import unittest class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : bytes ): '''simple docstring''' __A = data # Initialize hash values __A = [ 0X6a_09e_667, 0Xbb_67a_e85, 0X3c_6ef_372, 0Xa5_4ff_53a, 0X51_0e5_27f, 0X9b_056_88c, 0X1f_83d_9ab, 0X5b_e0c_d19, ] # Initialize round constants __A = [ 0X42_8a2_f98, 0X71_374_491, 0Xb5_c0f_bcf, 0Xe9_b5d_ba5, 0X39_56c_25b, 0X59_f11_1f1, 0X92_3f8_2a4, 0Xab_1c5_ed5, 0Xd8_07a_a98, 0X12_835_b01, 0X24_318_5be, 0X55_0c7_dc3, 0X72_be5_d74, 0X80_deb_1fe, 0X9b_dc0_6a7, 0Xc1_9bf_174, 0Xe4_9b6_9c1, 0Xef_be4_786, 0X0f_c19_dc6, 0X24_0ca_1cc, 0X2d_e92_c6f, 0X4a_748_4aa, 0X5c_b0a_9dc, 0X76_f98_8da, 0X98_3e5_152, 0Xa8_31c_66d, 0Xb0_032_7c8, 0Xbf_597_fc7, 0Xc6_e00_bf3, 0Xd5_a79_147, 0X06_ca6_351, 0X14_292_967, 0X27_b70_a85, 0X2e_1b2_138, 0X4d_2c6_dfc, 0X53_380_d13, 0X65_0a7_354, 0X76_6a0_abb, 0X81_c2c_92e, 0X92_722_c85, 0Xa2_bfe_8a1, 0Xa8_1a6_64b, 0Xc2_4b8_b70, 0Xc7_6c5_1a3, 0Xd1_92e_819, 0Xd6_990_624, 0Xf4_0e3_585, 0X10_6aa_070, 0X19_a4c_116, 0X1e_376_c08, 0X27_487_74c, 0X34_b0b_cb5, 0X39_1c0_cb3, 0X4e_d8a_a4a, 0X5b_9cc_a4f, 0X68_2e6_ff3, 0X74_8f8_2ee, 0X78_a56_36f, 0X84_c87_814, 0X8c_c70_208, 0X90_bef_ffa, 0Xa4_506_ceb, 0Xbe_f9a_3f7, 0Xc6_717_8f2, ] __A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : bytes ): '''simple docstring''' __A = b'''\x80''' + (b'''\x00''' * (63 - (len(_lowerCamelCase ) + 8) % 64)) __A = struct.pack('''>Q''', (len(_lowerCamelCase ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' # Convert into blocks of 64 bytes __A = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data ), 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __A = list(struct.unpack('''>16L''', _lowerCamelCase ) ) # add 48 0-ed integers words += [0] * 48 __A , __A , __A , __A , __A , __A , __A , __A = self.hashes for index in range(0, 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __A = ( self.ror(words[index - 15], 7 ) ^ self.ror(words[index - 15], 18 ) ^ (words[index - 15] >> 3) ) __A = ( self.ror(words[index - 2], 17 ) ^ self.ror(words[index - 2], 19 ) ^ (words[index - 2] >> 10) ) __A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X100_000_000 # Compression __A = self.ror(_lowerCamelCase, 6 ) ^ self.ror(_lowerCamelCase, 11 ) ^ self.ror(_lowerCamelCase, 25 ) __A = (e & f) ^ ((~e & 0Xff_fff_fff) & g) __A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X100_000_000 __A = self.ror(_lowerCamelCase, 2 ) ^ self.ror(_lowerCamelCase, 13 ) ^ self.ror(_lowerCamelCase, 22 ) __A = (a & b) ^ (a & c) ^ (b & c) __A = (sa + maj) % 0X100_000_000 __A , __A , __A , __A , __A , __A , __A , __A = ( g, f, e, ((d + tempa) % 0X100_000_000), c, b, a, ((tempa + tempa) % 0X100_000_000), ) __A = [a, b, c, d, e, f, g, h] # Modify final values __A = [ ((element + mutated_hash_values[index]) % 0X100_000_000) for index, element in enumerate(self.hashes ) ] __A = ''''''.join([hex(_lowerCamelCase )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' return 0Xff_fff_fff & (value << (32 - rotations)) | (value >> rotations) class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' import hashlib __A = bytes('''Test String''', '''utf-8''' ) self.assertEqual(SHAaaa(_lowerCamelCase ).hash, hashlib.shaaaa(_lowerCamelCase ).hexdigest() ) def lowerCAmelCase ( ): """simple docstring""" import doctest doctest.testmod() __A = argparse.ArgumentParser() parser.add_argument( '''-s''' , '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument( '''-f''' , '''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) __A = parser.parse_args() __A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: __A = f.read() else: __A = bytes(__UpperCamelCase , '''utf-8''' ) print(SHAaaa(__UpperCamelCase ).hash ) if __name__ == "__main__": main()
266
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available lowercase_ = { """configuration_audio_spectrogram_transformer""": [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ASTConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ASTForAudioClassification""", """ASTModel""", """ASTPreTrainedModel""", ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""ASTFeatureExtractor"""] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowercase_ = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' lowercase_ = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' lowercase_ = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, homepage='''https://github.com/krishnap25/mauve''', inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''string''', id='''sequence''' ), '''references''': datasets.Value('''string''', id='''sequence''' ), } ), codebase_urls=['''https://github.com/krishnap25/mauve'''], reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ], ) def _SCREAMING_SNAKE_CASE ( self : int, _lowerCamelCase : str, _lowerCamelCase : Optional[Any], _lowerCamelCase : Any=None, _lowerCamelCase : Tuple=None, _lowerCamelCase : Optional[Any]=None, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str="auto", _lowerCamelCase : Union[str, Any]=-1, _lowerCamelCase : List[str]=0.9, _lowerCamelCase : int=5, _lowerCamelCase : Tuple=5_00, _lowerCamelCase : Union[str, Any]="gpt2-large", _lowerCamelCase : int=-1, _lowerCamelCase : Union[str, Any]=10_24, _lowerCamelCase : Union[str, Any]=25, _lowerCamelCase : str=5, _lowerCamelCase : Any=True, _lowerCamelCase : Union[str, Any]=25, ): '''simple docstring''' __A = compute_mauve( p_text=_lowerCamelCase, q_text=_lowerCamelCase, p_features=_lowerCamelCase, q_features=_lowerCamelCase, p_tokens=_lowerCamelCase, q_tokens=_lowerCamelCase, num_buckets=_lowerCamelCase, pca_max_data=_lowerCamelCase, kmeans_explained_var=_lowerCamelCase, kmeans_num_redo=_lowerCamelCase, kmeans_max_iter=_lowerCamelCase, featurize_model_name=_lowerCamelCase, device_id=_lowerCamelCase, max_text_length=_lowerCamelCase, divergence_curve_discretization_size=_lowerCamelCase, mauve_scaling_factor=_lowerCamelCase, verbose=_lowerCamelCase, seed=_lowerCamelCase, ) return out
266
0
import unittest from transformers import XLMConfig, 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 ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase : def __init__(self : Optional[Any] , snake_case__ : str , snake_case__ : Optional[Any]=13 , snake_case__ : List[str]=7 , snake_case__ : Dict=True , snake_case__ : str=True , snake_case__ : Optional[Any]=True , snake_case__ : Tuple=True , snake_case__ : Union[str, Any]=True , snake_case__ : Optional[int]=False , snake_case__ : Tuple=False , snake_case__ : Tuple=False , snake_case__ : List[str]=2 , snake_case__ : List[Any]=99 , snake_case__ : List[Any]=0 , snake_case__ : List[Any]=32 , snake_case__ : Tuple=5 , snake_case__ : int=4 , snake_case__ : str=0.1 , snake_case__ : Dict=0.1 , snake_case__ : Optional[Any]=5_12 , snake_case__ : Optional[Any]=2 , snake_case__ : Tuple=0.02 , snake_case__ : Optional[int]=2 , snake_case__ : Union[str, Any]=4 , snake_case__ : int="last" , snake_case__ : str=True , snake_case__ : Dict=None , snake_case__ : int=0 , ) -> List[Any]: '''simple docstring''' snake_case : Tuple = parent snake_case : List[str] = batch_size snake_case : Dict = seq_length snake_case : List[str] = is_training snake_case : Dict = use_input_lengths snake_case : List[str] = use_token_type_ids snake_case : Dict = use_labels snake_case : List[Any] = gelu_activation snake_case : Any = sinusoidal_embeddings snake_case : Tuple = causal snake_case : str = asm snake_case : Tuple = n_langs snake_case : int = vocab_size snake_case : Any = n_special snake_case : List[Any] = hidden_size snake_case : Optional[int] = num_hidden_layers snake_case : List[Any] = num_attention_heads snake_case : Any = hidden_dropout_prob snake_case : Tuple = attention_probs_dropout_prob snake_case : Dict = max_position_embeddings snake_case : int = type_sequence_label_size snake_case : List[str] = initializer_range snake_case : str = num_labels snake_case : Optional[Any] = num_choices snake_case : Union[str, Any] = summary_type snake_case : Any = use_proj snake_case : int = scope snake_case : Optional[Any] = bos_token_id def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> Optional[int]: '''simple docstring''' snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case : Tuple = None if self.use_input_lengths: snake_case : List[str] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length snake_case : Any = None if self.use_token_type_ids: snake_case : str = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) snake_case : Optional[int] = None snake_case : Optional[int] = None snake_case : Union[str, Any] = None if self.use_labels: snake_case : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case : Union[str, Any] = ids_tensor([self.batch_size] , 2 ).float() snake_case : int = ids_tensor([self.batch_size] , self.num_choices ) snake_case : List[Any] = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _SCREAMING_SNAKE_CASE (self : List[str] ) -> int: '''simple docstring''' return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def _SCREAMING_SNAKE_CASE (self : Tuple , snake_case__ : Any , snake_case__ : List[str] , snake_case__ : str , snake_case__ : List[Any] , snake_case__ : List[Any] , snake_case__ : Optional[int] , snake_case__ : int , snake_case__ : Optional[Any] , snake_case__ : str , ) -> Optional[Any]: '''simple docstring''' snake_case : str = XLMModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() snake_case : Dict = model(snake_case__ , lengths=snake_case__ , langs=snake_case__ ) snake_case : Optional[Any] = model(snake_case__ , langs=snake_case__ ) snake_case : Union[str, Any] = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _SCREAMING_SNAKE_CASE (self : Optional[int] , snake_case__ : Optional[Any] , snake_case__ : Optional[int] , snake_case__ : Tuple , snake_case__ : Optional[Any] , snake_case__ : Optional[int] , snake_case__ : List[str] , snake_case__ : Any , snake_case__ : Any , snake_case__ : List[Any] , ) -> str: '''simple docstring''' snake_case : Union[str, Any] = XLMWithLMHeadModel(snake_case__ ) model.to(snake_case__ ) model.eval() snake_case : str = model(snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : List[Any] , snake_case__ : Any , snake_case__ : List[str] , snake_case__ : Optional[Any] , snake_case__ : Tuple , snake_case__ : str , snake_case__ : int , snake_case__ : int , ) -> Optional[int]: '''simple docstring''' snake_case : int = XLMForQuestionAnsweringSimple(snake_case__ ) model.to(snake_case__ ) model.eval() snake_case : int = model(snake_case__ ) snake_case : Optional[int] = model(snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ ) snake_case : Tuple = outputs 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 : int , snake_case__ : int , snake_case__ : Optional[Any] , snake_case__ : Dict , snake_case__ : Optional[Any] , snake_case__ : Union[str, Any] , snake_case__ : Any , snake_case__ : List[Any] , snake_case__ : Dict , snake_case__ : Tuple , ) -> str: '''simple docstring''' snake_case : int = XLMForQuestionAnswering(snake_case__ ) model.to(snake_case__ ) model.eval() snake_case : int = model(snake_case__ ) snake_case : Optional[int] = model( snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , cls_index=snake_case__ , is_impossible=snake_case__ , p_mask=snake_case__ , ) snake_case : int = model( snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , cls_index=snake_case__ , is_impossible=snake_case__ , ) ((snake_case) , ) : List[Any] = result_with_labels.to_tuple() snake_case : Optional[Any] = model(snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ ) ((snake_case) , ) : int = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def _SCREAMING_SNAKE_CASE (self : int , snake_case__ : Dict , snake_case__ : Any , snake_case__ : Any , snake_case__ : int , snake_case__ : Optional[int] , snake_case__ : Union[str, Any] , snake_case__ : int , snake_case__ : str , snake_case__ : Dict , ) -> Optional[int]: '''simple docstring''' snake_case : Union[str, Any] = XLMForSequenceClassification(snake_case__ ) model.to(snake_case__ ) model.eval() snake_case : Dict = model(snake_case__ ) snake_case : List[str] = model(snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _SCREAMING_SNAKE_CASE (self : Any , snake_case__ : Any , snake_case__ : Any , snake_case__ : int , snake_case__ : str , snake_case__ : Optional[Any] , snake_case__ : str , snake_case__ : List[str] , snake_case__ : List[Any] , snake_case__ : Optional[int] , ) -> Tuple: '''simple docstring''' snake_case : Optional[int] = self.num_labels snake_case : Tuple = XLMForTokenClassification(snake_case__ ) model.to(snake_case__ ) model.eval() snake_case : Dict = model(snake_case__ , attention_mask=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _SCREAMING_SNAKE_CASE (self : Optional[int] , snake_case__ : Any , snake_case__ : str , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Tuple , snake_case__ : Union[str, Any] , snake_case__ : List[Any] , snake_case__ : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' snake_case : List[str] = self.num_choices snake_case : str = XLMForMultipleChoice(config=snake_case__ ) model.to(snake_case__ ) model.eval() snake_case : Dict = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case : int = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case : Union[str, Any] = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> Any: '''simple docstring''' snake_case : Optional[Any] = self.prepare_config_and_inputs() ( ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ) : Dict = config_and_inputs snake_case : Dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths} return config, inputs_dict @require_torch class UpperCAmelCase ( A_ ,A_ ,A_ ,unittest.TestCase ): A__ : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) A__ : Any = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable A__ : str = ( { "feature-extraction": XLMModel, "fill-mask": XLMWithLMHeadModel, "question-answering": XLMForQuestionAnsweringSimple, "text-classification": XLMForSequenceClassification, "text-generation": XLMWithLMHeadModel, "token-classification": XLMForTokenClassification, "zero-shot": XLMForSequenceClassification, } if is_torch_available() else {} ) def _SCREAMING_SNAKE_CASE (self : List[str] , snake_case__ : Tuple , snake_case__ : int , snake_case__ : List[Any] , snake_case__ : Dict , snake_case__ : List[str] ) -> int: '''simple docstring''' if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _SCREAMING_SNAKE_CASE (self : Optional[int] , snake_case__ : Optional[Any] , snake_case__ : Dict , snake_case__ : str=False ) -> int: '''simple docstring''' snake_case : Tuple = super()._prepare_for_class(snake_case__ , snake_case__ , return_labels=snake_case__ ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": snake_case : Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=snake_case__ ) snake_case : Optional[int] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=snake_case__ ) return inputs_dict def _SCREAMING_SNAKE_CASE (self : Dict ) -> int: '''simple docstring''' snake_case : Any = XLMModelTester(self ) snake_case : List[str] = ConfigTester(self , config_class=snake_case__ , emb_dim=37 ) def _SCREAMING_SNAKE_CASE (self : Dict ) -> Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE (self : int ) -> Any: '''simple docstring''' snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Tuple ) -> List[Any]: '''simple docstring''' snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*snake_case__ ) def _SCREAMING_SNAKE_CASE (self : str ) -> Dict: '''simple docstring''' snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*snake_case__ ) def _SCREAMING_SNAKE_CASE (self : List[str] ) -> Tuple: '''simple docstring''' snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*snake_case__ ) def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> Any: '''simple docstring''' snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*snake_case__ ) def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> Union[str, Any]: '''simple docstring''' snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*snake_case__ ) def _SCREAMING_SNAKE_CASE (self : List[str] ) -> Any: '''simple docstring''' snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*snake_case__ ) def _SCREAMING_SNAKE_CASE (self : Optional[int] , snake_case__ : Union[str, Any] , snake_case__ : str , snake_case__ : List[Any] , snake_case__ : int , snake_case__ : Optional[Any] , snake_case__ : Optional[Any]=False , snake_case__ : int=1 ) -> Optional[int]: '''simple docstring''' self.assertIsInstance(snake_case__ , snake_case__ ) self.assertListEqual( [isinstance(snake_case__ , snake_case__ ) for iter_attentions in attentions] , [True] * len(snake_case__ ) ) self.assertEqual(len(snake_case__ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(snake_case__ ): # adds PAD dummy token snake_case : int = min_length + idx + 1 snake_case : Any = min_length + idx + 1 snake_case : str = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(snake_case__ ) ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] , snake_case__ : Union[str, Any] , snake_case__ : List[str] , snake_case__ : Dict , snake_case__ : Tuple , snake_case__ : Dict , snake_case__ : Optional[int]=False , snake_case__ : str=1 ) -> Dict: '''simple docstring''' self.assertIsInstance(snake_case__ , snake_case__ ) self.assertListEqual( [isinstance(snake_case__ , snake_case__ ) for iter_hidden_states in hidden_states] , [True] * len(snake_case__ ) , ) self.assertEqual(len(snake_case__ ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(snake_case__ ): # adds PAD dummy token snake_case : str = min_length + idx + 1 snake_case : Tuple = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(snake_case__ ) , ) pass @slow def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> List[str]: '''simple docstring''' for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : Dict = XLMModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) @require_torch class UpperCAmelCase ( unittest.TestCase ): @slow def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' snake_case : int = XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048" ) model.to(snake_case__ ) snake_case : Any = torch.tensor([[14, 4_47]] , dtype=torch.long , device=snake_case__ ) # the president snake_case : Dict = [ 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference snake_case : Optional[int] = model.generate(snake_case__ , do_sample=snake_case__ ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , snake_case__ )
59
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowercase_ = imread(R'digital_image_processing/image_data/lena_small.jpg') lowercase_ = cvtColor(img, COLOR_BGR2GRAY) def lowerCAmelCase ( ): """simple docstring""" __A = cn.convert_to_negative(__UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def lowerCAmelCase ( ): """simple docstring""" with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(__UpperCamelCase , 1_1_0 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def lowerCAmelCase ( ): """simple docstring""" __A = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def lowerCAmelCase ( ): """simple docstring""" __A = imread('''digital_image_processing/image_data/lena_small.jpg''' , 0 ) # assert ambiguous array for all == True assert canny_img.all() __A = canny.canny(__UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def lowerCAmelCase ( ): """simple docstring""" assert gg.gaussian_filter(__UpperCamelCase , 5 , sigma=0.9 ).all() def lowerCAmelCase ( ): """simple docstring""" __A = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __A = conv.img_convolve(__UpperCamelCase , __UpperCamelCase ).astype(__UpperCamelCase ) assert res.any() def lowerCAmelCase ( ): """simple docstring""" assert med.median_filter(__UpperCamelCase , 3 ).any() def lowerCAmelCase ( ): """simple docstring""" __A , __A = sob.sobel_filter(__UpperCamelCase ) assert grad.any() and theta.any() def lowerCAmelCase ( ): """simple docstring""" __A = sp.make_sepia(__UpperCamelCase , 2_0 ) assert sepia.all() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" __A = bs.Burkes(imread(__UpperCamelCase , 1 ) , 1_2_0 ) burkes.process() assert burkes.output_img.any() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" __A = rs.NearestNeighbour(imread(__UpperCamelCase , 1 ) , 4_0_0 , 2_0_0 ) nn.process() assert nn.output.any() def lowerCAmelCase ( ): """simple docstring""" __A = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. __A = imread(__UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __A = 0 __A = 0 __A = image[x_coordinate][y_coordinate] __A = lbp.get_neighbors_pixel( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __A = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __A = lbp.local_binary_value(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert lbp_image.any()
266
0
"""simple docstring""" def _snake_case ( ): return [list(range(1000 - i , -1000 - i , -1 ) ) for i in range(1000 )] snake_case__ : Optional[Any] = generate_large_matrix() snake_case__ : List[Any] = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def _snake_case ( _snake_case : list[list[int]] ): assert all(row == sorted(_snake_case , reverse=_snake_case ) for row in grid ) assert all(list(_snake_case ) == sorted(_snake_case , reverse=_snake_case ) for col in zip(*_snake_case ) ) def _snake_case ( _snake_case : list[int] ): lowerCAmelCase : Any = 0 lowerCAmelCase : Dict = len(_snake_case ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: lowerCAmelCase : str = (left + right) // 2 lowerCAmelCase : Optional[Any] = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: lowerCAmelCase : List[Any] = mid + 1 else: lowerCAmelCase : int = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(_snake_case ) def _snake_case ( _snake_case : list[list[int]] ): lowerCAmelCase : Any = 0 lowerCAmelCase : Tuple = len(grid[0] ) for i in range(len(_snake_case ) ): lowerCAmelCase : Union[str, Any] = find_negative_index(grid[i][:bound] ) total += bound return (len(_snake_case ) * len(grid[0] )) - total def _snake_case ( _snake_case : list[list[int]] ): return len([number for row in grid for number in row if number < 0] ) def _snake_case ( _snake_case : list[list[int]] ): lowerCAmelCase : Optional[int] = 0 for row in grid: for i, number in enumerate(_snake_case ): if number < 0: total += len(_snake_case ) - i break return total def _snake_case ( ): from timeit import timeit print('''Running benchmarks''' ) lowerCAmelCase : Optional[int] = ( '''from __main__ import count_negatives_binary_search, ''' '''count_negatives_brute_force, count_negatives_brute_force_with_break, grid''' ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): lowerCAmelCase : Any = timeit(f'''{func}(grid=grid)''' , setup=_snake_case , number=500 ) print(f'''{func}() took {time:0.4f} seconds''' ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
60
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase_ = random.Random() if is_torch_available(): import torch def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase=1.0 , __UpperCamelCase=None , __UpperCamelCase=None ): """simple docstring""" if rng is None: __A = global_rng __A = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any, _lowerCamelCase : List[str], _lowerCamelCase : Any=7, _lowerCamelCase : Optional[int]=4_00, _lowerCamelCase : Optional[int]=20_00, _lowerCamelCase : Dict=1, _lowerCamelCase : Optional[Any]=0.0, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : Dict=True, ): '''simple docstring''' __A = parent __A = batch_size __A = min_seq_length __A = max_seq_length __A = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __A = feature_size __A = padding_value __A = sampling_rate __A = return_attention_mask __A = do_normalize def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[Any]=False, _lowerCamelCase : int=False ): '''simple docstring''' def _flatten(_lowerCamelCase : List[str] ): return list(itertools.chain(*_lowerCamelCase ) ) if equal_length: __A = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __A = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: __A = [np.asarray(_lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : int = ASTFeatureExtractor def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ASTFeatureExtractionTester(self ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' # Tests that all call wrap to encode_plus and batch_encode_plus __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __A = [floats_list((1, x) )[0] for x in range(8_00, 14_00, 2_00 )] __A = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] # Test not batched input __A = feat_extract(speech_inputs[0], return_tensors='''np''' ).input_values __A = feat_extract(np_speech_inputs[0], return_tensors='''np''' ).input_values self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test batched __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __A = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] __A = np.asarray(_lowerCamelCase ) __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' import torch __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __A = np.random.rand(1_00 ).astype(np.floataa ) __A = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Union[str, Any] ): '''simple docstring''' from datasets import load_dataset __A = load_dataset('''hf-internal-testing/librispeech_asr_dummy''', '''clean''', split='''validation''' ) # automatic decoding with librispeech __A = ds.sort('''id''' ).select(range(_lowerCamelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # fmt: off __A = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on __A = self._load_datasamples(1 ) __A = ASTFeatureExtractor() __A = feature_extractor(_lowerCamelCase, return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape, (1, 10_24, 1_28) ) self.assertTrue(torch.allclose(input_values[0, 0, :30], _lowerCamelCase, atol=1e-4 ) )
266
0
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
61
"""simple docstring""" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = current_set.copy() for row_index, row in enumerate(__UpperCamelCase ): __A = row[0] for column_index, column in enumerate(__UpperCamelCase ): if magnitude == 0: __A = column continue __A = column / magnitude # Subtract to cancel term __A = current_set[0] __A = [first_row] __A = current_set[1::] for row in current_set: __A = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__UpperCamelCase ) continue for column_index in range(len(__UpperCamelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__UpperCamelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: __A = final_set[0] __A = [] __A = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __A = simplify(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __UpperCamelCase ) __A = resultant return final_set def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if len(__UpperCamelCase ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) __A = len(__UpperCamelCase ) + 1 if any(len(__UpperCamelCase ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__UpperCamelCase , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__UpperCamelCase ) == 1: return [equations[0][-1] / equations[0][0]] __A = equations.copy() if any(0 in row for row in data_set ): __A = data_set.copy() __A = [] for row_index, row in enumerate(__UpperCamelCase ): if 0 not in row: __A = data_set.pop(__UpperCamelCase ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __UpperCamelCase ) __A = data_set.copy() __A = simplify(__UpperCamelCase ) __A = simplified[::-1] __A = [] for row in simplified: __A = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __A = row.copy()[: len(__UpperCamelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__UpperCamelCase ) == 0: solutions.append(0 ) continue __A = temp_row[1::] __A = temp_row[::-1] for column_index, column in enumerate(__UpperCamelCase ): current_solution -= column * solutions[column_index] solutions.append(__UpperCamelCase ) __A = [] for item in solutions: final.append(float(round(__UpperCamelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
266
0
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 _A = logging.get_logger(__name__) class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ , A_ , A_ , **A_ ) -> Optional[Any]: __UpperCamelCase =feature_size __UpperCamelCase =sampling_rate __UpperCamelCase =padding_value __UpperCamelCase =kwargs.pop('padding_side' , 'right' ) __UpperCamelCase =kwargs.pop('return_attention_mask' , A_ ) super().__init__(**A_ ) def _a ( self , A_ , A_ = True , A_ = None , A_ = False , A_ = None , A_ = None , A_ = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(A_ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __UpperCamelCase ={ 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() )}' ) __UpperCamelCase =processed_features[self.model_input_names[0]] __UpperCamelCase =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(A_ ) == 0: if return_attention_mask: __UpperCamelCase =[] 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 __UpperCamelCase =required_input[0] if isinstance(A_ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __UpperCamelCase =0 while len(required_input[index] ) == 0: index += 1 if index < len(A_ ): __UpperCamelCase =required_input[index][0] if return_tensors is None: if is_tf_tensor(A_ ): __UpperCamelCase ='tf' elif is_torch_tensor(A_ ): __UpperCamelCase ='pt' elif isinstance(A_ , (int, float, list, tuple, np.ndarray) ): __UpperCamelCase ='np' else: raise ValueError( f'type of {first_element} unknown: {type(A_ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __UpperCamelCase =to_numpy(A_ ) else: __UpperCamelCase =[to_numpy(A_ ) for v in value] # Convert padding_strategy in PaddingStrategy __UpperCamelCase =self._get_padding_strategies(padding=A_ , max_length=A_ ) __UpperCamelCase =processed_features[self.model_input_names[0]] __UpperCamelCase =len(A_ ) if not all(len(A_ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) __UpperCamelCase =[] for i in range(A_ ): __UpperCamelCase ={k: v[i] for k, v in processed_features.items()} # truncation __UpperCamelCase =self._truncate( A_ , max_length=A_ , pad_to_multiple_of=A_ , truncation=A_ , ) truncated_inputs.append(A_ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __UpperCamelCase =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __UpperCamelCase =PaddingStrategy.MAX_LENGTH __UpperCamelCase ={} for i in range(A_ ): # padding __UpperCamelCase =self._pad( truncated_inputs[i] , max_length=A_ , padding_strategy=A_ , pad_to_multiple_of=A_ , return_attention_mask=A_ , ) for key, value in outputs.items(): if key not in batch_outputs: __UpperCamelCase =[] if value.dtype is np.dtype(np.floataa ): __UpperCamelCase =value.astype(np.floataa ) batch_outputs[key].append(A_ ) return BatchFeature(A_ , tensor_type=A_ ) def _a ( self , A_ , A_ = None , A_ = PaddingStrategy.DO_NOT_PAD , A_ = None , A_ = None , ) -> dict: __UpperCamelCase =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __UpperCamelCase =len(A_ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __UpperCamelCase =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __UpperCamelCase =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(A_ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __UpperCamelCase =np.ones(len(A_ ) , dtype=np.intaa ) if needs_to_be_padded: __UpperCamelCase =max_length - len(A_ ) if self.padding_side == "right": if return_attention_mask: __UpperCamelCase =np.pad( processed_features['attention_mask'] , (0, difference) ) __UpperCamelCase =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __UpperCamelCase =np.pad( A_ , A_ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __UpperCamelCase =np.pad( processed_features['attention_mask'] , (difference, 0) ) __UpperCamelCase =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __UpperCamelCase =np.pad( A_ , A_ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def _a ( self , A_ , A_ = None , A_ = None , A_ = None , ) -> Optional[Any]: 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.' ) __UpperCamelCase =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): __UpperCamelCase =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __UpperCamelCase =len(A_ ) > max_length if needs_to_be_truncated: __UpperCamelCase =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __UpperCamelCase =processed_features['attention_mask'][:max_length] return processed_features def _a ( self , A_=False , A_=None ) -> Optional[int]: # Get padding strategy if padding is not False: if padding is True: __UpperCamelCase =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(A_ , A_ ): __UpperCamelCase =PaddingStrategy(A_ ) elif isinstance(A_ , A_ ): __UpperCamelCase =padding else: __UpperCamelCase =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
62
"""simple docstring""" from __future__ import annotations from typing import Any def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not postfix_notation: return 0 __A = {'''+''', '''-''', '''*''', '''/'''} __A = [] for token in postfix_notation: if token in operations: __A , __A = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(__UpperCamelCase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
266
0
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" __a =MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __a =TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def UpperCamelCase__ ( self : Optional[int] , __a : Optional[Any] , __a : Dict , __a : List[str] ): _a = TextaTextGenerationPipeline(model=__a , tokenizer=__a ) return generator, ["Something to write", "Something else"] def UpperCamelCase__ ( self : List[str] , __a : List[Any] , __a : Any ): _a = generator("Something there" ) self.assertEqual(__a , [{"generated_text": ANY(__a )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["generated_text"].startswith("Something there" ) ) _a = generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) _a = generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) with self.assertRaises(__a ): generator(4 ) @require_torch def UpperCamelCase__ ( self : Optional[int] ): _a = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="pt" ) # do_sample=False necessary for reproducibility _a = generator("Something there" , do_sample=__a ) self.assertEqual(__a , [{"generated_text": ""}] ) _a = 3 _a = generator( "Something there" , num_return_sequences=__a , num_beams=__a , ) _a = [ {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": ""}, ] self.assertEqual(__a , __a ) _a = generator("This is a test" , do_sample=__a , num_return_sequences=2 , return_tensors=__a ) self.assertEqual( __a , [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ] , ) _a = generator.model.config.eos_token_id _a = "<pad>" _a = generator( ["This is a test", "This is a second test"] , do_sample=__a , num_return_sequences=2 , batch_size=2 , return_tensors=__a , ) self.assertEqual( __a , [ [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], [ {"generated_token_ids": ANY(torch.Tensor )}, {"generated_token_ids": ANY(torch.Tensor )}, ], ] , ) @require_tf def UpperCamelCase__ ( self : Dict ): _a = pipeline("text2text-generation" , model="patrickvonplaten/t5-tiny-random" , framework="tf" ) # do_sample=False necessary for reproducibility _a = generator("Something there" , do_sample=__a ) self.assertEqual(__a , [{"generated_text": ""}] )
63
"""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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple, _lowerCamelCase : List[str]=13, _lowerCamelCase : Optional[Any]=7, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : int=True, _lowerCamelCase : List[str]=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : int=99, _lowerCamelCase : Optional[int]=32, _lowerCamelCase : Tuple=5, _lowerCamelCase : Tuple=4, _lowerCamelCase : str=37, _lowerCamelCase : Union[str, Any]="gelu", _lowerCamelCase : int=0.1, _lowerCamelCase : List[Any]=0.1, _lowerCamelCase : Dict=5_12, _lowerCamelCase : List[Any]=16, _lowerCamelCase : Any=2, _lowerCamelCase : Any=0.02, _lowerCamelCase : Dict=4, ): '''simple docstring''' __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_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_choices def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __A = None if self.use_attention_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 = 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 _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Dict = True A_ : Tuple = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = FlaxRoFormerModelTester(self ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''', from_pt=_lowerCamelCase ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase ) @require_flax class snake_case ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __A = jnp.array([[0, 1, 2, 3, 4, 5]] ) __A = model(_lowerCamelCase )[0] __A = 5_00_00 __A = (1, 6, vocab_size) self.assertEqual(output.shape, _lowerCamelCase ) __A = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3], _lowerCamelCase, atol=1e-4 ) )
266
0
"""simple docstring""" import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class lowercase: '''simple docstring''' def __init__( self: Optional[Any], a_: Tuple, a_: Any=13, a_: Any=7, a_: Tuple=True, a_: int=True, a_: Union[str, Any]=True, a_: Optional[int]=True, a_: int=99, a_: Tuple=64, a_: Union[str, Any]=5, a_: Optional[int]=4, a_: int=37, a_: str="gelu", a_: Tuple=0.1, a_: Any=0.1, a_: Tuple=512, a_: Optional[Any]=16, a_: Union[str, Any]=2, a_: int=0.02, a_: List[Any]=3, a_: List[Any]=4, a_: Tuple=None, ): '''simple docstring''' _snake_case : Optional[int] = parent _snake_case : Tuple = batch_size _snake_case : List[Any] = seq_length _snake_case : Union[str, Any] = is_training _snake_case : Union[str, Any] = use_input_mask _snake_case : List[str] = use_token_type_ids _snake_case : Optional[int] = use_labels _snake_case : Optional[Any] = vocab_size _snake_case : str = hidden_size _snake_case : Tuple = num_hidden_layers _snake_case : Optional[Any] = num_attention_heads _snake_case : Optional[Any] = intermediate_size _snake_case : Union[str, Any] = hidden_act _snake_case : Optional[Any] = hidden_dropout_prob _snake_case : Optional[int] = attention_probs_dropout_prob _snake_case : Any = max_position_embeddings _snake_case : Optional[Any] = type_vocab_size _snake_case : Tuple = type_sequence_label_size _snake_case : Optional[int] = initializer_range _snake_case : int = num_labels _snake_case : Dict = num_choices _snake_case : str = scope _snake_case : Optional[int] = vocab_size - 1 def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) _snake_case : int = None if self.use_input_mask: _snake_case : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) _snake_case : Optional[int] = None if self.use_labels: _snake_case : Dict = ids_tensor([self.batch_size, self.seq_length], self.num_labels ) _snake_case : Optional[int] = self.get_config() return config, input_ids, input_mask, token_labels def UpperCamelCase_ ( self: str ): '''simple docstring''' return GPTNeoXConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=a_, initializer_range=self.initializer_range, pad_token_id=self.pad_token_id, ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case , _snake_case , _snake_case , _snake_case : Dict = self.prepare_config_and_inputs() _snake_case : Optional[Any] = True return config, input_ids, input_mask, token_labels def UpperCamelCase_ ( self: Tuple, a_: int, a_: List[Any], a_: Dict ): '''simple docstring''' _snake_case : Optional[Any] = GPTNeoXModel(config=a_ ) model.to(a_ ) model.eval() _snake_case : Union[str, Any] = model(a_, attention_mask=a_ ) _snake_case : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self: Union[str, Any], a_: Union[str, Any], a_: Optional[int], a_: List[Any] ): '''simple docstring''' _snake_case : List[str] = True _snake_case : Any = GPTNeoXModel(a_ ) model.to(a_ ) model.eval() _snake_case : Optional[Any] = model(a_, attention_mask=a_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self: Optional[Any], a_: Optional[int], a_: int, a_: Union[str, Any], a_: Any ): '''simple docstring''' _snake_case : Optional[Any] = GPTNeoXForCausalLM(config=a_ ) model.to(a_ ) model.eval() _snake_case : str = model(a_, attention_mask=a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self: Union[str, Any], a_: int, a_: List[Any], a_: Union[str, Any], a_: str ): '''simple docstring''' _snake_case : int = self.num_labels _snake_case : Optional[int] = GPTNeoXForQuestionAnswering(a_ ) model.to(a_ ) model.eval() _snake_case : Tuple = model(a_, attention_mask=a_ ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self: Dict, a_: Dict, a_: Optional[int], a_: str, a_: str ): '''simple docstring''' _snake_case : Optional[int] = self.num_labels _snake_case : Union[str, Any] = GPTNeoXForSequenceClassification(a_ ) model.to(a_ ) model.eval() _snake_case : List[str] = ids_tensor([self.batch_size], self.type_sequence_label_size ) _snake_case : List[Any] = model(a_, attention_mask=a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self: str, a_: Optional[Any], a_: Tuple, a_: List[Any], a_: List[str] ): '''simple docstring''' _snake_case : Optional[Any] = self.num_labels _snake_case : List[str] = GPTNeoXForTokenClassification(a_ ) model.to(a_ ) model.eval() _snake_case : str = model(a_, attention_mask=a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self: List[str], a_: Dict, a_: str, a_: Optional[Any] ): '''simple docstring''' _snake_case : Any = True _snake_case : Optional[int] = GPTNeoXForCausalLM(config=a_ ) model.to(a_ ) model.eval() # first forward pass _snake_case : Optional[Any] = model(a_, attention_mask=a_, use_cache=a_ ) _snake_case : Union[str, Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _snake_case : Dict = ids_tensor((self.batch_size, 3), config.vocab_size ) _snake_case : Optional[Any] = ids_tensor((self.batch_size, 3), vocab_size=2 ) # append to next input_ids and _snake_case : Optional[Any] = torch.cat([input_ids, next_tokens], dim=-1 ) _snake_case : List[Any] = torch.cat([input_mask, next_mask], dim=-1 ) _snake_case : int = model(a_, attention_mask=a_, output_hidden_states=a_ ) _snake_case : str = output_from_no_past["""hidden_states"""][0] _snake_case : Union[str, Any] = model( a_, attention_mask=a_, past_key_values=a_, output_hidden_states=a_, )["""hidden_states"""][0] # select random slice _snake_case : Any = ids_tensor((1,), output_from_past.shape[-1] ).item() _snake_case : str = output_from_no_past[:, -3:, random_slice_idx].detach() _snake_case : int = 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 UpperCamelCase_ ( self: List[str] ): '''simple docstring''' _snake_case : Any = self.prepare_config_and_inputs() _snake_case , _snake_case , _snake_case , _snake_case : Dict = config_and_inputs _snake_case : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowercase( __a , __a , __a , unittest.TestCase ): '''simple docstring''' lowercase__ = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) lowercase__ = (GPTNeoXForCausalLM,) if is_torch_available() else () lowercase__ = ( { "feature-extraction": GPTNeoXModel, "question-answering": GPTNeoXForQuestionAnswering, "text-classification": GPTNeoXForSequenceClassification, "text-generation": GPTNeoXForCausalLM, "token-classification": GPTNeoXForTokenClassification, "zero-shot": GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : Union[str, Any] = GPTNeoXModelTester(self ) _snake_case : List[str] = ConfigTester(self, config_class=a_, hidden_size=64, num_attention_heads=8 ) def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' _snake_case , _snake_case , _snake_case , _snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a_, a_, a_ ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case , _snake_case , _snake_case , _snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(a_, a_, a_ ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case , _snake_case , _snake_case , _snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() _snake_case : str = None self.model_tester.create_and_check_model_as_decoder(a_, a_, a_ ) def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case , _snake_case , _snake_case , _snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(a_, a_, a_ ) def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' _snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) @unittest.skip(reason="""Feed forward chunking is not implemented""" ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def UpperCamelCase_ ( self: Optional[int], a_: List[Any] ): '''simple docstring''' _snake_case , _snake_case : Tuple = self.model_tester.prepare_config_and_inputs_for_common() _snake_case : Optional[Any] = ids_tensor([1, 10], config.vocab_size ) _snake_case : Any = ids_tensor([1, int(config.max_position_embeddings * 1.5 )], config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights _snake_case : List[str] = GPTNeoXModel(a_ ) original_model.to(a_ ) original_model.eval() _snake_case : Dict = original_model(a_ ).last_hidden_state _snake_case : List[Any] = original_model(a_ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights _snake_case : Optional[int] = {"""type""": scaling_type, """factor""": 10.0} _snake_case : Union[str, Any] = GPTNeoXModel(a_ ) scaled_model.to(a_ ) scaled_model.eval() _snake_case : Optional[int] = scaled_model(a_ ).last_hidden_state _snake_case : Dict = scaled_model(a_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a_, a_, atol=1E-5 ) ) else: self.assertFalse(torch.allclose(a_, a_, atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(a_, a_, atol=1E-5 ) ) @require_torch class lowercase( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : List[str] = AutoTokenizer.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) for checkpointing in [True, False]: _snake_case : Dict = GPTNeoXForCausalLM.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(a_ ) _snake_case : Optional[int] = tokenizer("""My favorite food is""", return_tensors="""pt""" ).to(a_ ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 _snake_case : Tuple = """My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure""" _snake_case : str = model.generate(**a_, do_sample=a_, max_new_tokens=20 ) _snake_case : List[Any] = tokenizer.batch_decode(a_ )[0] self.assertEqual(a_, a_ )
64
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase ( __UpperCamelCase = 1_0_0_0_0_0_0 , __UpperCamelCase = 1_0 ): """simple docstring""" __A = defaultdict(__UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __A = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __A = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(__UpperCamelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 1_0 ) if __name__ == "__main__": print(F'''{solution() = }''')
266
0
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_xlnet import XLNetTokenizer else: UpperCamelCase__ = None UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} UpperCamelCase__ = { 'vocab_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model', }, 'tokenizer_file': { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json', }, } UpperCamelCase__ = { 'xlnet-base-cased': None, 'xlnet-large-cased': None, } UpperCamelCase__ = '▁' # Segments (not really needed) UpperCamelCase__ = 0 UpperCamelCase__ = 1 UpperCamelCase__ = 2 UpperCamelCase__ = 3 UpperCamelCase__ = 4 class A ( UpperCAmelCase_ ): __UpperCAmelCase : int = VOCAB_FILES_NAMES __UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : str = 'left' __UpperCAmelCase : List[str] = XLNetTokenizer def __init__(self : Union[str, Any] , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : List[Any]=False , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Union[str, Any]=False , __UpperCAmelCase : str="<s>" , __UpperCAmelCase : Tuple="</s>" , __UpperCAmelCase : List[Any]="<unk>" , __UpperCAmelCase : int="<sep>" , __UpperCAmelCase : Optional[Any]="<pad>" , __UpperCAmelCase : str="<cls>" , __UpperCAmelCase : Union[str, Any]="<mask>" , __UpperCAmelCase : Optional[int]=["<eop>", "<eod>"] , **__UpperCAmelCase : Any , ) -> Any: """simple docstring""" UpperCAmelCase__ = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token super().__init__( vocab_file=__UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , **__UpperCAmelCase , ) UpperCAmelCase__ = 3 UpperCAmelCase__ = do_lower_case UpperCAmelCase__ = remove_space UpperCAmelCase__ = keep_accents UpperCAmelCase__ = vocab_file UpperCAmelCase__ = False if not self.vocab_file else True def lowercase_ (self : Optional[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCAmelCase__ = [self.sep_token_id] UpperCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def lowercase_ (self : str , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCAmelCase__ = [self.sep_token_id] UpperCAmelCase__ = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def lowercase_ (self : int , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" 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 UpperCAmelCase__ = os.path.join( __UpperCAmelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.vocab_file , __UpperCAmelCase ) return (out_vocab_file,)
65
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : Optional[int]=2, _lowerCamelCase : Optional[int]=3, _lowerCamelCase : int=64, _lowerCamelCase : List[str]=None ): '''simple docstring''' __A = np.random.default_rng(_lowerCamelCase ) __A = length __A = rng.normal(size=(length,) ).astype(np.floataa ) __A = a * self.x + b + rng.normal(scale=0.1, size=(length,) ).astype(np.floataa ) def __len__( self : str ): '''simple docstring''' return self.length def __getitem__( self : Dict, _lowerCamelCase : Optional[int] ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple=0, _lowerCamelCase : Any=0, _lowerCamelCase : Optional[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Optional[Any]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a[0] + self.b[0] class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : str, _lowerCamelCase : Optional[Any]=0, _lowerCamelCase : Any=0, _lowerCamelCase : List[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[str]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a + self.b def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase = 1_6 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __A = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __A = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __A = load_dataset('''csv''' , data_files=__UpperCamelCase ) __A = datasets['''train'''].unique('''label''' ) __A = {v: i for i, v in enumerate(__UpperCamelCase )} def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding='''max_length''' ) if "label" in examples: __A = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __A = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(__UpperCamelCase ): # 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(__UpperCamelCase , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' ) return tokenizer.pad(__UpperCamelCase , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __A = DataLoader(tokenized_datasets['''train'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2 ) __A = DataLoader(tokenized_datasets['''validation'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
266
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __a = { "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = ["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys __a = _LazyModule(__name__, globals()["__file__"], _import_structure)
66
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowercase_ = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' lowercase_ = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' lowercase_ = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), id='''references''' ), } ), ) def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[List[List[str]]], _lowerCamelCase : List[List[str]], _lowerCamelCase : int = 1, _lowerCamelCase : int = 4, ): '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCamelCase, hypotheses=_lowerCamelCase, min_len=_lowerCamelCase, max_len=_lowerCamelCase ) }
266
0
'''simple docstring''' from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split __UpperCAmelCase =datasets.load_iris() __UpperCAmelCase =np.array(data["data"]) __UpperCAmelCase =np.array(data["target"]) __UpperCAmelCase =data["target_names"] __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase =train_test_split(X, y) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Tuple: return np.linalg.norm(np.array(UpperCamelCase__ ) - np.array(UpperCamelCase__ ) ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=5 ) -> int: __lowerCamelCase = zip(UpperCamelCase__ , UpperCamelCase__ ) # List of distances of all points from the point to be classified __lowerCamelCase = [] for data_point in data: __lowerCamelCase = euclidean_distance(data_point[0] , UpperCamelCase__ ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. __lowerCamelCase = [i[1] for i in sorted(UpperCamelCase__ )[:k]] # Most commonly occurring class among them # is the class into which the point is classified __lowerCamelCase = Counter(UpperCamelCase__ ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
67
"""simple docstring""" class snake_case : '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : list[int] ): '''simple docstring''' __A = len(_lowerCamelCase ) __A = [0] * len_array if len_array > 0: __A = array[0] for i in range(1, _lowerCamelCase ): __A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : int ): '''simple docstring''' __A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_lowerCamelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
266
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__ = float("""nan""") class a__ : """simple docstring""" def __init__( self , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = sys.stdout A__ = open(lowercase , "a" ) def __getattr__( self , lowercase ) -> List[Any]: '''simple docstring''' return getattr(self.stdout , lowercase ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' self.stdout.write(lowercase ) # strip tqdm codes self.file.write(re.sub(R"^.*\r" , "" , lowercase , 0 , re.M ) ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int]=8_0 , SCREAMING_SNAKE_CASE_: List[Any]=False ) -> Union[str, Any]: '''simple docstring''' A__ = [] # deal with critical env vars A__ = ["CUDA_VISIBLE_DEVICES"] for key in env_keys: A__ = os.environ.get(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ ) # 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(SCREAMING_SNAKE_CASE_ ) > 0: current_line += F'{cmd.pop(0 )} ' if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(SCREAMING_SNAKE_CASE_ ) A__ = "" return "\\\n".join(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: int ) -> Union[str, Any]: '''simple docstring''' 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__ ( SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: Union[str, Any] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: str ) -> int: '''simple docstring''' if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 1_0_0 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.22222222] )} , ) A__ = subprocess.run(SCREAMING_SNAKE_CASE_ , capture_output=SCREAMING_SNAKE_CASE_ , text=SCREAMING_SNAKE_CASE_ ) if verbose: print("STDOUT" , result.stdout ) print("STDERR" , result.stderr ) # save the streams A__ = variation.replace(" " , "-" ) with open(Path(SCREAMING_SNAKE_CASE_ ) / F'log.{prefix}.stdout.txt' , "w" ) as f: f.write(result.stdout ) with open(Path(SCREAMING_SNAKE_CASE_ ) / 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(SCREAMING_SNAKE_CASE_ ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: Union[str, Any] , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: str , ) -> List[Any]: '''simple docstring''' 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(SCREAMING_SNAKE_CASE_ ) , desc=SCREAMING_SNAKE_CASE_ , leave=SCREAMING_SNAKE_CASE_ ): A__ = process_run_single( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A__ = single_run_metrics[target_metric_key] if not math.isnan(SCREAMING_SNAKE_CASE_ ): metrics.append(SCREAMING_SNAKE_CASE_ ) results.append(SCREAMING_SNAKE_CASE_ ) outcome += "✓" else: outcome += "✘" A__ = F'\33[2K\r{outcome}' if len(SCREAMING_SNAKE_CASE_ ) > 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(SCREAMING_SNAKE_CASE_ ) > 1: results_str += F' {tuple(round(SCREAMING_SNAKE_CASE_ , 2 ) for x in results )}' print(SCREAMING_SNAKE_CASE_ ) A__ = variation return mean_metrics else: print(SCREAMING_SNAKE_CASE_ ) return {variation_key: variation, target_metric_key: nan} def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' A__ = torch.cuda.get_device_properties(torch.device("cuda" ) ) return F'\nDatetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch : {torch.__version__}\ncuda : {torch.version.cuda}\npython : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**3_0:0.2f}GB\n' def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: Optional[int] ) -> Union[str, Any]: '''simple docstring''' A__ = pd.DataFrame(SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ ): # 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(SCREAMING_SNAKE_CASE_ ): A__ = df.apply( lambda SCREAMING_SNAKE_CASE_ : round(1_0_0 * (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(SCREAMING_SNAKE_CASE_ , axis="columns" ) # reorder cols # capitalize A__ = df.rename(str.capitalize , axis="columns" ) # make the cols as narrow as possible A__ = df.rename(lambda SCREAMING_SNAKE_CASE_ : c.replace("_" , "<br>" ) , axis="columns" ) A__ = df.rename(lambda SCREAMING_SNAKE_CASE_ : 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=SCREAMING_SNAKE_CASE_ , 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=SCREAMING_SNAKE_CASE_ , floatfmt=".2f" )] print("\n\n".join(SCREAMING_SNAKE_CASE_ ) ) def lowerCAmelCase__ ( ) -> Optional[int]: '''simple docstring''' A__ = argparse.ArgumentParser() parser.add_argument( "--base-cmd" , default=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ , help="Base cmd" , ) parser.add_argument( "--variations" , default=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ , nargs="+" , required=SCREAMING_SNAKE_CASE_ , help="Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'" , ) parser.add_argument( "--base-variation" , default=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ , 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=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ , required=SCREAMING_SNAKE_CASE_ , help="Target metric key in output_dir/all_results.json, e.g., train_samples_per_second" , ) parser.add_argument( "--report-metric-keys" , default="" , type=SCREAMING_SNAKE_CASE_ , 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=SCREAMING_SNAKE_CASE_ , help="How many times to re-run each variation - an average will be reported" , ) parser.add_argument( "--output_dir" , default="output_benchmark" , type=SCREAMING_SNAKE_CASE_ , 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=SCREAMING_SNAKE_CASE_ , 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(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) A__ = get_base_command(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # split each dimension into its --foo variations A__ = [list(map(str.strip , re.split(R"\|" , SCREAMING_SNAKE_CASE_ ) ) ) 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(*SCREAMING_SNAKE_CASE_ ) ) ) ) A__ = max(len(SCREAMING_SNAKE_CASE_ ) 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(SCREAMING_SNAKE_CASE_ ) print(F'\n*** Running {len(SCREAMING_SNAKE_CASE_ )} benchmarks:' ) print(F'Base command: {" ".join(SCREAMING_SNAKE_CASE_ )}' ) A__ = "variation" A__ = [] for id, variation in enumerate(tqdm(SCREAMING_SNAKE_CASE_ , desc="Total completion: " , leave=SCREAMING_SNAKE_CASE_ ) ): A__ = base_cmd + variation.split() results.append( process_run( id + 1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , args.target_metric_key , SCREAMING_SNAKE_CASE_ , args.repeat_times , SCREAMING_SNAKE_CASE_ , args.verbose , ) ) process_results(SCREAMING_SNAKE_CASE_ , args.target_metric_key , SCREAMING_SNAKE_CASE_ , args.base_variation , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": main()
68
"""simple docstring""" import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ = logging.get_logger(__name__) lowercase_ = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } lowercase_ = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } lowercase_ = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCAmelCase ( ): """simple docstring""" __A = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __A = bs[:] __A = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 __A = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase , __UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = set() __A = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __A = char return pairs class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : Tuple = VOCAB_FILES_NAMES A_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : Dict, _lowerCamelCase : Optional[Any], _lowerCamelCase : List[str], _lowerCamelCase : Dict="replace", _lowerCamelCase : Any="<s>", _lowerCamelCase : Optional[int]="</s>", _lowerCamelCase : Dict="</s>", _lowerCamelCase : List[Any]="<s>", _lowerCamelCase : List[str]="<unk>", _lowerCamelCase : str="<pad>", _lowerCamelCase : Any="<mask>", _lowerCamelCase : Any=False, **_lowerCamelCase : Tuple, ): '''simple docstring''' __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else bos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else eos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else sep_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else cls_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else unk_token __A = 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 __A = 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: __A = json.load(_lowerCamelCase ) __A = {v: k for k, v in self.encoder.items()} __A = errors # how to handle errors in decoding __A = bytes_to_unicode() __A = {v: k for k, v in self.byte_encoder.items()} with open(_lowerCamelCase, encoding='''utf-8''' ) as merges_handle: __A = merges_handle.read().split('''\n''' )[1:-1] __A = [tuple(merge.split() ) for merge in bpe_merges] __A = dict(zip(_lowerCamelCase, range(len(_lowerCamelCase ) ) ) ) __A = {} __A = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __A = 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.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return len(self.encoder ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return dict(self.encoder, **self.added_tokens_encoder ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[Any] ): '''simple docstring''' if token in self.cache: return self.cache[token] __A = tuple(_lowerCamelCase ) __A = get_pairs(_lowerCamelCase ) if not pairs: return token while True: __A = min(_lowerCamelCase, key=lambda _lowerCamelCase : self.bpe_ranks.get(_lowerCamelCase, float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __A , __A = bigram __A = [] __A = 0 while i < len(_lowerCamelCase ): try: __A = word.index(_lowerCamelCase, _lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __A = 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 __A = tuple(_lowerCamelCase ) __A = new_word if len(_lowerCamelCase ) == 1: break else: __A = get_pairs(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = word return word def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Dict ): '''simple docstring''' __A = [] for token in re.findall(self.pat, _lowerCamelCase ): __A = ''''''.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 _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : Dict ): '''simple docstring''' return self.encoder.get(_lowerCamelCase, self.encoder.get(self.unk_token ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Any ): '''simple docstring''' return self.decoder.get(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' __A = ''''''.join(_lowerCamelCase ) __A = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''', errors=self.errors ) return text def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : str, _lowerCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __A = 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''' ) __A = 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!''' ) __A = token_index writer.write(''' '''.join(_lowerCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None, _lowerCamelCase : bool = 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 _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Union[str, Any], _lowerCamelCase : List[str]=False, **_lowerCamelCase : List[Any] ): '''simple docstring''' __A = 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()): __A = ''' ''' + text return (text, kwargs) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : "Conversation" ): '''simple docstring''' __A = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = self.encode(_lowerCamelCase ) if len(_lowerCamelCase ) > self.model_max_length: __A = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
266
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = '''▁''' __UpperCamelCase = {'''vocab_file''': '''sentencepiece.bpe.model'''} __UpperCamelCase = { '''vocab_file''': { '''facebook/mbart-large-50-one-to-many-mmt''': ( '''https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model''' ), } } __UpperCamelCase = { '''facebook/mbart-large-50-one-to-many-mmt''': 1024, } # fmt: off __UpperCamelCase = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN''', '''af_ZA''', '''az_AZ''', '''bn_IN''', '''fa_IR''', '''he_IL''', '''hr_HR''', '''id_ID''', '''ka_GE''', '''km_KH''', '''mk_MK''', '''ml_IN''', '''mn_MN''', '''mr_IN''', '''pl_PL''', '''ps_AF''', '''pt_XX''', '''sv_SE''', '''sw_KE''', '''ta_IN''', '''te_IN''', '''th_TH''', '''tl_XX''', '''uk_UA''', '''ur_PK''', '''xh_ZA''', '''gl_ES''', '''sl_SI'''] class UpperCamelCase ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ = ["input_ids", "attention_mask"] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] def __init__( self, lowerCAmelCase__, lowerCAmelCase__=None, lowerCAmelCase__=None, lowerCAmelCase__="</s>", lowerCAmelCase__="</s>", lowerCAmelCase__="<s>", lowerCAmelCase__="<unk>", lowerCAmelCase__="<pad>", lowerCAmelCase__="<mask>", lowerCAmelCase__ = None, **lowerCAmelCase__, ) -> None: # 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 snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs snake_case_ = kwargs.get('additional_special_tokens', []) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=lowerCAmelCase__, tgt_lang=lowerCAmelCase__, eos_token=lowerCAmelCase__, unk_token=lowerCAmelCase__, sep_token=lowerCAmelCase__, cls_token=lowerCAmelCase__, pad_token=lowerCAmelCase__, mask_token=lowerCAmelCase__, sp_model_kwargs=self.sp_model_kwargs, **lowerCAmelCase__, ) snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(lowerCAmelCase__)) snake_case_ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token snake_case_ = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab snake_case_ = 1 snake_case_ = len(self.sp_model) snake_case_ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(lowerCAmelCase__) } snake_case_ = {v: k for k, v in self.lang_code_to_id.items()} snake_case_ = len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id) snake_case_ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} snake_case_ = src_lang if src_lang is not None else 'en_XX' snake_case_ = self.lang_code_to_id[self._src_lang] snake_case_ = tgt_lang self.set_src_lang_special_tokens(self._src_lang) @property def a_ ( self) -> int: return len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def a_ ( self) -> str: return self._src_lang @src_lang.setter def a_ ( self, lowerCAmelCase__) -> None: snake_case_ = new_src_lang self.set_src_lang_special_tokens(self._src_lang) def __getstate__( self) -> Dict: snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self, lowerCAmelCase__) -> None: 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) -> Dict: snake_case_ = {self.convert_ids_to_tokens(lowerCAmelCase__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def a_ ( self, lowerCAmelCase__) -> List[str]: return self.sp_model.encode(lowerCAmelCase__, out_type=lowerCAmelCase__) def a_ ( self, lowerCAmelCase__) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case_ = self.sp_model.PieceToId(lowerCAmelCase__) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def a_ ( self, lowerCAmelCase__) -> str: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def a_ ( self, lowerCAmelCase__) -> Tuple: 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(lowerCAmelCase__) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(lowerCAmelCase__) snake_case_ = False out_string += self.sp_model.decode(lowerCAmelCase__) return out_string.strip() def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = None) -> Tuple[str]: 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']) if os.path.abspath(self.vocab_file) != os.path.abspath(lowerCAmelCase__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file, lowerCAmelCase__) elif not os.path.isfile(self.vocab_file): with open(lowerCAmelCase__, 'wb') as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase__) return (out_vocab_file,) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = None, lowerCAmelCase__ = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCAmelCase__, token_ids_a=lowerCAmelCase__, already_has_special_tokens=lowerCAmelCase__) 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(lowerCAmelCase__)) + suffix_ones return prefix_ones + ([0] * len(lowerCAmelCase__)) + ([0] * len(lowerCAmelCase__)) + suffix_ones def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = 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 a_ ( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, **lowerCAmelCase__) -> Optional[int]: 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(lowerCAmelCase__, add_special_tokens=lowerCAmelCase__, return_tensors=lowerCAmelCase__, **lowerCAmelCase__) snake_case_ = self.convert_tokens_to_ids(lowerCAmelCase__) snake_case_ = tgt_lang_id return inputs def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = "en_XX", lowerCAmelCase__ = None, lowerCAmelCase__ = "ro_RO", **lowerCAmelCase__, ) -> BatchEncoding: snake_case_ = src_lang snake_case_ = tgt_lang return super().prepare_seqaseq_batch(lowerCAmelCase__, lowerCAmelCase__, **lowerCAmelCase__) def a_ ( self) -> Optional[int]: return self.set_src_lang_special_tokens(self.src_lang) def a_ ( self) -> Tuple: return self.set_tgt_lang_special_tokens(self.tgt_lang) def a_ ( self, lowerCAmelCase__) -> None: snake_case_ = self.lang_code_to_id[src_lang] snake_case_ = [self.cur_lang_code_id] snake_case_ = [self.eos_token_id] def a_ ( self, lowerCAmelCase__) -> None: snake_case_ = self.lang_code_to_id[tgt_lang] snake_case_ = [self.cur_lang_code_id] snake_case_ = [self.eos_token_id]
69
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging lowercase_ = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase ( ): """simple docstring""" __A = '''https://pypi.org/pypi/diffusers/json''' __A = json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys() return sorted(__UpperCamelCase , key=lambda __UpperCamelCase : version.Version(__UpperCamelCase ) ) def lowerCAmelCase ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__UpperCamelCase ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = Path(__UpperCamelCase ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" init_hf_modules() __A = Path(__UpperCamelCase ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import .xxx` __A = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Unique-ify return list(set(__UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = False __A = [module_file] __A = [] # Let's recurse through all relative imports while not no_change: __A = [] for f in files_to_check: new_imports.extend(get_relative_imports(__UpperCamelCase ) ) __A = Path(__UpperCamelCase ).parent __A = [str(module_path / m ) for m in new_imports] __A = [f for f in new_import_files if f not in all_relative_imports] __A = [f'{f}.py' for f in new_import_files] __A = len(__UpperCamelCase ) == 0 all_relative_imports.extend(__UpperCamelCase ) return all_relative_imports def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import xxx` __A = re.findall('''^\s*import\s+(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Only keep the top-level module __A = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all __A = list(set(__UpperCamelCase ) ) __A = [] for imp in imports: try: importlib.import_module(__UpperCamelCase ) except ImportError: missing_packages.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' f'{", ".join(__UpperCamelCase )}. Run `pip install {" ".join(__UpperCamelCase )}`' ) return get_relative_imports(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" __A = module_path.replace(os.path.sep , '''.''' ) __A = importlib.import_module(__UpperCamelCase ) if class_name is None: return find_pipeline_class(__UpperCamelCase ) return getattr(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" from ..pipelines import DiffusionPipeline __A = dict(inspect.getmembers(__UpperCamelCase , inspect.isclass ) ) __A = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __UpperCamelCase ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:' f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in' f' {loaded_module}.' ) __A = cls return pipeline_class def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , ): """simple docstring""" __A = str(__UpperCamelCase ) __A = os.path.join(__UpperCamelCase , __UpperCamelCase ) if os.path.isfile(__UpperCamelCase ): __A = module_file_or_url __A = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: __A = get_diffusers_versions() # cut ".dev0" __A = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: __A = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(f'Defaulting to latest_version: {revision}.' ) elif revision in available_versions: __A = f'v{revision}' elif revision == "main": __A = revision else: raise ValueError( f'`custom_revision`: {revision} does not exist. Please make sure to choose one of' f' {", ".join(available_versions + ["main"] )}.' ) # community pipeline on GitHub __A = COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase , pipeline=__UpperCamelCase ) try: __A = cached_download( __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = '''git''' __A = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise else: try: # Load from URL or cache if already cached __A = hf_hub_download( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise # Check we have all the requirements in our environment __A = check_imports(__UpperCamelCase ) # Now we move the module inside our cached dynamic modules. __A = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__UpperCamelCase ) __A = Path(__UpperCamelCase ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__UpperCamelCase , submodule_path / module_file ) for module_needed in modules_needed: __A = f'{module_needed}.py' shutil.copy(os.path.join(__UpperCamelCase , __UpperCamelCase ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__UpperCamelCase , __UpperCamelCase ): __A = use_auth_token elif use_auth_token is True: __A = HfFolder.get_token() else: __A = None __A = model_info(__UpperCamelCase , revision=__UpperCamelCase , token=__UpperCamelCase ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. __A = submodule_path / commit_hash __A = full_submodule + os.path.sep + commit_hash create_dynamic_module(__UpperCamelCase ) if not (submodule_path / module_file).exists(): shutil.copy(__UpperCamelCase , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __UpperCamelCase , f'{module_needed}.py' , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return os.path.join(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , **__UpperCamelCase , ): """simple docstring""" __A = get_cached_module_file( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return get_class_in_module(__UpperCamelCase , final_module.replace('''.py''' , '''''' ) )
266
0
'''simple docstring''' def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = len(lowerCAmelCase ) for i in range(length - 1 ): _lowerCAmelCase = i for k in range(i + 1 , lowerCAmelCase ): if collection[k] < collection[least]: _lowerCAmelCase = k if least != i: _lowerCAmelCase , _lowerCAmelCase = (collection[i], collection[least]) return collection if __name__ == "__main__": A__ : str =input('''Enter numbers separated by a comma:\n''').strip() A__ : Optional[int] =[int(item) for item in user_input.split(''',''')] print(selection_sort(unsorted))
70
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[int] ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''], model_result['''ss'''] ): __A = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sgugger/tiny-distilbert-classification''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, only_pretrain_model=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, torchscript=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''', '''Cant do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, fpaa=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) # set architectures equal to `None` __A = None __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''', '''Can\'t do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], fpaa=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, save_to_csv=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], inference_time_csv_file=os.path.join(_lowerCamelCase, '''inf_time.csv''' ), train_memory_csv_file=os.path.join(_lowerCamelCase, '''train_mem.csv''' ), inference_memory_csv_file=os.path.join(_lowerCamelCase, '''inf_mem.csv''' ), train_time_csv_file=os.path.join(_lowerCamelCase, '''train_time.csv''' ), env_info_csv_file=os.path.join(_lowerCamelCase, '''env.csv''' ), multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''env.csv''' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_lowerCamelCase : List[Any] ): self.assertTrue(hasattr(_lowerCamelCase, '''sequential''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''cumulative''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''current''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], log_filename=os.path.join(_lowerCamelCase, '''log.txt''' ), log_print=_lowerCamelCase, trace_memory_line_by_line=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''log.txt''' ) ).exists() )
266
0
import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('''Googling.....''') A_ :Tuple = '''https://www.google.com/search?q=''' + ''' '''.join(sys.argv[1:]) A_ :str = requests.get(url, headers={'''UserAgent''': UserAgent().random}) # res.raise_for_status() with open('''project1a.html''', '''wb''') as out_file: # only for knowing the class for data in res.iter_content(10000): out_file.write(data) A_ :List[Any] = BeautifulSoup(res.text, '''html.parser''') A_ :List[Any] = list(soup.select('''.eZt8xd'''))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('''href''')) else: webbrowser.open(f"https://google.com{link.get('href')}")
71
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast 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 lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = PegasusTokenizer A_ : int = PegasusTokenizerFast A_ : Optional[Any] = True A_ : Union[str, Any] = True def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def _SCREAMING_SNAKE_CASE ( self : int, **_lowerCamelCase : List[Any] ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = '''</s>''' __A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ), _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ), _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], '''<pad>''' ) self.assertEqual(vocab_keys[1], '''</s>''' ) self.assertEqual(vocab_keys[-1], '''v''' ) self.assertEqual(len(_lowerCamelCase ), 11_03 ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 11_03 ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __A = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' __A = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 __A = '''To ensure a smooth flow of bank resolutions.''' __A = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 1_50, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # fmt: off __A = {'''input_ids''': [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 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], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 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]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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='''google/bigbird-pegasus-large-arxiv''', revision='''ba85d0851d708441f91440d509690f1ab6353415''', ) @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = PegasusTokenizer A_ : Union[str, Any] = PegasusTokenizerFast A_ : Any = True A_ : str = True def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase, offset=0, mask_token_sent=_lowerCamelCase, mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], **_lowerCamelCase : Dict ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : List[str] ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 10_00, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) __A = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase, [1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1], )
266
0
"""simple docstring""" import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class __snake_case ( _lowercase): snake_case__ : List[Any] = "MCTCTFeatureExtractor" snake_case__ : Optional[int] = "AutoTokenizer" def __init__( self : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" super().__init__(__lowerCAmelCase , __lowerCAmelCase ) _lowerCamelCase : Optional[Any] = self.feature_extractor _lowerCamelCase : Optional[Any] = False def __call__( self : Optional[int] , *__lowerCAmelCase : Dict , **__lowerCAmelCase : str ): """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.''' ) _lowerCamelCase : str = kwargs.pop('''raw_speech''' ) else: _lowerCamelCase : str = kwargs.pop('''audio''' , __lowerCAmelCase ) _lowerCamelCase : Dict = kwargs.pop('''sampling_rate''' , __lowerCAmelCase ) _lowerCamelCase : List[str] = kwargs.pop('''text''' , __lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: _lowerCamelCase : Optional[Any] = args[0] _lowerCamelCase : str = 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: _lowerCamelCase : str = self.feature_extractor(__lowerCAmelCase , *__lowerCAmelCase , sampling_rate=__lowerCAmelCase , **__lowerCAmelCase ) if text is not None: _lowerCamelCase : Union[str, Any] = self.tokenizer(__lowerCAmelCase , **__lowerCAmelCase ) if text is None: return inputs elif audio is None: return encodings else: _lowerCamelCase : Dict = encodings['''input_ids'''] return inputs def SCREAMING_SNAKE_CASE ( self : Dict , *__lowerCAmelCase : List[Any] , **__lowerCAmelCase : int ): """simple docstring""" return self.tokenizer.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , *__lowerCAmelCase : Union[str, Any] , **__lowerCAmelCase : Optional[int] ): """simple docstring""" if self._in_target_context_manager: return self.current_processor.pad(*__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Tuple = kwargs.pop('''input_features''' , __lowerCAmelCase ) _lowerCamelCase : int = kwargs.pop('''labels''' , __lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: _lowerCamelCase : List[str] = args[0] _lowerCamelCase : Optional[int] = args[1:] if input_features is not None: _lowerCamelCase : int = self.feature_extractor.pad(__lowerCAmelCase , *__lowerCAmelCase , **__lowerCAmelCase ) if labels is not None: _lowerCamelCase : Tuple = self.tokenizer.pad(__lowerCAmelCase , **__lowerCAmelCase ) if labels is None: return input_features elif input_features is None: return labels else: _lowerCamelCase : Any = labels['''input_ids'''] return input_features def SCREAMING_SNAKE_CASE ( self : List[Any] , *__lowerCAmelCase : Any , **__lowerCAmelCase : Union[str, Any] ): """simple docstring""" return self.tokenizer.decode(*__lowerCAmelCase , **__lowerCAmelCase ) @contextmanager def SCREAMING_SNAKE_CASE ( self : List[str] ): """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.''' ) _lowerCamelCase : Tuple = True _lowerCamelCase : str = self.tokenizer yield _lowerCamelCase : Union[str, Any] = self.feature_extractor _lowerCamelCase : Optional[Any] = False
72
"""simple docstring""" import re def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return [char.split() for char in re.split(r'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" try: __A = split_input(__UpperCamelCase ) if upper: __A = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __A = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return to_simple_case(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" try: __A = to_simple_case(__UpperCamelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''_''' ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
266
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a ={ """configuration_mvp""": ["""MVP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MvpConfig""", """MvpOnnxConfig"""], """tokenization_mvp""": ["""MvpTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =["""MvpTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a =[ """MVP_PRETRAINED_MODEL_ARCHIVE_LIST""", """MvpForCausalLM""", """MvpForConditionalGeneration""", """MvpForQuestionAnswering""", """MvpForSequenceClassification""", """MvpModel""", """MvpPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys a =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
73
"""simple docstring""" from __future__ import annotations class snake_case : '''simple docstring''' def __init__( self : int, _lowerCamelCase : List[Any]=None ): '''simple docstring''' __A = data __A = None def __repr__( self : Union[str, Any] ): '''simple docstring''' __A = [] __A = self while temp: string_rep.append(f'{temp.data}' ) __A = temp.next return "->".join(_lowerCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not elements_list: raise Exception('''The Elements List is empty''' ) __A = __A = Node(elements_list[0] ) for i in range(1 , len(__UpperCamelCase ) ): __A = Node(elements_list[i] ) __A = current.next return head def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if head_node is not None and isinstance(__UpperCamelCase , __UpperCamelCase ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase ( ): """simple docstring""" from doctest import testmod testmod() __A = make_linked_list([1_4, 5_2, 1_4, 1_2, 4_3] ) print('''Linked List:''' ) print(__UpperCamelCase ) print('''Elements in Reverse:''' ) print_reverse(__UpperCamelCase ) if __name__ == "__main__": main()
266
0
"""simple docstring""" from collections import namedtuple _lowercase = namedtuple('''from_to''', '''from_ to''') _lowercase = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.001, 10_00), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.00_454, 264.172), '''cubicyard''': from_to(0.76_455, 1.30_795), '''cubicfoot''': from_to(0.028, 35.3_147), '''cup''': from_to(0.000_236_588, 4_226.75), } def _snake_case ( snake_case__ : float , snake_case__ : str , snake_case__ : str ): if from_type not in METRIC_CONVERSION: raise ValueError( F'Invalid \'from_type\' value: {from_type!r} Supported values are:\n' + ', '.join(snake_case__ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'Invalid \'to_type\' value: {to_type!r}. Supported values are:\n' + ', '.join(snake_case__ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
74
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : int = ["input_features", "attention_mask"] def __init__( self : Optional[Any], _lowerCamelCase : Union[str, Any]=80, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Any=80, _lowerCamelCase : List[str]=0.0, _lowerCamelCase : int=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Optional[int]=True, **_lowerCamelCase : List[str], ): '''simple docstring''' super().__init__(feature_size=_lowerCamelCase, sampling_rate=_lowerCamelCase, padding_value=_lowerCamelCase, **_lowerCamelCase ) __A = num_mel_bins __A = do_ceptral_normalize __A = normalize_means __A = normalize_vars __A = True def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : np.ndarray, ): '''simple docstring''' __A = waveform * (2**15) # Kaldi compliance: 16-bit signed integers __A = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ) __A = ta_kaldi.fbank(_lowerCamelCase, num_mel_bins=self.num_mel_bins, sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray, _lowerCamelCase : int, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : float = 0.0, ): '''simple docstring''' # make sure we normalize float32 arrays if normalize_means: __A = x[:input_length].mean(axis=0 ) __A = np.subtract(_lowerCamelCase, _lowerCamelCase ) if normalize_vars: __A = x[:input_length].std(axis=0 ) __A = np.divide(_lowerCamelCase, _lowerCamelCase ) if input_length < x.shape[0]: __A = padding_value # make sure array is in float32 __A = x.astype(np.floataa ) return x def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[np.ndarray], _lowerCamelCase : Optional[np.ndarray] = None ): '''simple docstring''' __A = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_lowerCamelCase, _lowerCamelCase, self.normalize_means, self.normalize_vars, self.padding_value ) for x, n in zip(_lowerCamelCase, _lowerCamelCase ) ] def __call__( self : Optional[Any], _lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], _lowerCamelCase : Union[bool, str, PaddingStrategy] = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : bool = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[Union[str, TensorType]] = None, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[bool] = None, **_lowerCamelCase : Optional[Any], ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __A = isinstance(_lowerCamelCase, np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __A = is_batched_numpy or ( isinstance(_lowerCamelCase, (list, tuple) ) and (isinstance(raw_speech[0], (np.ndarray, tuple, list) )) ) if is_batched: __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_lowerCamelCase, np.ndarray ): __A = np.asarray(_lowerCamelCase, dtype=np.floataa ) elif isinstance(_lowerCamelCase, np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __A = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __A = [raw_speech] # extract fbank features __A = [self._extract_fbank_features(_lowerCamelCase ) for waveform in raw_speech] # convert into correct format for padding __A = BatchFeature({'''input_features''': features} ) __A = self.pad( _lowerCamelCase, padding=_lowerCamelCase, max_length=_lowerCamelCase, truncation=_lowerCamelCase, pad_to_multiple_of=_lowerCamelCase, return_attention_mask=_lowerCamelCase, **_lowerCamelCase, ) # make sure list is in array format __A = padded_inputs.get('''input_features''' ) if isinstance(input_features[0], _lowerCamelCase ): __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for feature in input_features] __A = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __A = [np.asarray(_lowerCamelCase, dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: __A = ( np.array(_lowerCamelCase, dtype=np.intaa ) if self._get_padding_strategies(_lowerCamelCase, max_length=_lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) __A = self.normalize( padded_inputs['''input_features'''], attention_mask=_lowerCamelCase ) if return_tensors is not None: __A = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs
266
0
'''simple docstring''' import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def a_ ( __snake_case : Any ) -> int: """simple docstring""" lowerCamelCase_ =checkpoints.load_tax_checkpoint(__snake_case ) lowerCamelCase_ =flatten_dict(__snake_case ) return flax_params def a_ ( __snake_case : Dict ) -> Optional[int]: """simple docstring""" lowerCamelCase_ ={} lowerCamelCase_ ={ '''token_embedder''': '''embeddings''', '''encoder_norm''': '''layernorm''', '''kernel''': '''weight''', '''.out''': '''.output''', '''scale''': '''weight''', '''embedders_0.pos_embedding''': '''row_embedder.weight''', '''embedders_1.pos_embedding''': '''column_embedder.weight''', } lowerCamelCase_ ={ '''query''': '''attention.query''', '''key''': '''attention.key''', '''value''': '''attention.value''', '''output.dense''': '''output''', '''encoder_decoder_attention.o''': '''encoder_decoder_attention.attention.o''', '''pre_self_attention_layer_norm''': '''self_attention.layer_norm''', '''pre_cross_attention_layer_norm''': '''encoder_decoder_attention.layer_norm''', '''mlp.''': '''mlp.DenseReluDense.''', '''pre_mlp_layer_norm''': '''mlp.layer_norm''', '''self_attention.o''': '''self_attention.attention.o''', '''decoder.embeddings.embedding''': '''decoder.embed_tokens.weight''', '''decoder.relpos_bias.rel_embedding''': '''decoder.layer.0.self_attention.attention.relative_attention_bias.weight''', '''decoder.decoder_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.logits_dense.weight''': '''decoder.lm_head.weight''', } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key lowerCamelCase_ ='''.'''.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): lowerCamelCase_ =new_key.replace(__snake_case , __snake_case ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): lowerCamelCase_ =new_key.replace(__snake_case , __snake_case ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number lowerCamelCase_ =re.sub(r'''layers_(\d+)''' , r'''layer.\1''' , __snake_case ) lowerCamelCase_ =new_key.replace('''encoder''' , '''encoder.encoder''' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number lowerCamelCase_ =re.sub(r'''layers_(\d+)''' , r'''layer.\1''' , __snake_case ) lowerCamelCase_ =flax_dict[key] lowerCamelCase_ ={} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): lowerCamelCase_ =torch.from_numpy(converted_dict[key].T ) else: lowerCamelCase_ =torch.from_numpy(converted_dict[key] ) return converted_torch_dict def a_ ( __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : Any=False , __snake_case : Optional[int]=False ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ =get_flax_param(__snake_case ) if not use_large: lowerCamelCase_ =PixaStructVisionConfig() lowerCamelCase_ =PixaStructTextConfig() else: lowerCamelCase_ =PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) lowerCamelCase_ =PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) lowerCamelCase_ =PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=__snake_case ) lowerCamelCase_ =PixaStructForConditionalGeneration(__snake_case ) lowerCamelCase_ =rename_and_convert_flax_params(__snake_case ) model.load_state_dict(__snake_case ) lowerCamelCase_ =AutoTokenizer.from_pretrained('''ybelkada/test-pix2struct-tokenizer''' ) lowerCamelCase_ =PixaStructImageProcessor() lowerCamelCase_ =PixaStructProcessor(image_processor=__snake_case , tokenizer=__snake_case ) if use_large: lowerCamelCase_ =4096 lowerCamelCase_ =True # mkdir if needed os.makedirs(__snake_case , exist_ok=__snake_case ) model.save_pretrained(__snake_case ) processor.save_pretrained(__snake_case ) print('''Model saved in {}'''.format(__snake_case ) ) if __name__ == "__main__": a_ : Optional[int] = argparse.ArgumentParser() parser.add_argument("""--t5x_checkpoint_path""", default=None, type=str, help="""Path to the original T5x checkpoint.""") parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--use_large""", action="""store_true""", help="""Use large model.""") parser.add_argument("""--is_vqa""", action="""store_true""", help="""Use large model.""") a_ : Tuple = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
75
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : Optional[Any], _lowerCamelCase : Union[str, Any]=13, _lowerCamelCase : Any=3, _lowerCamelCase : Optional[int]=2_24, _lowerCamelCase : str=30, _lowerCamelCase : Dict=4_00, _lowerCamelCase : Union[str, Any]=True, _lowerCamelCase : Any=None, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Any=[0.5, 0.5, 0.5], _lowerCamelCase : List[str]=[0.5, 0.5, 0.5], ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_normalize __A = image_mean __A = image_std def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = ViTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = EfficientFormerImageProcessorTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), )
266
0
# Copyright 2021 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 packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) a_ = 'pytorch_model.bin' a_ = 'pytorch_model.bin.index.json' a_ = 'adapter_config.json' a_ = 'adapter_model.bin' a_ = 'adapter_model.safetensors' a_ = 'tf_model.h5' a_ = 'tf_model.h5.index.json' a_ = 'model.ckpt' a_ = 'flax_model.msgpack' a_ = 'flax_model.msgpack.index.json' a_ = 'model.safetensors' a_ = 'model.safetensors.index.json' a_ = 'config.json' a_ = 'preprocessor_config.json' a_ = FEATURE_EXTRACTOR_NAME a_ = 'generation_config.json' a_ = 'modelcard.json' a_ = '▁' a_ = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility a_ = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. a_ = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] a_ = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def lowerCamelCase__ ( _a): if version.parse(_a) < version.parse(_a): if "dev" in min_version: SCREAMING_SNAKE_CASE : Optional[Any] = ( "This example requires a source install from HuggingFace Transformers (see " "`https://huggingface.co/docs/transformers/installation#install-from-source`)," ) else: SCREAMING_SNAKE_CASE : List[Any] = f"This example requires a minimum version of {min_version}," error_message += f" but the version found is {__version__}.\n" raise ImportError( error_message + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other " "versions of HuggingFace Transformers.")
76
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' def __init__( self : Optional[int], *_lowerCamelCase : Union[str, Any], **_lowerCamelCase : Dict ): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''', _lowerCamelCase, ) super().__init__(*_lowerCamelCase, **_lowerCamelCase )
266
0
"""simple docstring""" def a_ ( _lowerCAmelCase : int , _lowerCAmelCase : int ): '''simple docstring''' return x if y == 0 else greatest_common_divisor(_lowerCAmelCase , x % y ) def a_ ( _lowerCAmelCase : int , _lowerCAmelCase : int ): '''simple docstring''' return (x * y) // greatest_common_divisor(_lowerCAmelCase , _lowerCAmelCase ) def a_ ( _lowerCAmelCase : int = 20 ): '''simple docstring''' lowercase__ : Dict = 1 for i in range(1 , n + 1 ): lowercase__ : List[Any] = lcm(_lowerCAmelCase , _lowerCAmelCase ) return g if __name__ == "__main__": print(f'''{solution() = }''')
77
"""simple docstring""" 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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : List[Any]=7, _lowerCamelCase : int=3, _lowerCamelCase : Optional[Any]=18, _lowerCamelCase : Any=30, _lowerCamelCase : str=4_00, _lowerCamelCase : int=True, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str=True, ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = apply_ocr def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[int] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = LayoutLMvaImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = 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 : Union[str, Any] ): '''simple docstring''' __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'''height''': 18, '''width''': 18} ) __A = 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 : Optional[Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = 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 __A = 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 : Any ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = 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 __A = 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 __A = 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 __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = 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 __A = 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 __A = 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 : List[str] ): '''simple docstring''' # with apply_OCR = True __A = LayoutLMvaImageProcessor() from datasets import load_dataset __A = load_dataset('''hf-internal-testing/fixtures_docvqa''', split='''test''' ) __A = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ), len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __A = [['''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 __A = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words, _lowerCamelCase ) self.assertListEqual(encoding.boxes, _lowerCamelCase ) # with apply_OCR = False __A = LayoutLMvaImageProcessor(apply_ocr=_lowerCamelCase ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) )
266
0
"""simple docstring""" 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 snake_case_ = logging.get_logger(__name__) # pylint: disable=invalid-name class A_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): """simple docstring""" @register_to_config def __init__( self :List[str] , lowercase_ :bool , lowercase_ :Optional[int] = None , lowercase_ :Optional[int] = None ) -> List[Any]: super().__init__() UpperCAmelCase = 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" UpperCAmelCase = torch.zeros(lowercase_ , lowercase_ ) else: UpperCAmelCase = None UpperCAmelCase = torch.nn.Parameter(lowercase_ ) class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" __UpperCamelCase = 42 __UpperCamelCase = 42 __UpperCamelCase = 42 __UpperCamelCase = 42 __UpperCamelCase = 42 __UpperCamelCase = 42 def __init__( self :Union[str, Any] , lowercase_ :VQModel , lowercase_ :CLIPTextModel , lowercase_ :CLIPTokenizer , lowercase_ :TransformeraDModel , lowercase_ :VQDiffusionScheduler , lowercase_ :LearnedClassifierFreeSamplingEmbeddings , ) -> Union[str, Any]: super().__init__() self.register_modules( vqvae=lowercase_ , transformer=lowercase_ , text_encoder=lowercase_ , tokenizer=lowercase_ , scheduler=lowercase_ , learned_classifier_free_sampling_embeddings=lowercase_ , ) def UpperCAmelCase__ ( self :Tuple , lowercase_ :List[Any] , lowercase_ :str , lowercase_ :Optional[Any] ) -> Union[str, Any]: UpperCAmelCase = len(lowercase_ ) if isinstance(lowercase_ , lowercase_ ) else 1 # get prompt text embeddings UpperCAmelCase = self.tokenizer( lowercase_ , padding='max_length' , max_length=self.tokenizer.model_max_length , return_tensors='pt' , ) UpperCAmelCase = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCAmelCase = 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}""" ) UpperCAmelCase = text_input_ids[:, : self.tokenizer.model_max_length] UpperCAmelCase = 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 UpperCAmelCase = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=lowercase_ ) # duplicate text embeddings for each generation per prompt UpperCAmelCase = prompt_embeds.repeat_interleave(lowercase_ , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: UpperCAmelCase = self.learned_classifier_free_sampling_embeddings.embeddings UpperCAmelCase = negative_prompt_embeds.unsqueeze(0 ).repeat(lowercase_ , 1 , 1 ) else: UpperCAmelCase = [''] * batch_size UpperCAmelCase = text_input_ids.shape[-1] UpperCAmelCase = self.tokenizer( lowercase_ , padding='max_length' , max_length=lowercase_ , truncation=lowercase_ , return_tensors='pt' , ) UpperCAmelCase = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings UpperCAmelCase = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=lowercase_ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCAmelCase = negative_prompt_embeds.shape[1] UpperCAmelCase = negative_prompt_embeds.repeat(1 , lowercase_ , 1 ) UpperCAmelCase = negative_prompt_embeds.view(batch_size * num_images_per_prompt , lowercase_ , -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 UpperCAmelCase = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self :str , lowercase_ :Union[str, List[str]] , lowercase_ :int = 1_00 , lowercase_ :float = 5.0 , lowercase_ :float = 1.0 , lowercase_ :int = 1 , lowercase_ :Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowercase_ :Optional[torch.FloatTensor] = None , lowercase_ :Optional[str] = "pil" , lowercase_ :bool = True , lowercase_ :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowercase_ :int = 1 , ) -> Union[ImagePipelineOutput, Tuple]: if isinstance(lowercase_ , lowercase_ ): UpperCAmelCase = 1 elif isinstance(lowercase_ , lowercase_ ): UpperCAmelCase = len(lowercase_ ) else: raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(lowercase_ )}""" ) UpperCAmelCase = batch_size * num_images_per_prompt UpperCAmelCase = guidance_scale > 1.0 UpperCAmelCase = self._encode_prompt(lowercase_ , lowercase_ , lowercase_ ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(lowercase_ , lowercase_ ) or callback_steps <= 0) ): raise ValueError( f"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" f""" {type(lowercase_ )}.""" ) # get the initial completely masked latents unless the user supplied it UpperCAmelCase = (batch_size, self.transformer.num_latent_pixels) if latents is None: UpperCAmelCase = self.transformer.num_vector_embeds - 1 UpperCAmelCase = torch.full(lowercase_ , lowercase_ ).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).""" ) UpperCAmelCase = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(lowercase_ , device=self.device ) UpperCAmelCase = self.scheduler.timesteps.to(self.device ) UpperCAmelCase = latents for i, t in enumerate(self.progress_bar(lowercase_ ) ): # expand the sample if we are doing classifier free guidance UpperCAmelCase = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` UpperCAmelCase = self.transformer(lowercase_ , encoder_hidden_states=lowercase_ , timestep=lowercase_ ).sample if do_classifier_free_guidance: UpperCAmelCase , UpperCAmelCase = model_output.chunk(2 ) UpperCAmelCase = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(lowercase_ , dim=1 , keepdim=lowercase_ ) UpperCAmelCase = self.truncate(lowercase_ , lowercase_ ) # remove `log(0)`'s (`-inf`s) UpperCAmelCase = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 UpperCAmelCase = self.scheduler.step(lowercase_ , timestep=lowercase_ , sample=lowercase_ , generator=lowercase_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(lowercase_ , lowercase_ , lowercase_ ) UpperCAmelCase = self.vqvae.config.vq_embed_dim UpperCAmelCase = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) UpperCAmelCase = self.vqvae.quantize.get_codebook_entry(lowercase_ , shape=lowercase_ ) UpperCAmelCase = self.vqvae.decode(lowercase_ , force_not_quantize=lowercase_ ).sample UpperCAmelCase = (image / 2 + 0.5).clamp(0 , 1 ) UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCAmelCase = self.numpy_to_pil(lowercase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowercase_ ) def UpperCAmelCase__ ( self :int , lowercase_ :torch.FloatTensor , lowercase_ :float ) -> torch.FloatTensor: UpperCAmelCase , UpperCAmelCase = torch.sort(lowercase_ , 1 , descending=lowercase_ ) UpperCAmelCase = torch.exp(lowercase_ ) UpperCAmelCase = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out UpperCAmelCase = torch.full_like(keep_mask[:, 0:1, :] , lowercase_ ) UpperCAmelCase = torch.cat((all_true, keep_mask) , dim=1 ) UpperCAmelCase = keep_mask[:, :-1, :] UpperCAmelCase = keep_mask.gather(1 , indices.argsort(1 ) ) UpperCAmelCase = log_p_x_0.clone() UpperCAmelCase = -torch.inf # -inf = log(0) return rv
78
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): '''simple docstring''' A_ : List[str] = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = False ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = True ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def lowerCAmelCase ( ): """simple docstring""" try: hide_cursor() yield finally: show_cursor()
266
0
'''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 lowerCamelCase_ = logging.getLogger(__name__) lowerCamelCase_ = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) lowerCamelCase_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _UpperCAmelCase : """simple docstring""" snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization. Leave None if you want to train a model from''' ''' scratch.''' ) } , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case_ )} , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) @dataclass class _UpperCAmelCase : """simple docstring""" snake_case = field( default=snake_case_ , metadata={'''help''': '''The input training data file (a text file).'''} ) snake_case = field( default=snake_case_ , 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''' ) } , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''} , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''} , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''} , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''} ) snake_case = field(default=snake_case_ , metadata={'''help''': '''Whether ot not to use whole word mask.'''} ) snake_case = field( default=0.15 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) snake_case = field( default=1 / 6 , metadata={ '''help''': ( '''Ratio of length of a span of masked tokens to surrounding context length for permutation language''' ''' modeling.''' ) } , ) snake_case = field( default=5 , metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''} ) snake_case = 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).''' ) } , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) def __lowercase ( __lowercase , __lowercase , __lowercase = False , __lowercase = None , ) -> Optional[Any]: '''simple docstring''' def _dataset(__lowercase , __lowercase=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=__lowercase , file_path=__lowercase , block_size=args.block_size , ref_path=__lowercase , ) return LineByLineTextDataset(tokenizer=__lowercase , file_path=__lowercase , block_size=args.block_size ) else: return TextDataset( tokenizer=__lowercase , file_path=__lowercase , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=__lowercase , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(__lowercase ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def __lowercase ( ) -> Dict: '''simple docstring''' _A = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _A , _A , _A = 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" , __lowercase ) # 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: _A = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _A = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: _A = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch." ) if model_args.tokenizer_name: _A = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: _A = 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: _A = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=__lowercase , cache_dir=model_args.cache_dir , ) else: logger.info("Training new model from scratch" ) _A = AutoModelWithLMHead.from_config(__lowercase ) model.resize_token_embeddings(len(__lowercase ) ) 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: _A = tokenizer.max_len # Our input block size will be the max possible for the model else: _A = min(data_args.block_size , tokenizer.max_len ) # Get datasets _A = ( get_dataset(__lowercase , tokenizer=__lowercase , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) _A = ( get_dataset(__lowercase , tokenizer=__lowercase , evaluate=__lowercase , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": _A = DataCollatorForPermutationLanguageModeling( tokenizer=__lowercase , 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: _A = DataCollatorForWholeWordMask( tokenizer=__lowercase , mlm_probability=data_args.mlm_probability ) else: _A = DataCollatorForLanguageModeling( tokenizer=__lowercase , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer _A = Trainer( model=__lowercase , args=__lowercase , data_collator=__lowercase , train_dataset=__lowercase , eval_dataset=__lowercase , prediction_loss_only=__lowercase , ) # Training if training_args.do_train: _A = ( 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=__lowercase ) 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 _A = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) _A = trainer.evaluate() _A = math.exp(eval_output["eval_loss"] ) _A = {"perplexity": perplexity} _A = os.path.join(training_args.output_dir , "eval_results_lm.txt" ) if trainer.is_world_master(): with open(__lowercase , "w" ) as writer: logger.info("***** Eval results *****" ) for key in sorted(result.keys() ): logger.info(" %s = %s" , __lowercase , str(result[key] ) ) writer.write("%s = %s\n" % (key, str(result[key] )) ) results.update(__lowercase ) return results def __lowercase ( __lowercase ) -> str: '''simple docstring''' main() if __name__ == "__main__": main()
79
"""simple docstring""" import argparse import struct import unittest class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : bytes ): '''simple docstring''' __A = data # Initialize hash values __A = [ 0X6a_09e_667, 0Xbb_67a_e85, 0X3c_6ef_372, 0Xa5_4ff_53a, 0X51_0e5_27f, 0X9b_056_88c, 0X1f_83d_9ab, 0X5b_e0c_d19, ] # Initialize round constants __A = [ 0X42_8a2_f98, 0X71_374_491, 0Xb5_c0f_bcf, 0Xe9_b5d_ba5, 0X39_56c_25b, 0X59_f11_1f1, 0X92_3f8_2a4, 0Xab_1c5_ed5, 0Xd8_07a_a98, 0X12_835_b01, 0X24_318_5be, 0X55_0c7_dc3, 0X72_be5_d74, 0X80_deb_1fe, 0X9b_dc0_6a7, 0Xc1_9bf_174, 0Xe4_9b6_9c1, 0Xef_be4_786, 0X0f_c19_dc6, 0X24_0ca_1cc, 0X2d_e92_c6f, 0X4a_748_4aa, 0X5c_b0a_9dc, 0X76_f98_8da, 0X98_3e5_152, 0Xa8_31c_66d, 0Xb0_032_7c8, 0Xbf_597_fc7, 0Xc6_e00_bf3, 0Xd5_a79_147, 0X06_ca6_351, 0X14_292_967, 0X27_b70_a85, 0X2e_1b2_138, 0X4d_2c6_dfc, 0X53_380_d13, 0X65_0a7_354, 0X76_6a0_abb, 0X81_c2c_92e, 0X92_722_c85, 0Xa2_bfe_8a1, 0Xa8_1a6_64b, 0Xc2_4b8_b70, 0Xc7_6c5_1a3, 0Xd1_92e_819, 0Xd6_990_624, 0Xf4_0e3_585, 0X10_6aa_070, 0X19_a4c_116, 0X1e_376_c08, 0X27_487_74c, 0X34_b0b_cb5, 0X39_1c0_cb3, 0X4e_d8a_a4a, 0X5b_9cc_a4f, 0X68_2e6_ff3, 0X74_8f8_2ee, 0X78_a56_36f, 0X84_c87_814, 0X8c_c70_208, 0X90_bef_ffa, 0Xa4_506_ceb, 0Xbe_f9a_3f7, 0Xc6_717_8f2, ] __A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : bytes ): '''simple docstring''' __A = b'''\x80''' + (b'''\x00''' * (63 - (len(_lowerCamelCase ) + 8) % 64)) __A = struct.pack('''>Q''', (len(_lowerCamelCase ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' # Convert into blocks of 64 bytes __A = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data ), 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __A = list(struct.unpack('''>16L''', _lowerCamelCase ) ) # add 48 0-ed integers words += [0] * 48 __A , __A , __A , __A , __A , __A , __A , __A = self.hashes for index in range(0, 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __A = ( self.ror(words[index - 15], 7 ) ^ self.ror(words[index - 15], 18 ) ^ (words[index - 15] >> 3) ) __A = ( self.ror(words[index - 2], 17 ) ^ self.ror(words[index - 2], 19 ) ^ (words[index - 2] >> 10) ) __A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X100_000_000 # Compression __A = self.ror(_lowerCamelCase, 6 ) ^ self.ror(_lowerCamelCase, 11 ) ^ self.ror(_lowerCamelCase, 25 ) __A = (e & f) ^ ((~e & 0Xff_fff_fff) & g) __A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X100_000_000 __A = self.ror(_lowerCamelCase, 2 ) ^ self.ror(_lowerCamelCase, 13 ) ^ self.ror(_lowerCamelCase, 22 ) __A = (a & b) ^ (a & c) ^ (b & c) __A = (sa + maj) % 0X100_000_000 __A , __A , __A , __A , __A , __A , __A , __A = ( g, f, e, ((d + tempa) % 0X100_000_000), c, b, a, ((tempa + tempa) % 0X100_000_000), ) __A = [a, b, c, d, e, f, g, h] # Modify final values __A = [ ((element + mutated_hash_values[index]) % 0X100_000_000) for index, element in enumerate(self.hashes ) ] __A = ''''''.join([hex(_lowerCamelCase )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' return 0Xff_fff_fff & (value << (32 - rotations)) | (value >> rotations) class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' import hashlib __A = bytes('''Test String''', '''utf-8''' ) self.assertEqual(SHAaaa(_lowerCamelCase ).hash, hashlib.shaaaa(_lowerCamelCase ).hexdigest() ) def lowerCAmelCase ( ): """simple docstring""" import doctest doctest.testmod() __A = argparse.ArgumentParser() parser.add_argument( '''-s''' , '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument( '''-f''' , '''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) __A = parser.parse_args() __A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: __A = f.read() else: __A = bytes(__UpperCamelCase , '''utf-8''' ) print(SHAaaa(__UpperCamelCase ).hash ) if __name__ == "__main__": main()
266
0
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class lowercase_ ( a__ ): @staticmethod @abstractmethod def __a ( a ): raise NotImplementedError() @abstractmethod def __a ( self ): raise NotImplementedError()
80
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowercase_ = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' lowercase_ = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' lowercase_ = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, homepage='''https://github.com/krishnap25/mauve''', inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''string''', id='''sequence''' ), '''references''': datasets.Value('''string''', id='''sequence''' ), } ), codebase_urls=['''https://github.com/krishnap25/mauve'''], reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ], ) def _SCREAMING_SNAKE_CASE ( self : int, _lowerCamelCase : str, _lowerCamelCase : Optional[Any], _lowerCamelCase : Any=None, _lowerCamelCase : Tuple=None, _lowerCamelCase : Optional[Any]=None, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str="auto", _lowerCamelCase : Union[str, Any]=-1, _lowerCamelCase : List[str]=0.9, _lowerCamelCase : int=5, _lowerCamelCase : Tuple=5_00, _lowerCamelCase : Union[str, Any]="gpt2-large", _lowerCamelCase : int=-1, _lowerCamelCase : Union[str, Any]=10_24, _lowerCamelCase : Union[str, Any]=25, _lowerCamelCase : str=5, _lowerCamelCase : Any=True, _lowerCamelCase : Union[str, Any]=25, ): '''simple docstring''' __A = compute_mauve( p_text=_lowerCamelCase, q_text=_lowerCamelCase, p_features=_lowerCamelCase, q_features=_lowerCamelCase, p_tokens=_lowerCamelCase, q_tokens=_lowerCamelCase, num_buckets=_lowerCamelCase, pca_max_data=_lowerCamelCase, kmeans_explained_var=_lowerCamelCase, kmeans_num_redo=_lowerCamelCase, kmeans_max_iter=_lowerCamelCase, featurize_model_name=_lowerCamelCase, device_id=_lowerCamelCase, max_text_length=_lowerCamelCase, divergence_curve_discretization_size=_lowerCamelCase, mauve_scaling_factor=_lowerCamelCase, verbose=_lowerCamelCase, seed=_lowerCamelCase, ) return out
266
0
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def _A ( ): """simple docstring""" a =ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=lowercase ) a =parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=lowercase ) env_command_parser(subparsers=lowercase ) launch_command_parser(subparsers=lowercase ) tpu_command_parser(subparsers=lowercase ) test_command_parser(subparsers=lowercase ) # Let's go a =parser.parse_args() if not hasattr(lowercase , '''func''' ): parser.print_help() exit(1 ) # Run args.func(lowercase ) if __name__ == "__main__": main()
81
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowercase_ = imread(R'digital_image_processing/image_data/lena_small.jpg') lowercase_ = cvtColor(img, COLOR_BGR2GRAY) def lowerCAmelCase ( ): """simple docstring""" __A = cn.convert_to_negative(__UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def lowerCAmelCase ( ): """simple docstring""" with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(__UpperCamelCase , 1_1_0 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def lowerCAmelCase ( ): """simple docstring""" __A = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def lowerCAmelCase ( ): """simple docstring""" __A = imread('''digital_image_processing/image_data/lena_small.jpg''' , 0 ) # assert ambiguous array for all == True assert canny_img.all() __A = canny.canny(__UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def lowerCAmelCase ( ): """simple docstring""" assert gg.gaussian_filter(__UpperCamelCase , 5 , sigma=0.9 ).all() def lowerCAmelCase ( ): """simple docstring""" __A = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __A = conv.img_convolve(__UpperCamelCase , __UpperCamelCase ).astype(__UpperCamelCase ) assert res.any() def lowerCAmelCase ( ): """simple docstring""" assert med.median_filter(__UpperCamelCase , 3 ).any() def lowerCAmelCase ( ): """simple docstring""" __A , __A = sob.sobel_filter(__UpperCamelCase ) assert grad.any() and theta.any() def lowerCAmelCase ( ): """simple docstring""" __A = sp.make_sepia(__UpperCamelCase , 2_0 ) assert sepia.all() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" __A = bs.Burkes(imread(__UpperCamelCase , 1 ) , 1_2_0 ) burkes.process() assert burkes.output_img.any() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" __A = rs.NearestNeighbour(imread(__UpperCamelCase , 1 ) , 4_0_0 , 2_0_0 ) nn.process() assert nn.output.any() def lowerCAmelCase ( ): """simple docstring""" __A = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. __A = imread(__UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __A = 0 __A = 0 __A = image[x_coordinate][y_coordinate] __A = lbp.get_neighbors_pixel( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __A = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __A = lbp.local_binary_value(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert lbp_image.any()
266
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
82
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase_ = random.Random() if is_torch_available(): import torch def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase=1.0 , __UpperCamelCase=None , __UpperCamelCase=None ): """simple docstring""" if rng is None: __A = global_rng __A = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any, _lowerCamelCase : List[str], _lowerCamelCase : Any=7, _lowerCamelCase : Optional[int]=4_00, _lowerCamelCase : Optional[int]=20_00, _lowerCamelCase : Dict=1, _lowerCamelCase : Optional[Any]=0.0, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : Dict=True, ): '''simple docstring''' __A = parent __A = batch_size __A = min_seq_length __A = max_seq_length __A = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __A = feature_size __A = padding_value __A = sampling_rate __A = return_attention_mask __A = do_normalize def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[Any]=False, _lowerCamelCase : int=False ): '''simple docstring''' def _flatten(_lowerCamelCase : List[str] ): return list(itertools.chain(*_lowerCamelCase ) ) if equal_length: __A = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __A = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: __A = [np.asarray(_lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : int = ASTFeatureExtractor def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ASTFeatureExtractionTester(self ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' # Tests that all call wrap to encode_plus and batch_encode_plus __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __A = [floats_list((1, x) )[0] for x in range(8_00, 14_00, 2_00 )] __A = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] # Test not batched input __A = feat_extract(speech_inputs[0], return_tensors='''np''' ).input_values __A = feat_extract(np_speech_inputs[0], return_tensors='''np''' ).input_values self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test batched __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __A = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] __A = np.asarray(_lowerCamelCase ) __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' import torch __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __A = np.random.rand(1_00 ).astype(np.floataa ) __A = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Union[str, Any] ): '''simple docstring''' from datasets import load_dataset __A = load_dataset('''hf-internal-testing/librispeech_asr_dummy''', '''clean''', split='''validation''' ) # automatic decoding with librispeech __A = ds.sort('''id''' ).select(range(_lowerCamelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # fmt: off __A = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on __A = self._load_datasamples(1 ) __A = ASTFeatureExtractor() __A = feature_extractor(_lowerCamelCase, return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape, (1, 10_24, 1_28) ) self.assertTrue(torch.allclose(input_values[0, 0, :30], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' from PIL import Image def A__ ( UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : int = (2_5_9 * (level + 2_5_5)) / (2_5_5 * (2_5_9 - level)) def contrast(UpperCAmelCase_ ) -> int: return int(1_2_8 + factor * (c - 1_2_8) ) return img.point(UpperCAmelCase_ ) if __name__ == "__main__": # Load image with Image.open('image_data/lena.jpg') as img: # Change contrast to 170 snake_case_ : List[str] = change_contrast(img, 170) cont_img.save('image_data/lena_high_contrast.png', format='png')
83
"""simple docstring""" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = current_set.copy() for row_index, row in enumerate(__UpperCamelCase ): __A = row[0] for column_index, column in enumerate(__UpperCamelCase ): if magnitude == 0: __A = column continue __A = column / magnitude # Subtract to cancel term __A = current_set[0] __A = [first_row] __A = current_set[1::] for row in current_set: __A = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__UpperCamelCase ) continue for column_index in range(len(__UpperCamelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__UpperCamelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: __A = final_set[0] __A = [] __A = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __A = simplify(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __UpperCamelCase ) __A = resultant return final_set def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if len(__UpperCamelCase ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) __A = len(__UpperCamelCase ) + 1 if any(len(__UpperCamelCase ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__UpperCamelCase , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__UpperCamelCase ) == 1: return [equations[0][-1] / equations[0][0]] __A = equations.copy() if any(0 in row for row in data_set ): __A = data_set.copy() __A = [] for row_index, row in enumerate(__UpperCamelCase ): if 0 not in row: __A = data_set.pop(__UpperCamelCase ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __UpperCamelCase ) __A = data_set.copy() __A = simplify(__UpperCamelCase ) __A = simplified[::-1] __A = [] for row in simplified: __A = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __A = row.copy()[: len(__UpperCamelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__UpperCamelCase ) == 0: solutions.append(0 ) continue __A = temp_row[1::] __A = temp_row[::-1] for column_index, column in enumerate(__UpperCamelCase ): current_solution -= column * solutions[column_index] solutions.append(__UpperCamelCase ) __A = [] for item in solutions: final.append(float(round(__UpperCamelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
266
0
"""simple docstring""" from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class _SCREAMING_SNAKE_CASE ( A__ ): def __init__( self , __A = None , __A = None , __A = None , __A = None , __A = False , __A = False , __A = None , **__A , ) -> List[str]: lowerCAmelCase_ :List[str] = path_or_paths lowerCAmelCase_ :int = split if split or isinstance(__A , __A ) else """train""" lowerCAmelCase_ :Tuple = features lowerCAmelCase_ :str = cache_dir lowerCAmelCase_ :int = keep_in_memory lowerCAmelCase_ :Tuple = streaming lowerCAmelCase_ :Optional[int] = num_proc lowerCAmelCase_ :Optional[int] = kwargs @abstractmethod def __lowerCAmelCase ( self ) -> Union[Dataset, DatasetDict, IterableDataset, IterableDatasetDict]: pass class _SCREAMING_SNAKE_CASE ( A__ ): def __init__( self , __A = None , __A = None , __A = False , __A = False , __A = None , **__A , ) -> int: lowerCAmelCase_ :List[Any] = features lowerCAmelCase_ :str = cache_dir lowerCAmelCase_ :List[str] = keep_in_memory lowerCAmelCase_ :Union[str, Any] = streaming lowerCAmelCase_ :List[Any] = num_proc lowerCAmelCase_ :List[str] = kwargs @abstractmethod def __lowerCAmelCase ( self ) -> Union[Dataset, IterableDataset]: pass
84
"""simple docstring""" from __future__ import annotations from typing import Any def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not postfix_notation: return 0 __A = {'''+''', '''-''', '''*''', '''/'''} __A = [] for token in postfix_notation: if token in operations: __A , __A = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(__UpperCamelCase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
266
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _SCREAMING_SNAKE_CASE : Dict = { "configuration_rag": ["RagConfig"], "retrieval_rag": ["RagRetriever"], "tokenization_rag": ["RagTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Optional[int] = [ "RagModel", "RagPreTrainedModel", "RagSequenceForGeneration", "RagTokenForGeneration", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : List[Any] = [ "TFRagModel", "TFRagPreTrainedModel", "TFRagSequenceForGeneration", "TFRagTokenForGeneration", ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys _SCREAMING_SNAKE_CASE : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
"""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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple, _lowerCamelCase : List[str]=13, _lowerCamelCase : Optional[Any]=7, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : int=True, _lowerCamelCase : List[str]=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : int=99, _lowerCamelCase : Optional[int]=32, _lowerCamelCase : Tuple=5, _lowerCamelCase : Tuple=4, _lowerCamelCase : str=37, _lowerCamelCase : Union[str, Any]="gelu", _lowerCamelCase : int=0.1, _lowerCamelCase : List[Any]=0.1, _lowerCamelCase : Dict=5_12, _lowerCamelCase : List[Any]=16, _lowerCamelCase : Any=2, _lowerCamelCase : Any=0.02, _lowerCamelCase : Dict=4, ): '''simple docstring''' __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_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_choices def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __A = None if self.use_attention_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 = 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 _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Dict = True A_ : Tuple = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = FlaxRoFormerModelTester(self ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''', from_pt=_lowerCamelCase ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase ) @require_flax class snake_case ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __A = jnp.array([[0, 1, 2, 3, 4, 5]] ) __A = model(_lowerCamelCase )[0] __A = 5_00_00 __A = (1, 6, vocab_size) self.assertEqual(output.shape, _lowerCamelCase ) __A = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3], _lowerCamelCase, atol=1e-4 ) )
266
0
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase ): if not head: return True # split the list to two parts __lowerCAmelCase , __lowerCAmelCase : Optional[int] = head.next, head while fast and fast.next: __lowerCAmelCase : Any = fast.next.next __lowerCAmelCase : Any = slow.next __lowerCAmelCase : Optional[Any] = slow.next __lowerCAmelCase : Tuple = None # Don't forget here! But forget still works! # reverse the second part __lowerCAmelCase : Union[str, Any] = None while second: __lowerCAmelCase : List[Any] = second.next __lowerCAmelCase : Optional[Any] = node __lowerCAmelCase : List[str] = second __lowerCAmelCase : int = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False __lowerCAmelCase : Any = node.next __lowerCAmelCase : Any = head.next return True def __lowerCAmelCase (_UpperCamelCase ): if not head or not head.next: return True # 1. Get the midpoint (slow) __lowerCAmelCase : Optional[int] = head while fast and fast.next: __lowerCAmelCase , __lowerCAmelCase : List[str] = fast.next.next, slow.next # 2. Push the second half into the stack __lowerCAmelCase : Tuple = [slow.val] while slow.next: __lowerCAmelCase : Dict = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False __lowerCAmelCase : Tuple = cur.next return True def __lowerCAmelCase (_UpperCamelCase ): if not head or not head.next: return True __lowerCAmelCase : Tuple = {} __lowerCAmelCase : Optional[Any] = 0 while head: if head.val in d: d[head.val].append(_UpperCamelCase ) else: __lowerCAmelCase : Dict = [pos] __lowerCAmelCase : int = head.next pos += 1 __lowerCAmelCase : Union[str, Any] = pos - 1 __lowerCAmelCase : List[Any] = 0 for v in d.values(): if len(_UpperCamelCase ) % 2 != 0: middle += 1 else: __lowerCAmelCase : List[str] = 0 for i in range(0 , len(_UpperCamelCase ) ): if v[i] + v[len(_UpperCamelCase ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
86
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase ( __UpperCamelCase = 1_0_0_0_0_0_0 , __UpperCamelCase = 1_0 ): """simple docstring""" __A = defaultdict(__UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __A = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __A = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(__UpperCamelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 1_0 ) if __name__ == "__main__": print(F'''{solution() = }''')
266
0
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging UpperCamelCase = logging.get_logger(__name__) class snake_case_ : __A : str __A : str = None @staticmethod def __UpperCamelCase ( ) -> Union[str, Any]: raise NotImplementedError def __UpperCamelCase ( self : Optional[Any] , lowercase_ : List[str] , lowercase_ : int , lowercase_ : str , **lowercase_ : Dict ) -> int: raise NotImplementedError def __UpperCamelCase ( self : Any , lowercase_ : int ) -> List[str]: raise NotImplementedError def __UpperCamelCase ( self : str ) -> int: if not self.is_available(): raise RuntimeError( F'''You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.''' ) @classmethod def __UpperCamelCase ( cls : Optional[Any] ) -> Union[str, Any]: return F'''`pip install {cls.pip_package or cls.name}`''' class snake_case_ ( __A ): __A : List[str] = "optuna" @staticmethod def __UpperCamelCase ( ) -> int: return is_optuna_available() def __UpperCamelCase ( self : Optional[Any] , lowercase_ : str , lowercase_ : int , lowercase_ : str , **lowercase_ : Optional[Any] ) -> Optional[int]: return run_hp_search_optuna(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ) def __UpperCamelCase ( self : Tuple , lowercase_ : Optional[int] ) -> Any: return default_hp_space_optuna(lowercase_ ) class snake_case_ ( __A ): __A : Optional[Any] = "ray" __A : Dict = "'ray[tune]'" @staticmethod def __UpperCamelCase ( ) -> Tuple: return is_ray_available() def __UpperCamelCase ( self : Dict , lowercase_ : Dict , lowercase_ : int , lowercase_ : str , **lowercase_ : Any ) -> Optional[int]: return run_hp_search_ray(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ) def __UpperCamelCase ( self : List[Any] , lowercase_ : int ) -> Tuple: return default_hp_space_ray(lowercase_ ) class snake_case_ ( __A ): __A : List[Any] = "sigopt" @staticmethod def __UpperCamelCase ( ) -> Union[str, Any]: return is_sigopt_available() def __UpperCamelCase ( self : List[Any] , lowercase_ : str , lowercase_ : int , lowercase_ : str , **lowercase_ : Any ) -> Any: return run_hp_search_sigopt(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ) def __UpperCamelCase ( self : Optional[Any] , lowercase_ : Optional[Any] ) -> Optional[Any]: return default_hp_space_sigopt(lowercase_ ) class snake_case_ ( __A ): __A : Any = "wandb" @staticmethod def __UpperCamelCase ( ) -> List[Any]: return is_wandb_available() def __UpperCamelCase ( self : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : int , lowercase_ : str , **lowercase_ : Dict ) -> Dict: return run_hp_search_wandb(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ) def __UpperCamelCase ( self : List[str] , lowercase_ : Optional[Any] ) -> Dict: return default_hp_space_wandb(lowercase_ ) UpperCamelCase = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def lowercase_ ( ): lowercase__ : Dict = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(_lowerCamelCase) > 0: lowercase__ : List[str] = available_backends[0].name if len(_lowerCamelCase) > 1: logger.info( f'''{len(_lowerCamelCase)} hyperparameter search backends available. Using {name} as the default.''') return name raise RuntimeError( "No hyperparameter search backend available.\n" + "\n".join( f''' - To install {backend.name} run {backend.pip_install()}''' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values()))
87
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : Optional[int]=2, _lowerCamelCase : Optional[int]=3, _lowerCamelCase : int=64, _lowerCamelCase : List[str]=None ): '''simple docstring''' __A = np.random.default_rng(_lowerCamelCase ) __A = length __A = rng.normal(size=(length,) ).astype(np.floataa ) __A = a * self.x + b + rng.normal(scale=0.1, size=(length,) ).astype(np.floataa ) def __len__( self : str ): '''simple docstring''' return self.length def __getitem__( self : Dict, _lowerCamelCase : Optional[int] ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple=0, _lowerCamelCase : Any=0, _lowerCamelCase : Optional[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Optional[Any]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a[0] + self.b[0] class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : str, _lowerCamelCase : Optional[Any]=0, _lowerCamelCase : Any=0, _lowerCamelCase : List[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[str]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a + self.b def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase = 1_6 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __A = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __A = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __A = load_dataset('''csv''' , data_files=__UpperCamelCase ) __A = datasets['''train'''].unique('''label''' ) __A = {v: i for i, v in enumerate(__UpperCamelCase )} def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding='''max_length''' ) if "label" in examples: __A = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __A = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(__UpperCamelCase ): # 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(__UpperCamelCase , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' ) return tokenizer.pad(__UpperCamelCase , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __A = DataLoader(tokenized_datasets['''train'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2 ) __A = DataLoader(tokenized_datasets['''validation'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
266
0
def a__ ( A_, A_ ): '''simple docstring''' def get_matched_characters(A_, A_ ) -> str: __magic_name__ = [] __magic_name__ = min(len(_stra ), len(_stra ) ) // 2 for i, l in enumerate(_stra ): __magic_name__ = int(max(0, i - limit ) ) __magic_name__ = int(min(i + limit + 1, len(_stra ) ) ) if l in _stra[left:right]: matched.append(A_ ) __magic_name__ = f'''{_stra[0:_stra.index(A_ )]} {_stra[_stra.index(A_ ) + 1:]}''' return "".join(A_ ) # matching characters __magic_name__ = get_matched_characters(A_, A_ ) __magic_name__ = get_matched_characters(A_, A_ ) __magic_name__ = len(A_ ) # transposition __magic_name__ = ( len([(ca, ca) for ca, ca in zip(A_, A_ ) if ca != ca] ) // 2 ) if not match_count: __magic_name__ = 0.0 else: __magic_name__ = ( 1 / 3 * ( match_count / len(A_ ) + match_count / len(A_ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters __magic_name__ = 0 for ca, ca in zip(stra[:4], stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('hello', 'world'))
88
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowercase_ = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' lowercase_ = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' lowercase_ = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), id='''references''' ), } ), ) def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[List[List[str]]], _lowerCamelCase : List[List[str]], _lowerCamelCase : int = 1, _lowerCamelCase : int = 4, ): '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCamelCase, hypotheses=_lowerCamelCase, min_len=_lowerCamelCase, max_len=_lowerCamelCase ) }
266
0
'''simple docstring''' def __lowerCamelCase ( lowerCAmelCase_ = 4000000 ) -> int: _a : Optional[Any] = [0, 1] _a : str = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 _a : List[Any] = 0 for j in range(len(lowerCAmelCase_ ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"""{solution() = }""")
89
"""simple docstring""" class snake_case : '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : list[int] ): '''simple docstring''' __A = len(_lowerCamelCase ) __A = [0] * len_array if len_array > 0: __A = array[0] for i in range(1, _lowerCamelCase ): __A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : int ): '''simple docstring''' __A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_lowerCamelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
266
0
from __future__ import annotations import math def lowerCamelCase_ ( UpperCamelCase__ : list , UpperCamelCase__ : list ) -> list: """simple docstring""" if len(UpperCamelCase__ ) != 2 or len(a[0] ) != 2 or len(UpperCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def lowerCamelCase_ ( UpperCamelCase__ : list , UpperCamelCase__ : list ) -> List[str]: """simple docstring""" return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(UpperCamelCase__ ) ) ] def lowerCamelCase_ ( UpperCamelCase__ : list , UpperCamelCase__ : list ) -> Optional[Any]: """simple docstring""" return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(UpperCamelCase__ ) ) ] def lowerCamelCase_ ( UpperCamelCase__ : list ) -> tuple[list, list, list, list]: """simple docstring""" if len(UpperCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase = len(UpperCamelCase__ ) __lowerCamelCase = matrix_length // 2 __lowerCamelCase = [[a[i][j] for j in range(UpperCamelCase__ , UpperCamelCase__ )] for i in range(UpperCamelCase__ )] __lowerCamelCase = [ [a[i][j] for j in range(UpperCamelCase__ , UpperCamelCase__ )] for i in range(UpperCamelCase__ , UpperCamelCase__ ) ] __lowerCamelCase = [[a[i][j] for j in range(UpperCamelCase__ )] for i in range(UpperCamelCase__ )] __lowerCamelCase = [[a[i][j] for j in range(UpperCamelCase__ )] for i in range(UpperCamelCase__ , UpperCamelCase__ )] return top_left, top_right, bot_left, bot_right def lowerCamelCase_ ( UpperCamelCase__ : list ) -> tuple[int, int]: """simple docstring""" return len(UpperCamelCase__ ), len(matrix[0] ) def lowerCamelCase_ ( UpperCamelCase__ : list ) -> None: """simple docstring""" print('\n'.join(str(UpperCamelCase__ ) for line in matrix ) ) def lowerCamelCase_ ( UpperCamelCase__ : list , UpperCamelCase__ : list ) -> list: """simple docstring""" if matrix_dimensions(UpperCamelCase__ ) == (2, 2): return default_matrix_multiplication(UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = split_matrix(UpperCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = split_matrix(UpperCamelCase__ ) __lowerCamelCase = actual_strassen(UpperCamelCase__ , matrix_subtraction(UpperCamelCase__ , UpperCamelCase__ ) ) __lowerCamelCase = actual_strassen(matrix_addition(UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ ) __lowerCamelCase = actual_strassen(matrix_addition(UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ ) __lowerCamelCase = actual_strassen(UpperCamelCase__ , matrix_subtraction(UpperCamelCase__ , UpperCamelCase__ ) ) __lowerCamelCase = actual_strassen(matrix_addition(UpperCamelCase__ , UpperCamelCase__ ) , matrix_addition(UpperCamelCase__ , UpperCamelCase__ ) ) __lowerCamelCase = actual_strassen(matrix_subtraction(UpperCamelCase__ , UpperCamelCase__ ) , matrix_addition(UpperCamelCase__ , UpperCamelCase__ ) ) __lowerCamelCase = actual_strassen(matrix_subtraction(UpperCamelCase__ , UpperCamelCase__ ) , matrix_addition(UpperCamelCase__ , UpperCamelCase__ ) ) __lowerCamelCase = matrix_addition(matrix_subtraction(matrix_addition(UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ ) , UpperCamelCase__ ) __lowerCamelCase = matrix_addition(UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase = matrix_addition(UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase = matrix_subtraction(matrix_subtraction(matrix_addition(UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ ) , UpperCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase = [] for i in range(len(UpperCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(UpperCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def lowerCamelCase_ ( UpperCamelCase__ : list , UpperCamelCase__ : list ) -> list: """simple docstring""" if matrix_dimensions(UpperCamelCase__ )[1] != matrix_dimensions(UpperCamelCase__ )[0]: __lowerCamelCase = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"""Matrix A: {matrixa}\n""" F"""Matrix B: {matrixa}""" ) raise Exception(UpperCamelCase__ ) __lowerCamelCase = matrix_dimensions(UpperCamelCase__ ) __lowerCamelCase = matrix_dimensions(UpperCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase = max(*UpperCamelCase__ , *UpperCamelCase__ ) __lowerCamelCase = int(math.pow(2 , math.ceil(math.loga(UpperCamelCase__ ) ) ) ) __lowerCamelCase = matrixa __lowerCamelCase = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , UpperCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , UpperCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , UpperCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase = actual_strassen(UpperCamelCase__ , UpperCamelCase__ ) # Removing the additional zeros for i in range(0 , UpperCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , UpperCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": __A = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] __A = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
90
"""simple docstring""" import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ = logging.get_logger(__name__) lowercase_ = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } lowercase_ = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } lowercase_ = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCAmelCase ( ): """simple docstring""" __A = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __A = bs[:] __A = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 __A = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase , __UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = set() __A = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __A = char return pairs class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : Tuple = VOCAB_FILES_NAMES A_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : Dict, _lowerCamelCase : Optional[Any], _lowerCamelCase : List[str], _lowerCamelCase : Dict="replace", _lowerCamelCase : Any="<s>", _lowerCamelCase : Optional[int]="</s>", _lowerCamelCase : Dict="</s>", _lowerCamelCase : List[Any]="<s>", _lowerCamelCase : List[str]="<unk>", _lowerCamelCase : str="<pad>", _lowerCamelCase : Any="<mask>", _lowerCamelCase : Any=False, **_lowerCamelCase : Tuple, ): '''simple docstring''' __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else bos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else eos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else sep_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else cls_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else unk_token __A = 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 __A = 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: __A = json.load(_lowerCamelCase ) __A = {v: k for k, v in self.encoder.items()} __A = errors # how to handle errors in decoding __A = bytes_to_unicode() __A = {v: k for k, v in self.byte_encoder.items()} with open(_lowerCamelCase, encoding='''utf-8''' ) as merges_handle: __A = merges_handle.read().split('''\n''' )[1:-1] __A = [tuple(merge.split() ) for merge in bpe_merges] __A = dict(zip(_lowerCamelCase, range(len(_lowerCamelCase ) ) ) ) __A = {} __A = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __A = 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.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return len(self.encoder ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return dict(self.encoder, **self.added_tokens_encoder ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[Any] ): '''simple docstring''' if token in self.cache: return self.cache[token] __A = tuple(_lowerCamelCase ) __A = get_pairs(_lowerCamelCase ) if not pairs: return token while True: __A = min(_lowerCamelCase, key=lambda _lowerCamelCase : self.bpe_ranks.get(_lowerCamelCase, float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __A , __A = bigram __A = [] __A = 0 while i < len(_lowerCamelCase ): try: __A = word.index(_lowerCamelCase, _lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __A = 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 __A = tuple(_lowerCamelCase ) __A = new_word if len(_lowerCamelCase ) == 1: break else: __A = get_pairs(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = word return word def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Dict ): '''simple docstring''' __A = [] for token in re.findall(self.pat, _lowerCamelCase ): __A = ''''''.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 _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : Dict ): '''simple docstring''' return self.encoder.get(_lowerCamelCase, self.encoder.get(self.unk_token ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Any ): '''simple docstring''' return self.decoder.get(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' __A = ''''''.join(_lowerCamelCase ) __A = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''', errors=self.errors ) return text def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : str, _lowerCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __A = 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''' ) __A = 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!''' ) __A = token_index writer.write(''' '''.join(_lowerCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None, _lowerCamelCase : bool = 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 _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Union[str, Any], _lowerCamelCase : List[str]=False, **_lowerCamelCase : List[Any] ): '''simple docstring''' __A = 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()): __A = ''' ''' + text return (text, kwargs) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : "Conversation" ): '''simple docstring''' __A = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = self.encode(_lowerCamelCase ) if len(_lowerCamelCase ) > self.model_max_length: __A = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
266
0
"""simple docstring""" import math import os import sys def _A (__a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = '''''' try: with open(__a , '''rb''' ) as binary_file: SCREAMING_SNAKE_CASE_ : Optional[int] = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE_ : int = f'{dat:08b}' result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def _A (__a , __a , __a , __a ) -> None: """simple docstring""" lexicon.pop(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = last_match_id if math.loga(__a ).is_integer(): for curr_key in lexicon: SCREAMING_SNAKE_CASE_ : Dict = '''0''' + lexicon[curr_key] SCREAMING_SNAKE_CASE_ : str = bin(__a )[2:] def _A (__a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = {'''0''': '''0''', '''1''': '''1'''} SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = '''''', '''''' SCREAMING_SNAKE_CASE_ : Tuple = len(__a ) for i in range(len(__a ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE_ : int = lexicon[curr_string] result += last_match_id add_key_to_lexicon(__a , __a , __a , __a ) index += 1 SCREAMING_SNAKE_CASE_ : int = '''''' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": SCREAMING_SNAKE_CASE_ : Union[str, Any] = lexicon[curr_string] result += last_match_id return result def _A (__a , __a ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = os.path.getsize(__a ) SCREAMING_SNAKE_CASE_ : List[str] = bin(__a )[2:] SCREAMING_SNAKE_CASE_ : List[Any] = len(__a ) return "0" * (length_length - 1) + file_length_binary + compressed def _A (__a , __a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = 8 try: with open(__a , '''wb''' ) as opened_file: SCREAMING_SNAKE_CASE_ : int = [ to_write[i : i + byte_length] for i in range(0 , len(__a ) , __a ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('''10000000''' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(__a , 2 ).to_bytes(1 , byteorder='''big''' ) ) except OSError: print('''File not accessible''' ) sys.exit() def _A (__a , __a ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = read_file_binary(__a ) SCREAMING_SNAKE_CASE_ : List[str] = compress_data(__a ) SCREAMING_SNAKE_CASE_ : Dict = add_file_length(__a , __a ) write_file_binary(__a , __a ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
91
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging lowercase_ = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase ( ): """simple docstring""" __A = '''https://pypi.org/pypi/diffusers/json''' __A = json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys() return sorted(__UpperCamelCase , key=lambda __UpperCamelCase : version.Version(__UpperCamelCase ) ) def lowerCAmelCase ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__UpperCamelCase ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = Path(__UpperCamelCase ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" init_hf_modules() __A = Path(__UpperCamelCase ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import .xxx` __A = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Unique-ify return list(set(__UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = False __A = [module_file] __A = [] # Let's recurse through all relative imports while not no_change: __A = [] for f in files_to_check: new_imports.extend(get_relative_imports(__UpperCamelCase ) ) __A = Path(__UpperCamelCase ).parent __A = [str(module_path / m ) for m in new_imports] __A = [f for f in new_import_files if f not in all_relative_imports] __A = [f'{f}.py' for f in new_import_files] __A = len(__UpperCamelCase ) == 0 all_relative_imports.extend(__UpperCamelCase ) return all_relative_imports def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import xxx` __A = re.findall('''^\s*import\s+(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Only keep the top-level module __A = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all __A = list(set(__UpperCamelCase ) ) __A = [] for imp in imports: try: importlib.import_module(__UpperCamelCase ) except ImportError: missing_packages.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' f'{", ".join(__UpperCamelCase )}. Run `pip install {" ".join(__UpperCamelCase )}`' ) return get_relative_imports(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" __A = module_path.replace(os.path.sep , '''.''' ) __A = importlib.import_module(__UpperCamelCase ) if class_name is None: return find_pipeline_class(__UpperCamelCase ) return getattr(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" from ..pipelines import DiffusionPipeline __A = dict(inspect.getmembers(__UpperCamelCase , inspect.isclass ) ) __A = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __UpperCamelCase ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:' f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in' f' {loaded_module}.' ) __A = cls return pipeline_class def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , ): """simple docstring""" __A = str(__UpperCamelCase ) __A = os.path.join(__UpperCamelCase , __UpperCamelCase ) if os.path.isfile(__UpperCamelCase ): __A = module_file_or_url __A = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: __A = get_diffusers_versions() # cut ".dev0" __A = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: __A = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(f'Defaulting to latest_version: {revision}.' ) elif revision in available_versions: __A = f'v{revision}' elif revision == "main": __A = revision else: raise ValueError( f'`custom_revision`: {revision} does not exist. Please make sure to choose one of' f' {", ".join(available_versions + ["main"] )}.' ) # community pipeline on GitHub __A = COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase , pipeline=__UpperCamelCase ) try: __A = cached_download( __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = '''git''' __A = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise else: try: # Load from URL or cache if already cached __A = hf_hub_download( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise # Check we have all the requirements in our environment __A = check_imports(__UpperCamelCase ) # Now we move the module inside our cached dynamic modules. __A = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__UpperCamelCase ) __A = Path(__UpperCamelCase ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__UpperCamelCase , submodule_path / module_file ) for module_needed in modules_needed: __A = f'{module_needed}.py' shutil.copy(os.path.join(__UpperCamelCase , __UpperCamelCase ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__UpperCamelCase , __UpperCamelCase ): __A = use_auth_token elif use_auth_token is True: __A = HfFolder.get_token() else: __A = None __A = model_info(__UpperCamelCase , revision=__UpperCamelCase , token=__UpperCamelCase ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. __A = submodule_path / commit_hash __A = full_submodule + os.path.sep + commit_hash create_dynamic_module(__UpperCamelCase ) if not (submodule_path / module_file).exists(): shutil.copy(__UpperCamelCase , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __UpperCamelCase , f'{module_needed}.py' , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return os.path.join(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , **__UpperCamelCase , ): """simple docstring""" __A = get_cached_module_file( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return get_class_in_module(__UpperCamelCase , final_module.replace('''.py''' , '''''' ) )
266
0
import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : float = 1E-12 , SCREAMING_SNAKE_CASE_ : int = 1_00 , ): assert np.shape(SCREAMING_SNAKE_CASE_ )[0] == np.shape(SCREAMING_SNAKE_CASE_ )[1] # Ensure proper dimensionality. assert np.shape(SCREAMING_SNAKE_CASE_ )[0] == np.shape(SCREAMING_SNAKE_CASE_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(SCREAMING_SNAKE_CASE_ ) == np.iscomplexobj(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = np.iscomplexobj(SCREAMING_SNAKE_CASE_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(SCREAMING_SNAKE_CASE_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __lowerCAmelCase = False __lowerCAmelCase = 0 __lowerCAmelCase = 0 __lowerCAmelCase = 1E12 while not convergence: # Multiple matrix by the vector. __lowerCAmelCase = np.dot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Normalize the resulting output vector. __lowerCAmelCase = w / np.linalg.norm(SCREAMING_SNAKE_CASE_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __lowerCAmelCase = vector.conj().T if is_complex else vector.T __lowerCAmelCase = np.dot(SCREAMING_SNAKE_CASE_ , np.dot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Check convergence. __lowerCAmelCase = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __lowerCAmelCase = True __lowerCAmelCase = lambda_ if is_complex: __lowerCAmelCase = np.real(lambda_ ) return lambda_, vector def _a ( ): __lowerCAmelCase = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __lowerCAmelCase = np.array([41, 4, 20] ) __lowerCAmelCase = real_input_matrix.astype(np.complexaaa ) __lowerCAmelCase = np.triu(1j * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __lowerCAmelCase = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __lowerCAmelCase = real_input_matrix __lowerCAmelCase = real_vector elif problem_type == "complex": __lowerCAmelCase = complex_input_matrix __lowerCAmelCase = complex_vector # Our implementation. __lowerCAmelCase , __lowerCAmelCase = power_iteration(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __lowerCAmelCase , __lowerCAmelCase = np.linalg.eigh(SCREAMING_SNAKE_CASE_ ) # Last eigenvalue is the maximum one. __lowerCAmelCase = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __lowerCAmelCase = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(SCREAMING_SNAKE_CASE_ ) - np.abs(SCREAMING_SNAKE_CASE_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
92
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[int] ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''], model_result['''ss'''] ): __A = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sgugger/tiny-distilbert-classification''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, only_pretrain_model=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, torchscript=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''', '''Cant do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, fpaa=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) # set architectures equal to `None` __A = None __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''', '''Can\'t do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], fpaa=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, save_to_csv=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], inference_time_csv_file=os.path.join(_lowerCamelCase, '''inf_time.csv''' ), train_memory_csv_file=os.path.join(_lowerCamelCase, '''train_mem.csv''' ), inference_memory_csv_file=os.path.join(_lowerCamelCase, '''inf_mem.csv''' ), train_time_csv_file=os.path.join(_lowerCamelCase, '''train_time.csv''' ), env_info_csv_file=os.path.join(_lowerCamelCase, '''env.csv''' ), multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''env.csv''' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_lowerCamelCase : List[Any] ): self.assertTrue(hasattr(_lowerCamelCase, '''sequential''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''cumulative''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''current''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], log_filename=os.path.join(_lowerCamelCase, '''log.txt''' ), log_print=_lowerCamelCase, trace_memory_line_by_line=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''log.txt''' ) ).exists() )
266
0
'''simple docstring''' import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def snake_case_ ( __SCREAMING_SNAKE_CASE : Any ): """simple docstring""" lowercase_ : Optional[Any] = checkpoints.load_tax_checkpoint(__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = flatten_dict(__SCREAMING_SNAKE_CASE ) return flax_params def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] ): """simple docstring""" lowercase_ : List[Any] = {} lowercase_ : List[Any] = { '''token_embedder''': '''embeddings''', '''encoder_norm''': '''layernorm''', '''kernel''': '''weight''', '''.out''': '''.output''', '''scale''': '''weight''', '''embedders_0.pos_embedding''': '''row_embedder.weight''', '''embedders_1.pos_embedding''': '''column_embedder.weight''', } lowercase_ : str = { '''query''': '''attention.query''', '''key''': '''attention.key''', '''value''': '''attention.value''', '''output.dense''': '''output''', '''encoder_decoder_attention.o''': '''encoder_decoder_attention.attention.o''', '''pre_self_attention_layer_norm''': '''self_attention.layer_norm''', '''pre_cross_attention_layer_norm''': '''encoder_decoder_attention.layer_norm''', '''mlp.''': '''mlp.DenseReluDense.''', '''pre_mlp_layer_norm''': '''mlp.layer_norm''', '''self_attention.o''': '''self_attention.attention.o''', '''decoder.embeddings.embedding''': '''decoder.embed_tokens.weight''', '''decoder.relpos_bias.rel_embedding''': '''decoder.layer.0.self_attention.attention.relative_attention_bias.weight''', '''decoder.decoder_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.logits_dense.weight''': '''decoder.lm_head.weight''', } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key lowercase_ : Dict = '''.'''.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): lowercase_ : List[str] = new_key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): lowercase_ : int = new_key.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number lowercase_ : List[str] = re.sub(R'''layers_(\d+)''' , R'''layer.\1''' , __SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = new_key.replace('''encoder''' , '''encoder.encoder''' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number lowercase_ : Any = re.sub(R'''layers_(\d+)''' , R'''layer.\1''' , __SCREAMING_SNAKE_CASE ) lowercase_ : str = flax_dict[key] lowercase_ : List[str] = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): lowercase_ : Tuple = torch.from_numpy(converted_dict[key].T ) else: lowercase_ : Dict = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def snake_case_ ( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int]=False , __SCREAMING_SNAKE_CASE : Union[str, Any]=False ): """simple docstring""" lowercase_ : Tuple = get_flax_param(__SCREAMING_SNAKE_CASE ) if not use_large: lowercase_ : Any = PixaStructVisionConfig() lowercase_ : Optional[Any] = PixaStructTextConfig() else: lowercase_ : Tuple = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) lowercase_ : int = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) lowercase_ : Any = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=__SCREAMING_SNAKE_CASE ) lowercase_ : Any = PixaStructForConditionalGeneration(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = rename_and_convert_flax_params(__SCREAMING_SNAKE_CASE ) model.load_state_dict(__SCREAMING_SNAKE_CASE ) lowercase_ : str = AutoTokenizer.from_pretrained('''ybelkada/test-pix2struct-tokenizer''' ) lowercase_ : List[str] = PixaStructImageProcessor() lowercase_ : Tuple = PixaStructProcessor(image_processor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) if use_large: lowercase_ : str = 4096 lowercase_ : Dict = True # mkdir if needed os.makedirs(__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) processor.save_pretrained(__SCREAMING_SNAKE_CASE ) print('''Model saved in {}'''.format(__SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": _lowercase : Tuple = argparse.ArgumentParser() parser.add_argument("--t5x_checkpoint_path", default=None, type=str, help="Path to the original T5x checkpoint.") parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--use_large", action="store_true", help="Use large model.") parser.add_argument("--is_vqa", action="store_true", help="Use large model.") _lowercase : Tuple = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
93
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast 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 lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = PegasusTokenizer A_ : int = PegasusTokenizerFast A_ : Optional[Any] = True A_ : Union[str, Any] = True def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def _SCREAMING_SNAKE_CASE ( self : int, **_lowerCamelCase : List[Any] ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = '''</s>''' __A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ), _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ), _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], '''<pad>''' ) self.assertEqual(vocab_keys[1], '''</s>''' ) self.assertEqual(vocab_keys[-1], '''v''' ) self.assertEqual(len(_lowerCamelCase ), 11_03 ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 11_03 ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __A = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' __A = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 __A = '''To ensure a smooth flow of bank resolutions.''' __A = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 1_50, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # fmt: off __A = {'''input_ids''': [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 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], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 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]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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='''google/bigbird-pegasus-large-arxiv''', revision='''ba85d0851d708441f91440d509690f1ab6353415''', ) @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = PegasusTokenizer A_ : Union[str, Any] = PegasusTokenizerFast A_ : Any = True A_ : str = True def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase, offset=0, mask_token_sent=_lowerCamelCase, mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], **_lowerCamelCase : Dict ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : List[str] ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 10_00, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) __A = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase, [1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1], )
266
0
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ): a :int = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): a :str = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): a :Tuple = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): a :Union[str, Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): a :Dict = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): a :Optional[Any] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] a :Optional[int] = '''fp16''' self.assertTrue(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): a :Any = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] a :List[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): # pass variant but use the non-variant filenames a :List[str] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] a :Optional[int] = '''fp16''' self.assertTrue(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): a :Optional[int] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] a :List[str] = '''fp16''' self.assertFalse(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): a :List[Any] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] a :Any = '''fp16''' self.assertTrue(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): # pass variant but use the non-variant filenames a :Optional[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] a :Union[str, Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( self ): a :Dict = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] a :Optional[Any] = '''fp16''' self.assertFalse(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) )
94
"""simple docstring""" import re def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return [char.split() for char in re.split(r'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" try: __A = split_input(__UpperCamelCase ) if upper: __A = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __A = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return to_simple_case(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" try: __A = to_simple_case(__UpperCamelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''_''' ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
266
0
from importlib import import_module from .logging import get_logger UpperCAmelCase : int = get_logger(__name__) class __lowerCAmelCase : def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> Tuple: '''simple docstring''' a__ : int =attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("__" ): setattr(self , lowerCAmelCase__ , getattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) a__ : Any =module._original_module if isinstance(lowerCAmelCase__ , _PatchedModuleObj ) else module class __lowerCAmelCase : _lowercase : List[Any] = [] def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None ) -> List[str]: '''simple docstring''' a__ : Optional[int] =obj a__ : Tuple =target a__ : Tuple =new a__ : str =target.split("." )[0] a__ : str ={} a__ : int =attrs or [] def __enter__( self ) -> str: '''simple docstring''' *a__ , a__ : List[Any] =self.target.split("." ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(lowerCAmelCase__ ) ): try: a__ : Optional[int] =import_module(".".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): a__ : Optional[int] =getattr(self.obj , lowerCAmelCase__ ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(lowerCAmelCase__ , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): a__ : Dict =obj_attr # patch at top level setattr(self.obj , lowerCAmelCase__ , _PatchedModuleObj(lowerCAmelCase__ , attrs=self.attrs ) ) a__ : Union[str, Any] =getattr(self.obj , lowerCAmelCase__ ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(lowerCAmelCase__ , lowerCAmelCase__ , _PatchedModuleObj(getattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) , attrs=self.attrs ) ) a__ : int =getattr(lowerCAmelCase__ , lowerCAmelCase__ ) # finally set the target attribute setattr(lowerCAmelCase__ , lowerCAmelCase__ , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: a__ : Any =getattr(import_module(".".join(lowerCAmelCase__ ) ) , lowerCAmelCase__ ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , lowerCAmelCase__ ) is attr_value: a__ : Optional[Any] =getattr(self.obj , lowerCAmelCase__ ) setattr(self.obj , lowerCAmelCase__ , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" a__ : Dict =globals()["__builtins__"][target_attr] setattr(self.obj , lowerCAmelCase__ , self.new ) else: raise RuntimeError(F'''Tried to patch attribute {target_attr} instead of a submodule.''' ) def __exit__( self , *lowerCAmelCase__ ) -> str: '''simple docstring''' for attr in list(self.original ): setattr(self.obj , lowerCAmelCase__ , self.original.pop(lowerCAmelCase__ ) ) def _lowercase ( self ) -> Optional[Any]: '''simple docstring''' self.__enter__() self._active_patches.append(self ) def _lowercase ( self ) -> str: '''simple docstring''' try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
95
"""simple docstring""" from __future__ import annotations class snake_case : '''simple docstring''' def __init__( self : int, _lowerCamelCase : List[Any]=None ): '''simple docstring''' __A = data __A = None def __repr__( self : Union[str, Any] ): '''simple docstring''' __A = [] __A = self while temp: string_rep.append(f'{temp.data}' ) __A = temp.next return "->".join(_lowerCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not elements_list: raise Exception('''The Elements List is empty''' ) __A = __A = Node(elements_list[0] ) for i in range(1 , len(__UpperCamelCase ) ): __A = Node(elements_list[i] ) __A = current.next return head def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if head_node is not None and isinstance(__UpperCamelCase , __UpperCamelCase ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase ( ): """simple docstring""" from doctest import testmod testmod() __A = make_linked_list([1_4, 5_2, 1_4, 1_2, 4_3] ) print('''Linked List:''' ) print(__UpperCamelCase ) print('''Elements in Reverse:''' ) print_reverse(__UpperCamelCase ) if __name__ == "__main__": main()
266
0
"""simple docstring""" def _snake_case ( lowercase__ ): stooge(lowercase__ , 0 , len(lowercase__ ) - 1 ) return arr def _snake_case ( lowercase__ , lowercase__ , lowercase__ ): if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: _lowerCamelCase, _lowerCamelCase : Optional[Any] = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: _lowerCamelCase : Union[str, Any] = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(lowercase__ , lowercase__ , (h - t) ) # Recursively sort last 2/3 elements stooge(lowercase__ , i + t , (lowercase__) ) # Recursively sort first 2/3 elements stooge(lowercase__ , lowercase__ , (h - t) ) if __name__ == "__main__": lowercase__ = input("""Enter numbers separated by a comma:\n""").strip() lowercase__ = [int(item) for item in user_input.split(""",""")] print(stooge_sort(unsorted))
96
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : int = ["input_features", "attention_mask"] def __init__( self : Optional[Any], _lowerCamelCase : Union[str, Any]=80, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Any=80, _lowerCamelCase : List[str]=0.0, _lowerCamelCase : int=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Optional[int]=True, **_lowerCamelCase : List[str], ): '''simple docstring''' super().__init__(feature_size=_lowerCamelCase, sampling_rate=_lowerCamelCase, padding_value=_lowerCamelCase, **_lowerCamelCase ) __A = num_mel_bins __A = do_ceptral_normalize __A = normalize_means __A = normalize_vars __A = True def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : np.ndarray, ): '''simple docstring''' __A = waveform * (2**15) # Kaldi compliance: 16-bit signed integers __A = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ) __A = ta_kaldi.fbank(_lowerCamelCase, num_mel_bins=self.num_mel_bins, sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray, _lowerCamelCase : int, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : float = 0.0, ): '''simple docstring''' # make sure we normalize float32 arrays if normalize_means: __A = x[:input_length].mean(axis=0 ) __A = np.subtract(_lowerCamelCase, _lowerCamelCase ) if normalize_vars: __A = x[:input_length].std(axis=0 ) __A = np.divide(_lowerCamelCase, _lowerCamelCase ) if input_length < x.shape[0]: __A = padding_value # make sure array is in float32 __A = x.astype(np.floataa ) return x def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[np.ndarray], _lowerCamelCase : Optional[np.ndarray] = None ): '''simple docstring''' __A = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_lowerCamelCase, _lowerCamelCase, self.normalize_means, self.normalize_vars, self.padding_value ) for x, n in zip(_lowerCamelCase, _lowerCamelCase ) ] def __call__( self : Optional[Any], _lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], _lowerCamelCase : Union[bool, str, PaddingStrategy] = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : bool = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[Union[str, TensorType]] = None, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[bool] = None, **_lowerCamelCase : Optional[Any], ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __A = isinstance(_lowerCamelCase, np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __A = is_batched_numpy or ( isinstance(_lowerCamelCase, (list, tuple) ) and (isinstance(raw_speech[0], (np.ndarray, tuple, list) )) ) if is_batched: __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_lowerCamelCase, np.ndarray ): __A = np.asarray(_lowerCamelCase, dtype=np.floataa ) elif isinstance(_lowerCamelCase, np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __A = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __A = [raw_speech] # extract fbank features __A = [self._extract_fbank_features(_lowerCamelCase ) for waveform in raw_speech] # convert into correct format for padding __A = BatchFeature({'''input_features''': features} ) __A = self.pad( _lowerCamelCase, padding=_lowerCamelCase, max_length=_lowerCamelCase, truncation=_lowerCamelCase, pad_to_multiple_of=_lowerCamelCase, return_attention_mask=_lowerCamelCase, **_lowerCamelCase, ) # make sure list is in array format __A = padded_inputs.get('''input_features''' ) if isinstance(input_features[0], _lowerCamelCase ): __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for feature in input_features] __A = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __A = [np.asarray(_lowerCamelCase, dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: __A = ( np.array(_lowerCamelCase, dtype=np.intaa ) if self._get_padding_strategies(_lowerCamelCase, max_length=_lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) __A = self.normalize( padded_inputs['''input_features'''], attention_mask=_lowerCamelCase ) if return_tensors is not None: __A = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs
266
0
'''simple docstring''' import json import os import shutil import warnings from argparse import ArgumentParser, Namespace from pathlib import Path from typing import List from ..utils import logging from . import BaseTransformersCLICommand try: from cookiecutter.main import cookiecutter __snake_case = True except ImportError: __snake_case = False __snake_case = logging.get_logger(__name__) # pylint: disable=invalid-name def a ( __a ) -> Union[str, Any]: '''simple docstring''' return AddNewModelCommand(args.testing , args.testing_file , path=args.path ) class lowercase ( A__ ): """simple docstring""" @staticmethod def lowerCAmelCase__ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Tuple = parser.add_parser('''add-new-model''' ) add_new_model_parser.add_argument('''--testing''' , action='''store_true''' , help='''If in testing mode.''' ) add_new_model_parser.add_argument('''--testing_file''' , type=UpperCamelCase_ , help='''Configuration file on which to run.''' ) add_new_model_parser.add_argument( '''--path''' , type=UpperCamelCase_ , help='''Path to cookiecutter. Should only be used for testing purposes.''' ) add_new_model_parser.set_defaults(func=UpperCamelCase_ ) def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None , *UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :int = testing UpperCamelCase__ :Optional[int] = testing_file UpperCamelCase__ :Dict = path def lowerCAmelCase__ ( self ): '''simple docstring''' warnings.warn( '''The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. ''' '''It is not actively maintained anymore, so might give a result that won\'t pass all tests and quality ''' '''checks, you should use `transformers-cli add-new-model-like` instead.''' ) if not _has_cookiecutter: raise ImportError( '''Model creation dependencies are required to use the `add_new_model` command. Install them by running ''' '''the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n''' ) # Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory UpperCamelCase__ :Optional[int] = [directory for directory in os.listdir() if '''cookiecutter-template-''' == directory[:22]] if len(UpperCamelCase_ ) > 0: raise ValueError( '''Several directories starting with `cookiecutter-template-` in current working directory. ''' '''Please clean your directory by removing all folders starting with `cookiecutter-template-` or ''' '''change your working directory.''' ) UpperCamelCase__ :Optional[int] = ( Path(UpperCamelCase_ ).parent.parent.parent.parent if self._path is None else Path(self._path ).parent.parent ) UpperCamelCase__ :int = path_to_transformer_root / '''templates''' / '''adding_a_new_model''' # Execute cookiecutter if not self._testing: cookiecutter(str(UpperCamelCase_ ) ) else: with open(self._testing_file , '''r''' ) as configuration_file: UpperCamelCase__ :Union[str, Any] = json.load(UpperCamelCase_ ) cookiecutter( str(path_to_cookiecutter if self._path is None else self._path ) , no_input=UpperCamelCase_ , extra_context=UpperCamelCase_ , ) UpperCamelCase__ :List[Any] = [directory for directory in os.listdir() if '''cookiecutter-template-''' in directory[:22]][0] # Retrieve configuration with open(directory + '''/configuration.json''' , '''r''' ) as configuration_file: UpperCamelCase__ :Any = json.load(UpperCamelCase_ ) UpperCamelCase__ :Union[str, Any] = configuration['''lowercase_modelname'''] UpperCamelCase__ :Union[str, Any] = configuration['''generate_tensorflow_pytorch_and_flax'''] os.remove(F'''{directory}/configuration.json''' ) UpperCamelCase__ :str = '''PyTorch''' in generate_tensorflow_pytorch_and_flax UpperCamelCase__ :str = '''TensorFlow''' in generate_tensorflow_pytorch_and_flax UpperCamelCase__ :List[str] = '''Flax''' in generate_tensorflow_pytorch_and_flax UpperCamelCase__ :List[Any] = F'''{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}''' os.makedirs(UpperCamelCase_ , exist_ok=UpperCamelCase_ ) os.makedirs(F'''{path_to_transformer_root}/tests/models/{lowercase_model_name}''' , exist_ok=UpperCamelCase_ ) # Tests require submodules as they have parent imports with open(F'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py''' , '''w''' ): pass shutil.move( F'''{directory}/__init__.py''' , F'''{model_dir}/__init__.py''' , ) shutil.move( F'''{directory}/configuration_{lowercase_model_name}.py''' , F'''{model_dir}/configuration_{lowercase_model_name}.py''' , ) def remove_copy_lines(UpperCamelCase_ ): with open(UpperCamelCase_ , '''r''' ) as f: UpperCamelCase__ :List[str] = f.readlines() with open(UpperCamelCase_ , '''w''' ) as f: for line in lines: if "# Copied from transformers." not in line: f.write(UpperCamelCase_ ) if output_pytorch: if not self._testing: remove_copy_lines(F'''{directory}/modeling_{lowercase_model_name}.py''' ) shutil.move( F'''{directory}/modeling_{lowercase_model_name}.py''' , F'''{model_dir}/modeling_{lowercase_model_name}.py''' , ) shutil.move( F'''{directory}/test_modeling_{lowercase_model_name}.py''' , F'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py''' , ) else: os.remove(F'''{directory}/modeling_{lowercase_model_name}.py''' ) os.remove(F'''{directory}/test_modeling_{lowercase_model_name}.py''' ) if output_tensorflow: if not self._testing: remove_copy_lines(F'''{directory}/modeling_tf_{lowercase_model_name}.py''' ) shutil.move( F'''{directory}/modeling_tf_{lowercase_model_name}.py''' , F'''{model_dir}/modeling_tf_{lowercase_model_name}.py''' , ) shutil.move( F'''{directory}/test_modeling_tf_{lowercase_model_name}.py''' , F'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py''' , ) else: os.remove(F'''{directory}/modeling_tf_{lowercase_model_name}.py''' ) os.remove(F'''{directory}/test_modeling_tf_{lowercase_model_name}.py''' ) if output_flax: if not self._testing: remove_copy_lines(F'''{directory}/modeling_flax_{lowercase_model_name}.py''' ) shutil.move( F'''{directory}/modeling_flax_{lowercase_model_name}.py''' , F'''{model_dir}/modeling_flax_{lowercase_model_name}.py''' , ) shutil.move( F'''{directory}/test_modeling_flax_{lowercase_model_name}.py''' , F'''{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py''' , ) else: os.remove(F'''{directory}/modeling_flax_{lowercase_model_name}.py''' ) os.remove(F'''{directory}/test_modeling_flax_{lowercase_model_name}.py''' ) shutil.move( F'''{directory}/{lowercase_model_name}.md''' , F'''{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md''' , ) shutil.move( F'''{directory}/tokenization_{lowercase_model_name}.py''' , F'''{model_dir}/tokenization_{lowercase_model_name}.py''' , ) shutil.move( F'''{directory}/tokenization_fast_{lowercase_model_name}.py''' , F'''{model_dir}/tokenization_{lowercase_model_name}_fast.py''' , ) from os import fdopen, remove from shutil import copymode, move from tempfile import mkstemp def replace(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): # Create temp file UpperCamelCase__ , UpperCamelCase__ :List[str] = mkstemp() UpperCamelCase__ :Optional[int] = False with fdopen(UpperCamelCase_ , '''w''' ) as new_file: with open(UpperCamelCase_ ) as old_file: for line in old_file: new_file.write(UpperCamelCase_ ) if line_to_copy_below in line: UpperCamelCase__ :int = True for line_to_copy in lines_to_copy: new_file.write(UpperCamelCase_ ) if not line_found: raise ValueError(F'''Line {line_to_copy_below} was not found in file.''' ) # Copy the file permissions from the old file to the new file copymode(UpperCamelCase_ , UpperCamelCase_ ) # Remove original file remove(UpperCamelCase_ ) # Move new file move(UpperCamelCase_ , UpperCamelCase_ ) def skip_units(UpperCamelCase_ ): return ( ("generating PyTorch" in line and not output_pytorch) or ("generating TensorFlow" in line and not output_tensorflow) or ("generating Flax" in line and not output_flax) ) def replace_in_files(UpperCamelCase_ ): with open(UpperCamelCase_ ) as datafile: UpperCamelCase__ :Union[str, Any] = [] UpperCamelCase__ :int = False UpperCamelCase__ :Dict = False for line in datafile: if "# To replace in: " in line and "##" not in line: UpperCamelCase__ :List[str] = line.split('''"''' )[1] UpperCamelCase__ :int = skip_units(UpperCamelCase_ ) elif "# Below: " in line and "##" not in line: UpperCamelCase__ :str = line.split('''"''' )[1] UpperCamelCase__ :Tuple = skip_units(UpperCamelCase_ ) elif "# End." in line and "##" not in line: if not skip_file and not skip_snippet: replace(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase__ :Union[str, Any] = [] elif "# Replace with" in line and "##" not in line: UpperCamelCase__ :str = [] elif "##" not in line: lines_to_copy.append(UpperCamelCase_ ) remove(UpperCamelCase_ ) replace_in_files(F'''{directory}/to_replace_{lowercase_model_name}.py''' ) os.rmdir(UpperCamelCase_ )
97
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : Optional[Any], _lowerCamelCase : Union[str, Any]=13, _lowerCamelCase : Any=3, _lowerCamelCase : Optional[int]=2_24, _lowerCamelCase : str=30, _lowerCamelCase : Dict=4_00, _lowerCamelCase : Union[str, Any]=True, _lowerCamelCase : Any=None, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Any=[0.5, 0.5, 0.5], _lowerCamelCase : List[str]=[0.5, 0.5, 0.5], ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_normalize __A = image_mean __A = image_std def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = ViTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = EfficientFormerImageProcessorTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), )
266
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase__ : Tuple = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : List[Any] = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : int = [ '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 lowerCAmelCase__ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
98
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' def __init__( self : Optional[int], *_lowerCamelCase : Union[str, Any], **_lowerCamelCase : Dict ): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''', _lowerCamelCase, ) super().__init__(*_lowerCamelCase, **_lowerCamelCase )
266
0
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class A__ : """simple docstring""" def __init__( self , lowercase , lowercase=2 , lowercase=32 , lowercase=16 , lowercase=3 , lowercase=True , lowercase=True , lowercase=32 , lowercase=4 , lowercase=[0, 1, 2, 3] , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=0.02 , lowercase=3 , lowercase=[1, 384, 24, 24] , lowercase=True , lowercase=None , ) -> Dict: '''simple docstring''' a__ : List[str] = parent a__ : Optional[Any] = batch_size a__ : Optional[int] = image_size a__ : List[Any] = patch_size a__ : List[Any] = num_channels a__ : Any = is_training a__ : Dict = use_labels a__ : Dict = hidden_size a__ : Tuple = num_hidden_layers a__ : int = backbone_out_indices a__ : int = num_attention_heads a__ : Any = intermediate_size a__ : Optional[Any] = hidden_act a__ : Tuple = hidden_dropout_prob a__ : Any = attention_probs_dropout_prob a__ : int = initializer_range a__ : Optional[int] = num_labels a__ : int = backbone_featmap_shape a__ : Dict = scope a__ : Dict = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) a__ : List[str] = (image_size // patch_size) ** 2 a__ : str = num_patches + 1 def __lowercase ( self) -> int: '''simple docstring''' a__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) a__ : int = None if self.use_labels: a__ : Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels) a__ : str = self.get_config() return config, pixel_values, labels def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : List[str] = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, 'hidden_sizes': [96, 192, 384, 768], 'num_groups': 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , 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=lowercase , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=lowercase , backbone_featmap_shape=self.backbone_featmap_shape , ) def __lowercase ( self , lowercase , lowercase , lowercase) -> Union[str, Any]: '''simple docstring''' a__ : Union[str, Any] = DPTModel(config=lowercase) model.to(lowercase) model.eval() a__ : str = model(lowercase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def __lowercase ( self , lowercase , lowercase , lowercase) -> str: '''simple docstring''' a__ : str = self.num_labels a__ : Dict = DPTForDepthEstimation(lowercase) model.to(lowercase) model.eval() a__ : Dict = model(lowercase) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size)) def __lowercase ( self , lowercase , lowercase , lowercase) -> List[str]: '''simple docstring''' a__ : List[Any] = self.num_labels a__ : str = DPTForSemanticSegmentation(lowercase) model.to(lowercase) model.eval() a__ : int = model(lowercase , labels=lowercase) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size)) def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : Any = self.prepare_config_and_inputs() a__ , a__ , a__ : Any = config_and_inputs a__ : Tuple = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class A__ ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __A : Tuple = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () __A : Tuple = ( { '''depth-estimation''': DPTForDepthEstimation, '''feature-extraction''': DPTModel, '''image-segmentation''': DPTForSemanticSegmentation, } if is_torch_available() else {} ) __A : str = False __A : Optional[int] = False __A : int = False def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : Optional[Any] = DPTModelTester(self) a__ : Optional[int] = ConfigTester(self , config_class=lowercase , has_text_modality=lowercase , hidden_size=37) def __lowercase ( self) -> Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='DPT does not use inputs_embeds') def __lowercase ( self) -> List[str]: '''simple docstring''' pass def __lowercase ( self) -> str: '''simple docstring''' a__ , a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Tuple = model_class(lowercase) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) a__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase , nn.Linear)) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ , a__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Optional[Any] = model_class(lowercase) a__ : Any = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Tuple = [*signature.parameters.keys()] a__ : Optional[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , lowercase) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase) def __lowercase ( self) -> Any: '''simple docstring''' a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*lowercase) def __lowercase ( self) -> str: '''simple docstring''' a__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*lowercase) def __lowercase ( self) -> List[Any]: '''simple docstring''' for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue a__ , a__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() a__ : Tuple = True if model_class in get_values(lowercase): continue a__ : Optional[int] = model_class(lowercase) model.to(lowercase) model.train() a__ : List[str] = self._prepare_for_class(lowercase , lowercase , return_labels=lowercase) a__ : Optional[Any] = model(**lowercase).loss loss.backward() def __lowercase ( self) -> str: '''simple docstring''' for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue a__ , a__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() a__ : Optional[Any] = False a__ : Any = True if model_class in get_values(lowercase) or not model_class.supports_gradient_checkpointing: continue a__ : Tuple = model_class(lowercase) model.to(lowercase) model.gradient_checkpointing_enable() model.train() a__ : List[Any] = self._prepare_for_class(lowercase , lowercase , return_labels=lowercase) a__ : Any = model(**lowercase).loss loss.backward() def __lowercase ( self) -> Dict: '''simple docstring''' a__ , a__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() a__ : int = _config_zero_init(lowercase) for model_class in self.all_model_classes: a__ : List[str] = model_class(config=lowercase) # Skip the check for the backbone a__ : Dict = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": a__ : Optional[int] = [F'{name}.{key}' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'Parameter {name} of model {model_class} seems not properly initialized' , ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.') def __lowercase ( self) -> Dict: '''simple docstring''' pass @slow def __lowercase ( self) -> List[Any]: '''simple docstring''' for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: a__ : Dict = DPTModel.from_pretrained(lowercase) self.assertIsNotNone(lowercase) def __lowercase ( self) -> List[str]: '''simple docstring''' a__ , a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() a__ : Optional[int] = 'add' with self.assertRaises(lowercase): a__ : str = DPTForDepthEstimation(lowercase) def A_ ( ) -> Any: a__ : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision @slow class A__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : str = DPTImageProcessor.from_pretrained('Intel/dpt-hybrid-midas') a__ : List[Any] = DPTForDepthEstimation.from_pretrained('Intel/dpt-hybrid-midas').to(lowercase) a__ : Dict = prepare_img() a__ : Any = image_processor(images=lowercase , return_tensors='pt').to(lowercase) # forward pass with torch.no_grad(): a__ : str = model(**lowercase) a__ : List[Any] = outputs.predicted_depth # verify the predicted depth a__ : Optional[int] = torch.Size((1, 384, 384)) self.assertEqual(predicted_depth.shape , lowercase) a__ : Optional[Any] = torch.tensor( [[[5.64_37, 5.61_46, 5.65_11], [5.43_71, 5.56_49, 5.59_58], [5.52_15, 5.51_84, 5.52_93]]]).to(lowercase) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , lowercase , atol=1e-4))
99
"""simple docstring""" 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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : List[Any]=7, _lowerCamelCase : int=3, _lowerCamelCase : Optional[Any]=18, _lowerCamelCase : Any=30, _lowerCamelCase : str=4_00, _lowerCamelCase : int=True, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str=True, ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = apply_ocr def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[int] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = LayoutLMvaImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = 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 : Union[str, Any] ): '''simple docstring''' __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'''height''': 18, '''width''': 18} ) __A = 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 : Optional[Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = 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 __A = 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 : Any ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = 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 __A = 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 __A = 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 __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = 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 __A = 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 __A = 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 : List[str] ): '''simple docstring''' # with apply_OCR = True __A = LayoutLMvaImageProcessor() from datasets import load_dataset __A = load_dataset('''hf-internal-testing/fixtures_docvqa''', split='''test''' ) __A = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ), len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __A = [['''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 __A = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words, _lowerCamelCase ) self.assertListEqual(encoding.boxes, _lowerCamelCase ) # with apply_OCR = False __A = LayoutLMvaImageProcessor(apply_ocr=_lowerCamelCase ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) )
266
0
"""simple docstring""" import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=1024 , UpperCamelCase_=1024 , UpperCamelCase_=False , **UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = SeqaSeqDataset(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , type_path="""train""" , **UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = tok.pad_token_id def get_lens(UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = tqdm( DataLoader(UpperCamelCase_ , batch_size=512 , num_workers=8 , shuffle=UpperCamelCase_ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) __SCREAMING_SNAKE_CASE = [] for batch in dl: __SCREAMING_SNAKE_CASE = batch["""input_ids"""].ne(UpperCamelCase_ ).sum(1 ).tolist() __SCREAMING_SNAKE_CASE = batch["""labels"""].ne(UpperCamelCase_ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(UpperCamelCase_ , UpperCamelCase_ ): max_lens.append(max(UpperCamelCase_ , UpperCamelCase_ ) ) else: max_lens.extend(UpperCamelCase_ ) return max_lens __SCREAMING_SNAKE_CASE = get_lens(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = SeqaSeqDataset(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , type_path="""val""" , **UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = get_lens(UpperCamelCase_ ) pickle_save(UpperCamelCase_ , train_ds.len_file ) pickle_save(UpperCamelCase_ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
100
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): '''simple docstring''' A_ : List[str] = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = False ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = True ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def lowerCAmelCase ( ): """simple docstring""" try: hide_cursor() yield finally: show_cursor()
266
0
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def UpperCamelCase ( ): '''simple docstring''' lowercase = [randint(-1000 , 1000 ) for i in range(10 )] lowercase = randint(-5000 , 5000 ) return (arr, r) lowercase__ :Dict = make_dataset() def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' for triplet in permutations(lowerCAmelCase__ , 3 ): if sum(lowerCAmelCase__ ) == target: return tuple(sorted(lowerCAmelCase__ ) ) return (0, 0, 0) def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' arr.sort() lowercase = len(lowerCAmelCase__ ) for i in range(n - 1 ): lowercase , lowercase = 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 UpperCamelCase ( ): '''simple docstring''' lowercase = ''' from __main__ import dataset, triplet_sum1, triplet_sum2 ''' lowercase = ''' triplet_sum1(*dataset) ''' lowercase = ''' triplet_sum2(*dataset) ''' lowercase = repeat(setup=lowerCAmelCase__ , stmt=lowerCAmelCase__ , repeat=5 , number=1_0000 ) lowercase = repeat(setup=lowerCAmelCase__ , stmt=lowerCAmelCase__ , repeat=5 , number=1_0000 ) return (min(lowerCAmelCase__ ), min(lowerCAmelCase__ )) if __name__ == "__main__": from doctest import testmod testmod() lowercase__ :str = solution_times() print(F'The time for naive implementation is {times[0]}.') print(F'The time for optimized implementation is {times[1]}.')
101
"""simple docstring""" import argparse import struct import unittest class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : bytes ): '''simple docstring''' __A = data # Initialize hash values __A = [ 0X6a_09e_667, 0Xbb_67a_e85, 0X3c_6ef_372, 0Xa5_4ff_53a, 0X51_0e5_27f, 0X9b_056_88c, 0X1f_83d_9ab, 0X5b_e0c_d19, ] # Initialize round constants __A = [ 0X42_8a2_f98, 0X71_374_491, 0Xb5_c0f_bcf, 0Xe9_b5d_ba5, 0X39_56c_25b, 0X59_f11_1f1, 0X92_3f8_2a4, 0Xab_1c5_ed5, 0Xd8_07a_a98, 0X12_835_b01, 0X24_318_5be, 0X55_0c7_dc3, 0X72_be5_d74, 0X80_deb_1fe, 0X9b_dc0_6a7, 0Xc1_9bf_174, 0Xe4_9b6_9c1, 0Xef_be4_786, 0X0f_c19_dc6, 0X24_0ca_1cc, 0X2d_e92_c6f, 0X4a_748_4aa, 0X5c_b0a_9dc, 0X76_f98_8da, 0X98_3e5_152, 0Xa8_31c_66d, 0Xb0_032_7c8, 0Xbf_597_fc7, 0Xc6_e00_bf3, 0Xd5_a79_147, 0X06_ca6_351, 0X14_292_967, 0X27_b70_a85, 0X2e_1b2_138, 0X4d_2c6_dfc, 0X53_380_d13, 0X65_0a7_354, 0X76_6a0_abb, 0X81_c2c_92e, 0X92_722_c85, 0Xa2_bfe_8a1, 0Xa8_1a6_64b, 0Xc2_4b8_b70, 0Xc7_6c5_1a3, 0Xd1_92e_819, 0Xd6_990_624, 0Xf4_0e3_585, 0X10_6aa_070, 0X19_a4c_116, 0X1e_376_c08, 0X27_487_74c, 0X34_b0b_cb5, 0X39_1c0_cb3, 0X4e_d8a_a4a, 0X5b_9cc_a4f, 0X68_2e6_ff3, 0X74_8f8_2ee, 0X78_a56_36f, 0X84_c87_814, 0X8c_c70_208, 0X90_bef_ffa, 0Xa4_506_ceb, 0Xbe_f9a_3f7, 0Xc6_717_8f2, ] __A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : bytes ): '''simple docstring''' __A = b'''\x80''' + (b'''\x00''' * (63 - (len(_lowerCamelCase ) + 8) % 64)) __A = struct.pack('''>Q''', (len(_lowerCamelCase ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' # Convert into blocks of 64 bytes __A = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data ), 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __A = list(struct.unpack('''>16L''', _lowerCamelCase ) ) # add 48 0-ed integers words += [0] * 48 __A , __A , __A , __A , __A , __A , __A , __A = self.hashes for index in range(0, 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __A = ( self.ror(words[index - 15], 7 ) ^ self.ror(words[index - 15], 18 ) ^ (words[index - 15] >> 3) ) __A = ( self.ror(words[index - 2], 17 ) ^ self.ror(words[index - 2], 19 ) ^ (words[index - 2] >> 10) ) __A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X100_000_000 # Compression __A = self.ror(_lowerCamelCase, 6 ) ^ self.ror(_lowerCamelCase, 11 ) ^ self.ror(_lowerCamelCase, 25 ) __A = (e & f) ^ ((~e & 0Xff_fff_fff) & g) __A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X100_000_000 __A = self.ror(_lowerCamelCase, 2 ) ^ self.ror(_lowerCamelCase, 13 ) ^ self.ror(_lowerCamelCase, 22 ) __A = (a & b) ^ (a & c) ^ (b & c) __A = (sa + maj) % 0X100_000_000 __A , __A , __A , __A , __A , __A , __A , __A = ( g, f, e, ((d + tempa) % 0X100_000_000), c, b, a, ((tempa + tempa) % 0X100_000_000), ) __A = [a, b, c, d, e, f, g, h] # Modify final values __A = [ ((element + mutated_hash_values[index]) % 0X100_000_000) for index, element in enumerate(self.hashes ) ] __A = ''''''.join([hex(_lowerCamelCase )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' return 0Xff_fff_fff & (value << (32 - rotations)) | (value >> rotations) class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' import hashlib __A = bytes('''Test String''', '''utf-8''' ) self.assertEqual(SHAaaa(_lowerCamelCase ).hash, hashlib.shaaaa(_lowerCamelCase ).hexdigest() ) def lowerCAmelCase ( ): """simple docstring""" import doctest doctest.testmod() __A = argparse.ArgumentParser() parser.add_argument( '''-s''' , '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument( '''-f''' , '''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) __A = parser.parse_args() __A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: __A = f.read() else: __A = bytes(__UpperCamelCase , '''utf-8''' ) print(SHAaaa(__UpperCamelCase ).hash ) if __name__ == "__main__": main()
266
0
"""simple docstring""" from __future__ import annotations class _UpperCAmelCase : '''simple docstring''' def __init__(self , a_ ): '''simple docstring''' __snake_case : List[Any] = TypeError( '''Matrices must be formed from a list of zero or more lists containing at ''' '''least one and the same number of values, each of which must be of type ''' '''int or float.''' ) if len(a_ ) != 0: __snake_case : List[Any] = len(rows[0] ) if cols == 0: raise error for row in rows: if len(a_ ) != cols: raise error for value in row: if not isinstance(a_ , (int, float) ): raise error __snake_case : List[Any] = rows else: __snake_case : int = [] def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return [[row[i] for row in self.rows] for i in range(len(self.rows[0] ) )] @property def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return len(self.rows ) @property def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return len(self.rows[0] ) @property def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return (self.num_rows, self.num_columns) @property def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return self.order[0] == self.order[1] def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Any = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows )] for row_num in range(self.num_rows ) ] return Matrix(a_ ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0] ) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns ) ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return bool(self.determinant() ) def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' __snake_case : Optional[int] = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns ) if other_column != column ] for other_row in range(self.num_rows ) if other_row != row ] return Matrix(a_ ).determinant() def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' if (row + column) % 2 == 0: return self.get_minor(a_ , a_ ) return -1 * self.get_minor(a_ , a_ ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return Matrix( [ [self.get_minor(a_ , a_ ) for column in range(self.num_columns )] for row in range(self.num_rows ) ] ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns ) ] for row in range(self.minors().num_rows ) ] ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Dict = [ [self.cofactors().rows[column][row] for column in range(self.num_columns )] for row in range(self.num_rows ) ] return Matrix(a_ ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : str = self.determinant() if not determinant: raise TypeError('''Only matrices with a non-zero determinant have an inverse''' ) return self.adjugate() * (1 / determinant) def __repr__(self ): '''simple docstring''' return str(self.rows ) def __str__(self ): '''simple docstring''' if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0] ) ) + "]]" return ( "[" + "\n ".join( [ '''[''' + '''. '''.join([str(a_ ) for value in row] ) + '''.]''' for row in self.rows ] ) + "]" ) def SCREAMING_SNAKE_CASE (self , a_ , a_ = None ): '''simple docstring''' __snake_case : List[str] = TypeError('''Row must be a list containing all ints and/or floats''' ) if not isinstance(a_ , a_ ): raise type_error for value in row: if not isinstance(a_ , (int, float) ): raise type_error if len(a_ ) != self.num_columns: raise ValueError( '''Row must be equal in length to the other rows in the matrix''' ) if position is None: self.rows.append(a_ ) else: __snake_case : List[Any] = self.rows[0:position] + [row] + self.rows[position:] def SCREAMING_SNAKE_CASE (self , a_ , a_ = None ): '''simple docstring''' __snake_case : Union[str, Any] = TypeError( '''Column must be a list containing all ints and/or floats''' ) if not isinstance(a_ , a_ ): raise type_error for value in column: if not isinstance(a_ , (int, float) ): raise type_error if len(a_ ) != self.num_rows: raise ValueError( '''Column must be equal in length to the other columns in the matrix''' ) if position is None: __snake_case : str = [self.rows[i] + [column[i]] for i in range(self.num_rows )] else: __snake_case : Union[str, Any] = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows ) ] def __eq__(self , a_ ): '''simple docstring''' if not isinstance(a_ , a_ ): return NotImplemented return self.rows == other.rows def __ne__(self , a_ ): '''simple docstring''' return not self == other def __neg__(self ): '''simple docstring''' return self * -1 def __add__(self , a_ ): '''simple docstring''' if self.order != other.order: raise ValueError('''Addition requires matrices of the same order''' ) return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __sub__(self , a_ ): '''simple docstring''' if self.order != other.order: raise ValueError('''Subtraction requires matrices of the same order''' ) return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __mul__(self , a_ ): '''simple docstring''' if isinstance(a_ , (int, float) ): return Matrix( [[int(element * other ) for element in row] for row in self.rows] ) elif isinstance(a_ , a_ ): if self.num_columns != other.num_rows: raise ValueError( '''The number of columns in the first matrix must ''' '''be equal to the number of rows in the second''' ) return Matrix( [ [Matrix.dot_product(a_ , a_ ) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( '''A Matrix can only be multiplied by an int, float, or another matrix''' ) def __pow__(self , a_ ): '''simple docstring''' if not isinstance(a_ , a_ ): raise TypeError('''A Matrix can only be raised to the power of an int''' ) if not self.is_square: raise ValueError('''Only square matrices can be raised to a power''' ) if other == 0: return self.identity() if other < 0: if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( '''Only invertable matrices can be raised to a negative power''' ) __snake_case : Dict = self for _ in range(other - 1 ): result *= self return result @classmethod def SCREAMING_SNAKE_CASE (cls , a_ , a_ ): '''simple docstring''' return sum(row[i] * column[i] for i in range(len(a_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
102
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowercase_ = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' lowercase_ = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' lowercase_ = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, homepage='''https://github.com/krishnap25/mauve''', inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''string''', id='''sequence''' ), '''references''': datasets.Value('''string''', id='''sequence''' ), } ), codebase_urls=['''https://github.com/krishnap25/mauve'''], reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ], ) def _SCREAMING_SNAKE_CASE ( self : int, _lowerCamelCase : str, _lowerCamelCase : Optional[Any], _lowerCamelCase : Any=None, _lowerCamelCase : Tuple=None, _lowerCamelCase : Optional[Any]=None, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str="auto", _lowerCamelCase : Union[str, Any]=-1, _lowerCamelCase : List[str]=0.9, _lowerCamelCase : int=5, _lowerCamelCase : Tuple=5_00, _lowerCamelCase : Union[str, Any]="gpt2-large", _lowerCamelCase : int=-1, _lowerCamelCase : Union[str, Any]=10_24, _lowerCamelCase : Union[str, Any]=25, _lowerCamelCase : str=5, _lowerCamelCase : Any=True, _lowerCamelCase : Union[str, Any]=25, ): '''simple docstring''' __A = compute_mauve( p_text=_lowerCamelCase, q_text=_lowerCamelCase, p_features=_lowerCamelCase, q_features=_lowerCamelCase, p_tokens=_lowerCamelCase, q_tokens=_lowerCamelCase, num_buckets=_lowerCamelCase, pca_max_data=_lowerCamelCase, kmeans_explained_var=_lowerCamelCase, kmeans_num_redo=_lowerCamelCase, kmeans_max_iter=_lowerCamelCase, featurize_model_name=_lowerCamelCase, device_id=_lowerCamelCase, max_text_length=_lowerCamelCase, divergence_curve_discretization_size=_lowerCamelCase, mauve_scaling_factor=_lowerCamelCase, verbose=_lowerCamelCase, seed=_lowerCamelCase, ) return out
266
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __snake_case ( UpperCamelCase_ ): _a = ['''image_processor''', '''tokenizer'''] _a = '''CLIPImageProcessor''' _a = ('''XLMRobertaTokenizer''', '''XLMRobertaTokenizerFast''') def __init__( self : Optional[Any] , A_ : Union[str, Any]=None , A_ : List[Any]=None , **A_ : int): lowerCAmelCase_ : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , A_ , ) lowerCAmelCase_ : str = kwargs.pop('''feature_extractor''') lowerCAmelCase_ : List[str] = 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__(A_ , A_) def __call__( self : Optional[Any] , A_ : Dict=None , A_ : int=None , A_ : str=None , **A_ : List[str]): if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''') if text is not None: lowerCAmelCase_ : str = self.tokenizer(A_ , return_tensors=A_ , **A_) if images is not None: lowerCAmelCase_ : str = self.image_processor(A_ , return_tensors=A_ , **A_) if text is not None and images is not None: lowerCAmelCase_ : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**A_) , tensor_type=A_) def UpperCAmelCase__ ( self : Any , *A_ : Tuple , **A_ : List[str]): return self.tokenizer.batch_decode(*A_ , **A_) def UpperCAmelCase__ ( self : str , *A_ : List[str] , **A_ : Tuple): return self.tokenizer.decode(*A_ , **A_) @property def UpperCAmelCase__ ( self : Optional[int]): lowerCAmelCase_ : Tuple = self.tokenizer.model_input_names lowerCAmelCase_ : Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
103
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowercase_ = imread(R'digital_image_processing/image_data/lena_small.jpg') lowercase_ = cvtColor(img, COLOR_BGR2GRAY) def lowerCAmelCase ( ): """simple docstring""" __A = cn.convert_to_negative(__UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def lowerCAmelCase ( ): """simple docstring""" with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(__UpperCamelCase , 1_1_0 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def lowerCAmelCase ( ): """simple docstring""" __A = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def lowerCAmelCase ( ): """simple docstring""" __A = imread('''digital_image_processing/image_data/lena_small.jpg''' , 0 ) # assert ambiguous array for all == True assert canny_img.all() __A = canny.canny(__UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def lowerCAmelCase ( ): """simple docstring""" assert gg.gaussian_filter(__UpperCamelCase , 5 , sigma=0.9 ).all() def lowerCAmelCase ( ): """simple docstring""" __A = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __A = conv.img_convolve(__UpperCamelCase , __UpperCamelCase ).astype(__UpperCamelCase ) assert res.any() def lowerCAmelCase ( ): """simple docstring""" assert med.median_filter(__UpperCamelCase , 3 ).any() def lowerCAmelCase ( ): """simple docstring""" __A , __A = sob.sobel_filter(__UpperCamelCase ) assert grad.any() and theta.any() def lowerCAmelCase ( ): """simple docstring""" __A = sp.make_sepia(__UpperCamelCase , 2_0 ) assert sepia.all() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" __A = bs.Burkes(imread(__UpperCamelCase , 1 ) , 1_2_0 ) burkes.process() assert burkes.output_img.any() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" __A = rs.NearestNeighbour(imread(__UpperCamelCase , 1 ) , 4_0_0 , 2_0_0 ) nn.process() assert nn.output.any() def lowerCAmelCase ( ): """simple docstring""" __A = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. __A = imread(__UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __A = 0 __A = 0 __A = image[x_coordinate][y_coordinate] __A = lbp.get_neighbors_pixel( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __A = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __A = lbp.local_binary_value(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert lbp_image.any()
266
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json''', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = 'convbert' def __init__( self : Optional[Any] ,lowercase__ : Dict=3_0_5_2_2 ,lowercase__ : Any=7_6_8 ,lowercase__ : Any=1_2 ,lowercase__ : Dict=1_2 ,lowercase__ : Union[str, Any]=3_0_7_2 ,lowercase__ : List[Any]="gelu" ,lowercase__ : Optional[int]=0.1 ,lowercase__ : Tuple=0.1 ,lowercase__ : Any=5_1_2 ,lowercase__ : Union[str, Any]=2 ,lowercase__ : Dict=0.0_2 ,lowercase__ : str=1e-1_2 ,lowercase__ : Tuple=1 ,lowercase__ : Optional[int]=0 ,lowercase__ : int=2 ,lowercase__ : Optional[int]=7_6_8 ,lowercase__ : List[Any]=2 ,lowercase__ : List[str]=9 ,lowercase__ : Any=1 ,lowercase__ : str=None ,**lowercase__ : List[Any] ,): super().__init__( pad_token_id=lowercase__ ,bos_token_id=lowercase__ ,eos_token_id=lowercase__ ,**lowercase__ ,) __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 = initializer_range __lowercase = layer_norm_eps __lowercase = embedding_size __lowercase = head_ratio __lowercase = conv_kernel_size __lowercase = num_groups __lowercase = classifier_dropout class lowercase_ (lowerCamelCase__ ): """simple docstring""" @property def SCREAMING_SNAKE_CASE ( self : Any ): if self.task == "multiple-choice": __lowercase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __lowercase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
104
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase_ = random.Random() if is_torch_available(): import torch def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase=1.0 , __UpperCamelCase=None , __UpperCamelCase=None ): """simple docstring""" if rng is None: __A = global_rng __A = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any, _lowerCamelCase : List[str], _lowerCamelCase : Any=7, _lowerCamelCase : Optional[int]=4_00, _lowerCamelCase : Optional[int]=20_00, _lowerCamelCase : Dict=1, _lowerCamelCase : Optional[Any]=0.0, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : Dict=True, ): '''simple docstring''' __A = parent __A = batch_size __A = min_seq_length __A = max_seq_length __A = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __A = feature_size __A = padding_value __A = sampling_rate __A = return_attention_mask __A = do_normalize def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[Any]=False, _lowerCamelCase : int=False ): '''simple docstring''' def _flatten(_lowerCamelCase : List[str] ): return list(itertools.chain(*_lowerCamelCase ) ) if equal_length: __A = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __A = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: __A = [np.asarray(_lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : int = ASTFeatureExtractor def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ASTFeatureExtractionTester(self ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' # Tests that all call wrap to encode_plus and batch_encode_plus __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __A = [floats_list((1, x) )[0] for x in range(8_00, 14_00, 2_00 )] __A = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] # Test not batched input __A = feat_extract(speech_inputs[0], return_tensors='''np''' ).input_values __A = feat_extract(np_speech_inputs[0], return_tensors='''np''' ).input_values self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test batched __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __A = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] __A = np.asarray(_lowerCamelCase ) __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' import torch __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __A = np.random.rand(1_00 ).astype(np.floataa ) __A = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Union[str, Any] ): '''simple docstring''' from datasets import load_dataset __A = load_dataset('''hf-internal-testing/librispeech_asr_dummy''', '''clean''', split='''validation''' ) # automatic decoding with librispeech __A = ds.sort('''id''' ).select(range(_lowerCamelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # fmt: off __A = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on __A = self._load_datasamples(1 ) __A = ASTFeatureExtractor() __A = feature_extractor(_lowerCamelCase, return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape, (1, 10_24, 1_28) ) self.assertTrue(torch.allclose(input_values[0, 0, :30], _lowerCamelCase, atol=1e-4 ) )
266
0
"""simple docstring""" from __future__ import annotations from typing import Any def _SCREAMING_SNAKE_CASE ( _lowercase : list ) ->int: '''simple docstring''' if not postfix_notation: return 0 a : List[str] = {"+", "-", "*", "/"} a : list[Any] = [] for token in postfix_notation: if token in operations: a, a : int = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(_lowercase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
105
"""simple docstring""" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = current_set.copy() for row_index, row in enumerate(__UpperCamelCase ): __A = row[0] for column_index, column in enumerate(__UpperCamelCase ): if magnitude == 0: __A = column continue __A = column / magnitude # Subtract to cancel term __A = current_set[0] __A = [first_row] __A = current_set[1::] for row in current_set: __A = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__UpperCamelCase ) continue for column_index in range(len(__UpperCamelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__UpperCamelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: __A = final_set[0] __A = [] __A = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __A = simplify(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __UpperCamelCase ) __A = resultant return final_set def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if len(__UpperCamelCase ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) __A = len(__UpperCamelCase ) + 1 if any(len(__UpperCamelCase ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__UpperCamelCase , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__UpperCamelCase ) == 1: return [equations[0][-1] / equations[0][0]] __A = equations.copy() if any(0 in row for row in data_set ): __A = data_set.copy() __A = [] for row_index, row in enumerate(__UpperCamelCase ): if 0 not in row: __A = data_set.pop(__UpperCamelCase ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __UpperCamelCase ) __A = data_set.copy() __A = simplify(__UpperCamelCase ) __A = simplified[::-1] __A = [] for row in simplified: __A = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __A = row.copy()[: len(__UpperCamelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__UpperCamelCase ) == 0: solutions.append(0 ) continue __A = temp_row[1::] __A = temp_row[::-1] for column_index, column in enumerate(__UpperCamelCase ): current_solution -= column * solutions[column_index] solutions.append(__UpperCamelCase ) __A = [] for item in solutions: final.append(float(round(__UpperCamelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
266
0
"""simple docstring""" import random def __SCREAMING_SNAKE_CASE ( A_ , A_ ): lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Optional[int] = [], [], [] for element in data: if element < pivot: less.append(A_ ) elif element > pivot: greater.append(A_ ) else: equal.append(A_ ) return less, equal, greater def __SCREAMING_SNAKE_CASE ( A_ , A_ ): # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(A_ ) or index < 0: return None lowerCAmelCase__ : str = items[random.randint(0 , len(A_ ) - 1 )] lowerCAmelCase__ : Optional[Any] = 0 lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ : Any = _partition(A_ , A_ ) lowerCAmelCase__ : str = len(A_ ) lowerCAmelCase__ : Optional[Any] = len(A_ ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(A_ , A_ ) # must be in larger else: return quick_select(A_ , index - (m + count) )
106
"""simple docstring""" from __future__ import annotations from typing import Any def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not postfix_notation: return 0 __A = {'''+''', '''-''', '''*''', '''/'''} __A = [] for token in postfix_notation: if token in operations: __A , __A = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(__UpperCamelCase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
266
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCAmelCase : str = logging.get_logger(__name__) __lowerCAmelCase : Dict = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class snake_case__ (_UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = """camembert""" def __init__( self : Any , __lowerCamelCase : Tuple=3_05_22 , __lowerCamelCase : Optional[Any]=7_68 , __lowerCamelCase : Tuple=12 , __lowerCamelCase : Any=12 , __lowerCamelCase : Any=30_72 , __lowerCamelCase : str="gelu" , __lowerCamelCase : int=0.1 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : Optional[Any]=5_12 , __lowerCamelCase : Any=2 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Optional[Any]=1e-12 , __lowerCamelCase : int=1 , __lowerCamelCase : Union[str, Any]=0 , __lowerCamelCase : List[str]=2 , __lowerCamelCase : Tuple="absolute" , __lowerCamelCase : List[str]=True , __lowerCamelCase : Dict=None , **__lowerCamelCase : Dict , ) -> Tuple: super().__init__(pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = hidden_act a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = initializer_range a = layer_norm_eps a = position_embedding_type a = use_cache a = classifier_dropout class snake_case__ (_UpperCamelCase ): """simple docstring""" @property def __UpperCAmelCase ( self : Dict ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a = {0: "batch", 1: "choice", 2: "sequence"} else: a = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
107
"""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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple, _lowerCamelCase : List[str]=13, _lowerCamelCase : Optional[Any]=7, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : int=True, _lowerCamelCase : List[str]=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : int=99, _lowerCamelCase : Optional[int]=32, _lowerCamelCase : Tuple=5, _lowerCamelCase : Tuple=4, _lowerCamelCase : str=37, _lowerCamelCase : Union[str, Any]="gelu", _lowerCamelCase : int=0.1, _lowerCamelCase : List[Any]=0.1, _lowerCamelCase : Dict=5_12, _lowerCamelCase : List[Any]=16, _lowerCamelCase : Any=2, _lowerCamelCase : Any=0.02, _lowerCamelCase : Dict=4, ): '''simple docstring''' __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_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_choices def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __A = None if self.use_attention_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 = 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 _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Dict = True A_ : Tuple = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = FlaxRoFormerModelTester(self ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''', from_pt=_lowerCamelCase ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase ) @require_flax class snake_case ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __A = jnp.array([[0, 1, 2, 3, 4, 5]] ) __A = model(_lowerCamelCase )[0] __A = 5_00_00 __A = (1, 6, vocab_size) self.assertEqual(output.shape, _lowerCamelCase ) __A = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3], _lowerCamelCase, atol=1e-4 ) )
266
0
"""simple docstring""" import functools from typing import Any def a__ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : list[str] ): '''simple docstring''' if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("the string should be not empty string" ) if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or not all( isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) > 0 for item in words ): raise ValueError("the words should be a list of non-empty strings" ) # Build trie lowerCAmelCase : dict[str, Any] = {} lowerCAmelCase : Union[str, Any] = "WORD_KEEPER" for word in words: lowerCAmelCase : int = trie for c in word: if c not in trie_node: lowerCAmelCase : Union[str, Any] = {} lowerCAmelCase : Tuple = trie_node[c] lowerCAmelCase : Optional[Any] = True lowerCAmelCase : str = len(SCREAMING_SNAKE_CASE ) # Dynamic programming method @functools.cache def is_breakable(SCREAMING_SNAKE_CASE : int ) -> bool: if index == len_string: return True lowerCAmelCase : str = trie for i in range(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): lowerCAmelCase : Tuple = trie_node.get(string[i] , SCREAMING_SNAKE_CASE ) if trie_node is None: return False if trie_node.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
108
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase ( __UpperCamelCase = 1_0_0_0_0_0_0 , __UpperCamelCase = 1_0 ): """simple docstring""" __A = defaultdict(__UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __A = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __A = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(__UpperCamelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 1_0 ) if __name__ == "__main__": print(F'''{solution() = }''')
266
0
"""simple docstring""" import unittest import numpy as np from datasets import load_dataset 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 BeitImageProcessor class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=False , ) -> List[str]: '''simple docstring''' UpperCAmelCase : Dict = size if size is not None else {"""height""": 20, """width""": 20} UpperCAmelCase : Optional[int] = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} UpperCAmelCase : Optional[int] = parent UpperCAmelCase : Any = batch_size UpperCAmelCase : Dict = num_channels UpperCAmelCase : Union[str, Any] = image_size UpperCAmelCase : int = min_resolution UpperCAmelCase : Any = max_resolution UpperCAmelCase : int = do_resize UpperCAmelCase : Optional[int] = size UpperCAmelCase : Tuple = do_center_crop UpperCAmelCase : List[str] = crop_size UpperCAmelCase : Dict = do_normalize UpperCAmelCase : List[str] = image_mean UpperCAmelCase : Any = image_std UpperCAmelCase : List[Any] = do_reduce_labels def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def _snake_case ( ): UpperCAmelCase : Tuple = load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) UpperCAmelCase : Any = Image.open(dataset[0]["""file"""] ) UpperCAmelCase : Optional[int] = Image.open(dataset[1]["""file"""] ) return image, map def _snake_case ( ): UpperCAmelCase : Optional[int] = load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) UpperCAmelCase : int = Image.open(ds[0]["""file"""] ) UpperCAmelCase : Optional[int] = Image.open(ds[1]["""file"""] ) UpperCAmelCase : Dict = Image.open(ds[2]["""file"""] ) UpperCAmelCase : List[Any] = Image.open(ds[3]["""file"""] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ , unittest.TestCase ): __lowerCAmelCase : int = BeitImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' UpperCAmelCase : int = BeitImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self ) -> Tuple: '''simple docstring''' UpperCAmelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """size""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """do_center_crop""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """center_crop""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """do_normalize""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """image_mean""" ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , """image_std""" ) ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' UpperCAmelCase : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 20, """width""": 20} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) self.assertEqual(image_processor.do_reduce_labels , _SCREAMING_SNAKE_CASE ) UpperCAmelCase : str = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) self.assertEqual(image_processor.do_reduce_labels , _SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' UpperCAmelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input UpperCAmelCase : List[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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCAmelCase : Any = image_processing(_SCREAMING_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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , numpify=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input UpperCAmelCase : 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.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched UpperCAmelCase : str = image_processing(_SCREAMING_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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , torchify=_SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input UpperCAmelCase : int = 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 : Optional[Any] = image_processing(_SCREAMING_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 SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' UpperCAmelCase : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , torchify=_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Tuple = [] for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input UpperCAmelCase : Optional[int] = image_processing(image_inputs[0] , maps[0] , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 1, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test batched UpperCAmelCase : Tuple = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].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"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test not batched input (PIL images) UpperCAmelCase , UpperCAmelCase : Any = prepare_semantic_single_inputs() UpperCAmelCase : int = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 1, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) # Test batched input (PIL images) UpperCAmelCase , UpperCAmelCase : List[str] = prepare_semantic_batch_inputs() UpperCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertEqual( encoding["""pixel_values"""].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual( encoding["""labels"""].shape , ( 2, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) self.assertEqual(encoding["""labels"""].dtype , torch.long ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' UpperCAmelCase : Tuple = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 UpperCAmelCase , UpperCAmelCase : Dict = prepare_semantic_single_inputs() UpperCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 150 ) UpperCAmelCase : List[Any] = True UpperCAmelCase : Union[str, Any] = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertTrue(encoding["""labels"""].min().item() >= 0 ) self.assertTrue(encoding["""labels"""].max().item() <= 255 )
109
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : Optional[int]=2, _lowerCamelCase : Optional[int]=3, _lowerCamelCase : int=64, _lowerCamelCase : List[str]=None ): '''simple docstring''' __A = np.random.default_rng(_lowerCamelCase ) __A = length __A = rng.normal(size=(length,) ).astype(np.floataa ) __A = a * self.x + b + rng.normal(scale=0.1, size=(length,) ).astype(np.floataa ) def __len__( self : str ): '''simple docstring''' return self.length def __getitem__( self : Dict, _lowerCamelCase : Optional[int] ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple=0, _lowerCamelCase : Any=0, _lowerCamelCase : Optional[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Optional[Any]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a[0] + self.b[0] class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : str, _lowerCamelCase : Optional[Any]=0, _lowerCamelCase : Any=0, _lowerCamelCase : List[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[str]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a + self.b def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase = 1_6 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __A = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __A = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __A = load_dataset('''csv''' , data_files=__UpperCamelCase ) __A = datasets['''train'''].unique('''label''' ) __A = {v: i for i, v in enumerate(__UpperCamelCase )} def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding='''max_length''' ) if "label" in examples: __A = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __A = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(__UpperCamelCase ): # 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(__UpperCamelCase , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' ) return tokenizer.pad(__UpperCamelCase , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __A = DataLoader(tokenized_datasets['''train'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2 ) __A = DataLoader(tokenized_datasets['''validation'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
266
0
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class a ( ctypes.Structure ): """simple docstring""" UpperCAmelCase = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def _snake_case ( ): if os.name == "nt": A__ = CursorInfo() A__ = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) A__ = False ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write("""\033[?25l""" ) sys.stdout.flush() def _snake_case ( ): if os.name == "nt": A__ = CursorInfo() A__ = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) A__ = True ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write("""\033[?25h""" ) sys.stdout.flush() @contextmanager def _snake_case ( ): try: hide_cursor() yield finally: show_cursor()
335
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowercase_ = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' lowercase_ = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' lowercase_ = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), id='''references''' ), } ), ) def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[List[List[str]]], _lowerCamelCase : List[List[str]], _lowerCamelCase : int = 1, _lowerCamelCase : int = 4, ): '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCamelCase, hypotheses=_lowerCamelCase, min_len=_lowerCamelCase, max_len=_lowerCamelCase ) }
266
0
'''simple docstring''' import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class __UpperCAmelCase ( _lowerCAmelCase , unittest.TestCase ): __lowercase = BertJapaneseTokenizer __lowercase = False __lowercase = True def lowerCamelCase ( self ): """simple docstring""" super().setUp() _snake_case = [ '[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは', '世界', '##世界', '、', '##、', '。', '##。', ] _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 lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = 'こんにちは、世界。 \nこんばんは、世界。' _snake_case = 'こんにちは 、 世界 。 こんばんは 、 世界 。' return input_text, output_text def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case , _snake_case = self.get_input_output_texts(_lowerCamelCase ) _snake_case = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) _snake_case = tokenizer.decode(_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase ) return text, ids def lowerCamelCase ( self ): """simple docstring""" pass # TODO add if relevant def lowerCamelCase ( self ): """simple docstring""" pass # TODO add if relevant def lowerCamelCase ( self ): """simple docstring""" pass # TODO add if relevant def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.tokenizer_class(self.vocab_file ) _snake_case = tokenizer.tokenize('こんにちは、世界。\nこんばんは、世界。' ) self.assertListEqual(_lowerCamelCase , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.tokenizer_class(self.vocab_file , word_tokenizer_type='mecab' ) self.assertIsNotNone(_lowerCamelCase ) _snake_case = 'こんにちは、世界。\nこんばんは、世界。' _snake_case = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) _snake_case = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(_lowerCamelCase , 'wb' ) as handle: pickle.dump(_lowerCamelCase , _lowerCamelCase ) with open(_lowerCamelCase , 'rb' ) as handle: _snake_case = pickle.load(_lowerCamelCase ) _snake_case = tokenizer_new.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = MecabTokenizer(mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def lowerCamelCase ( self ): """simple docstring""" try: _snake_case = MecabTokenizer(mecab_dic='unidic_lite' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def lowerCamelCase ( self ): """simple docstring""" try: _snake_case = MecabTokenizer(mecab_dic='unidic' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = MecabTokenizer(do_lower_case=_lowerCamelCase , mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iphone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def lowerCamelCase ( self ): """simple docstring""" try: _snake_case = MecabTokenizer( do_lower_case=_lowerCamelCase , normalize_text=_lowerCamelCase , mecab_option='-d /usr/local/lib/mecab/dic/jumandic' ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れた', '\u3000', '。'] , ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = MecabTokenizer(normalize_text=_lowerCamelCase , mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', ' ', '。'] , ) @require_sudachi def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.tokenizer_class(self.vocab_file , word_tokenizer_type='sudachi' ) self.assertIsNotNone(_lowerCamelCase ) _snake_case = 'こんにちは、世界。\nこんばんは、世界。' _snake_case = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) _snake_case = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(_lowerCamelCase , 'wb' ) as handle: pickle.dump(_lowerCamelCase , _lowerCamelCase ) with open(_lowerCamelCase , 'rb' ) as handle: _snake_case = pickle.load(_lowerCamelCase ) _snake_case = tokenizer_new.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) @require_sudachi def lowerCamelCase ( self ): """simple docstring""" _snake_case = SudachiTokenizer(sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iPhone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' '] , ) @require_sudachi def lowerCamelCase ( self ): """simple docstring""" _snake_case = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='A' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国', '人', '参政', '権'] ) @require_sudachi def lowerCamelCase ( self ): """simple docstring""" _snake_case = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='B' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国人', '参政権'] ) @require_sudachi def lowerCamelCase ( self ): """simple docstring""" _snake_case = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='C' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国人参政権'] ) @require_sudachi def lowerCamelCase ( self ): """simple docstring""" _snake_case = SudachiTokenizer(do_lower_case=_lowerCamelCase , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iphone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' '] , ) @require_sudachi def lowerCamelCase ( self ): """simple docstring""" _snake_case = SudachiTokenizer(normalize_text=_lowerCamelCase , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iPhone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', '\u3000', '。', ' ', ' '] , ) @require_sudachi def lowerCamelCase ( self ): """simple docstring""" _snake_case = SudachiTokenizer(trim_whitespace=_lowerCamelCase , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) @require_jumanpp def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.tokenizer_class(self.vocab_file , word_tokenizer_type='jumanpp' ) self.assertIsNotNone(_lowerCamelCase ) _snake_case = 'こんにちは、世界。\nこんばんは、世界。' _snake_case = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) _snake_case = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(_lowerCamelCase , 'wb' ) as handle: pickle.dump(_lowerCamelCase , _lowerCamelCase ) with open(_lowerCamelCase , 'rb' ) as handle: _snake_case = pickle.load(_lowerCamelCase ) _snake_case = tokenizer_new.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) @require_jumanpp def lowerCamelCase ( self ): """simple docstring""" _snake_case = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def lowerCamelCase ( self ): """simple docstring""" _snake_case = JumanppTokenizer(do_lower_case=_lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iphone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def lowerCamelCase ( self ): """simple docstring""" _snake_case = JumanppTokenizer(normalize_text=_lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['ア', 'ッ', 'フ', '゚', 'ル', 'ストア', 'で', 'iPhone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def lowerCamelCase ( self ): """simple docstring""" _snake_case = JumanppTokenizer(trim_whitespace=_lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れた', '。'] , ) @require_jumanpp def lowerCamelCase ( self ): """simple docstring""" _snake_case = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize('ありがとうございますm(_ _)m見つけるのが大変です。' ) , ['ありがとう', 'ございます', 'm(_ _)m', '見つける', 'の', 'が', '大変です', '。'] , ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = ['[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは'] _snake_case = {} for i, token in enumerate(_lowerCamelCase ): _snake_case = i _snake_case = WordpieceTokenizer(vocab=_lowerCamelCase , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('こんにちは' ) , ['こんにちは'] ) self.assertListEqual(tokenizer.tokenize('こんばんは' ) , ['こん', '##ばんは'] ) self.assertListEqual(tokenizer.tokenize('こんばんは こんばんにちは こんにちは' ) , ['こん', '##ばんは', '[UNK]', 'こんにちは'] ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = BertJapaneseTokenizer.from_pretrained('nlp-waseda/roberta-base-japanese-with-auto-jumanpp' ) _snake_case = tokenizer.subword_tokenizer _snake_case = subword_tokenizer.tokenize('国境 の 長い トンネル を 抜ける と 雪国 であった 。' ) self.assertListEqual(_lowerCamelCase , ['▁国境', '▁の', '▁長い', '▁トンネル', '▁を', '▁抜ける', '▁と', '▁雪', '国', '▁であった', '▁。'] ) _snake_case = subword_tokenizer.tokenize('こんばんは こんばん にち は こんにちは' ) self.assertListEqual(_lowerCamelCase , ['▁こん', 'ばん', 'は', '▁こん', 'ばん', '▁に', 'ち', '▁は', '▁こんにちは'] ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese' ) _snake_case = tokenizer.encode('ありがとう。' , add_special_tokens=_lowerCamelCase ) _snake_case = tokenizer.encode('どういたしまして。' , add_special_tokens=_lowerCamelCase ) _snake_case = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase ) _snake_case = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase , _lowerCamelCase ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class __UpperCAmelCase ( _lowerCAmelCase , unittest.TestCase ): __lowercase = BertJapaneseTokenizer __lowercase = False def lowerCamelCase ( self ): """simple docstring""" super().setUp() _snake_case = ['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。'] _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 lowerCamelCase ( self , **lowerCAmelCase_ ): """simple docstring""" return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type='character' , **_lowerCamelCase ) def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" _snake_case = 'こんにちは、世界。 \nこんばんは、世界。' _snake_case = 'こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。' return input_text, output_text def lowerCamelCase ( self ): """simple docstring""" pass # TODO add if relevant def lowerCamelCase ( self ): """simple docstring""" pass # TODO add if relevant def lowerCamelCase ( self ): """simple docstring""" pass # TODO add if relevant def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.tokenizer_class(self.vocab_file , subword_tokenizer_type='character' ) _snake_case = tokenizer.tokenize('こんにちは、世界。 \nこんばんは、世界。' ) self.assertListEqual( _lowerCamelCase , ['こ', 'ん', 'に', 'ち', 'は', '、', '世', '界', '。', 'こ', 'ん', 'ば', 'ん', 'は', '、', '世', '界', '。'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = ['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。'] _snake_case = {} for i, token in enumerate(_lowerCamelCase ): _snake_case = i _snake_case = CharacterTokenizer(vocab=_lowerCamelCase , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('こんにちは' ) , ['こ', 'ん', 'に', 'ち', 'は'] ) self.assertListEqual(tokenizer.tokenize('こんにちほ' ) , ['こ', 'ん', 'に', 'ち', '[UNK]'] ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese-char' ) _snake_case = tokenizer.encode('ありがとう。' , add_special_tokens=_lowerCamelCase ) _snake_case = tokenizer.encode('どういたしまして。' , add_special_tokens=_lowerCamelCase ) _snake_case = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase ) _snake_case = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase , _lowerCamelCase ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" _snake_case = 'cl-tohoku/bert-base-japanese' _snake_case = AutoTokenizer.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" _snake_case = 'cl-tohoku/bert-base-japanese' with self.assertLogs('transformers' , level='WARNING' ) as cm: BertTokenizer.from_pretrained(_lowerCamelCase ) self.assertTrue( cm.records[0].message.startswith( 'The tokenizer class you load from this checkpoint is not the same type as the class this function' ' is called from.' ) ) _snake_case = 'bert-base-cased' with self.assertLogs('transformers' , level='WARNING' ) as cm: BertJapaneseTokenizer.from_pretrained(_lowerCamelCase ) self.assertTrue( cm.records[0].message.startswith( 'The tokenizer class you load from this checkpoint is not the same type as the class this function' ' is called from.' ) )
42
"""simple docstring""" class snake_case : '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : list[int] ): '''simple docstring''' __A = len(_lowerCamelCase ) __A = [0] * len_array if len_array > 0: __A = array[0] for i in range(1, _lowerCamelCase ): __A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : int ): '''simple docstring''' __A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_lowerCamelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
266
0
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging a : List[Any] = logging.get_logger(__name__) class __UpperCamelCase ( _lowerCAmelCase ): lowerCamelCase : int =["input_features", "attention_mask"] def __init__( self , lowerCAmelCase__=80 , lowerCAmelCase__=1_6000 , lowerCAmelCase__=80 , lowerCAmelCase__=0.0 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , **lowerCAmelCase__ , ) -> str: super().__init__(feature_size=_lowerCamelCase , sampling_rate=_lowerCamelCase , padding_value=_lowerCamelCase , **_lowerCamelCase ) a : Optional[Any] = num_mel_bins a : Tuple = do_ceptral_normalize a : str = normalize_means a : Optional[int] = normalize_vars a : Dict = True def __a ( self , lowerCAmelCase__ , ) -> List[str]: a : Optional[Any] = waveform * (2**15) # Kaldi compliance: 16-bit signed integers a : Optional[int] = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ) a : Dict = ta_kaldi.fbank(_lowerCamelCase , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def __a ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = True , lowerCAmelCase__ = True , lowerCAmelCase__ = 0.0 , ) -> Optional[Any]: # make sure we normalize float32 arrays if normalize_means: a : int = x[:input_length].mean(axis=0 ) a : int = np.subtract(_lowerCamelCase , _lowerCamelCase ) if normalize_vars: a : Any = x[:input_length].std(axis=0 ) a : Dict = np.divide(_lowerCamelCase , _lowerCamelCase ) if input_length < x.shape[0]: a : List[Any] = padding_value # make sure array is in float32 a : List[str] = x.astype(np.floataa ) return x def __a ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> int: a : str = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_lowerCamelCase , _lowerCamelCase , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(_lowerCamelCase , _lowerCamelCase ) ] def __call__( self , lowerCAmelCase__ , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = None , **lowerCAmelCase__ , ) -> List[Any]: if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( "It is strongly recommended to pass the `sampling_rate` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug." ) a : Dict = isinstance(_lowerCamelCase , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) a : Any = is_batched_numpy or ( isinstance(_lowerCamelCase , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: a : List[Any] = [np.asarray(_lowerCamelCase , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_lowerCamelCase , np.ndarray ): a : List[Any] = np.asarray(_lowerCamelCase , dtype=np.floataa ) elif isinstance(_lowerCamelCase , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): a : Optional[int] = raw_speech.astype(np.floataa ) # always return batch if not is_batched: a : Optional[Any] = [raw_speech] # extract fbank features a : Dict = [self._extract_fbank_features(_lowerCamelCase ) for waveform in raw_speech] # convert into correct format for padding a : List[Any] = BatchFeature({"input_features": features} ) a : Union[str, Any] = self.pad( _lowerCamelCase , padding=_lowerCamelCase , max_length=_lowerCamelCase , truncation=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=_lowerCamelCase , **_lowerCamelCase , ) # make sure list is in array format a : List[Any] = padded_inputs.get("input_features" ) if isinstance(input_features[0] , _lowerCamelCase ): a : Tuple = [np.asarray(_lowerCamelCase , dtype=np.floataa ) for feature in input_features] a : Optional[Any] = padded_inputs.get("attention_mask" ) if attention_mask is not None: a : int = [np.asarray(_lowerCamelCase , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: a : Union[str, Any] = ( np.array(_lowerCamelCase , dtype=np.intaa ) if self._get_padding_strategies(_lowerCamelCase , max_length=_lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) a : Optional[Any] = self.normalize( padded_inputs["input_features"] , attention_mask=_lowerCamelCase ) if return_tensors is not None: a : List[Any] = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs
105
"""simple docstring""" import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ = logging.get_logger(__name__) lowercase_ = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } lowercase_ = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } lowercase_ = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCAmelCase ( ): """simple docstring""" __A = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __A = bs[:] __A = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 __A = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase , __UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = set() __A = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __A = char return pairs class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : Tuple = VOCAB_FILES_NAMES A_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : Dict, _lowerCamelCase : Optional[Any], _lowerCamelCase : List[str], _lowerCamelCase : Dict="replace", _lowerCamelCase : Any="<s>", _lowerCamelCase : Optional[int]="</s>", _lowerCamelCase : Dict="</s>", _lowerCamelCase : List[Any]="<s>", _lowerCamelCase : List[str]="<unk>", _lowerCamelCase : str="<pad>", _lowerCamelCase : Any="<mask>", _lowerCamelCase : Any=False, **_lowerCamelCase : Tuple, ): '''simple docstring''' __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else bos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else eos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else sep_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else cls_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else unk_token __A = 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 __A = 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: __A = json.load(_lowerCamelCase ) __A = {v: k for k, v in self.encoder.items()} __A = errors # how to handle errors in decoding __A = bytes_to_unicode() __A = {v: k for k, v in self.byte_encoder.items()} with open(_lowerCamelCase, encoding='''utf-8''' ) as merges_handle: __A = merges_handle.read().split('''\n''' )[1:-1] __A = [tuple(merge.split() ) for merge in bpe_merges] __A = dict(zip(_lowerCamelCase, range(len(_lowerCamelCase ) ) ) ) __A = {} __A = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __A = 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.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return len(self.encoder ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return dict(self.encoder, **self.added_tokens_encoder ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[Any] ): '''simple docstring''' if token in self.cache: return self.cache[token] __A = tuple(_lowerCamelCase ) __A = get_pairs(_lowerCamelCase ) if not pairs: return token while True: __A = min(_lowerCamelCase, key=lambda _lowerCamelCase : self.bpe_ranks.get(_lowerCamelCase, float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __A , __A = bigram __A = [] __A = 0 while i < len(_lowerCamelCase ): try: __A = word.index(_lowerCamelCase, _lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __A = 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 __A = tuple(_lowerCamelCase ) __A = new_word if len(_lowerCamelCase ) == 1: break else: __A = get_pairs(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = word return word def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Dict ): '''simple docstring''' __A = [] for token in re.findall(self.pat, _lowerCamelCase ): __A = ''''''.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 _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : Dict ): '''simple docstring''' return self.encoder.get(_lowerCamelCase, self.encoder.get(self.unk_token ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Any ): '''simple docstring''' return self.decoder.get(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' __A = ''''''.join(_lowerCamelCase ) __A = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''', errors=self.errors ) return text def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : str, _lowerCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __A = 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''' ) __A = 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!''' ) __A = token_index writer.write(''' '''.join(_lowerCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None, _lowerCamelCase : bool = 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 _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Union[str, Any], _lowerCamelCase : List[str]=False, **_lowerCamelCase : List[Any] ): '''simple docstring''' __A = 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()): __A = ''' ''' + text return (text, kwargs) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : "Conversation" ): '''simple docstring''' __A = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = self.encode(_lowerCamelCase ) if len(_lowerCamelCase ) > self.model_max_length: __A = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
266
0
'''simple docstring''' from manim import * class __lowerCAmelCase (_lowerCAmelCase ): '''simple docstring''' def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = Rectangle(height=0.5 , width=0.5 ) lowercase__ = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) lowercase__ = [mem.copy() for i in range(6 )] lowercase__ = [mem.copy() for i in range(6 )] lowercase__ = VGroup(*_lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowercase__ = VGroup(*_lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowercase__ = VGroup(_lowerCamelCase , _lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowercase__ = Text('''CPU''' , font_size=24 ) lowercase__ = Group(_lowerCamelCase , _lowerCamelCase ).arrange(_lowerCamelCase , buff=0.5 , aligned_edge=_lowerCamelCase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_lowerCamelCase ) lowercase__ = [mem.copy() for i in range(1 )] lowercase__ = VGroup(*_lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowercase__ = Text('''GPU''' , font_size=24 ) lowercase__ = Group(_lowerCamelCase , _lowerCamelCase ).arrange(_lowerCamelCase , buff=0.5 , aligned_edge=_lowerCamelCase ) gpu.align_to(_lowerCamelCase , _lowerCamelCase ) gpu.set_x(gpu.get_x() - 1 ) self.add(_lowerCamelCase ) lowercase__ = [mem.copy() for i in range(6 )] lowercase__ = VGroup(*_lowerCamelCase ).arrange(_lowerCamelCase , buff=0 ) lowercase__ = Text('''Model''' , font_size=24 ) lowercase__ = Group(_lowerCamelCase , _lowerCamelCase ).arrange(_lowerCamelCase , buff=0.5 , aligned_edge=_lowerCamelCase ) model.move_to([3, -1.0, 0] ) self.play( Create(_lowerCamelCase , run_time=1 ) , Create(_lowerCamelCase , run_time=1 ) , Create(_lowerCamelCase , run_time=1 ) , ) lowercase__ = MarkupText( f"First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM." , font_size=24 , ) lowercase__ = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowercase__ = 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(_lowerCamelCase , run_time=2.5 ) , Write(_lowerCamelCase ) , Write(_lowerCamelCase ) ) self.add(_lowerCamelCase ) lowercase__ = [] lowercase__ = [] lowercase__ = [] for i, rect in enumerate(_lowerCamelCase ): lowercase__ = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(_lowerCamelCase , opacity=0.7 ) cpu_target.move_to(_lowerCamelCase ) cpu_target.generate_target() lowercase__ = 0.46 / 4 lowercase__ = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=_lowerCamelCase ) 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=_lowerCamelCase , buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=_lowerCamelCase , buff=0.0 ) cpu_targs.append(_lowerCamelCase ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(_lowerCamelCase ) ) second_animations.append(MoveToTarget(_lowerCamelCase , run_time=1.5 ) ) self.play(*_lowerCamelCase ) self.play(*_lowerCamelCase ) self.wait()
2
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging lowercase_ = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase ( ): """simple docstring""" __A = '''https://pypi.org/pypi/diffusers/json''' __A = json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys() return sorted(__UpperCamelCase , key=lambda __UpperCamelCase : version.Version(__UpperCamelCase ) ) def lowerCAmelCase ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__UpperCamelCase ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = Path(__UpperCamelCase ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" init_hf_modules() __A = Path(__UpperCamelCase ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import .xxx` __A = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Unique-ify return list(set(__UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = False __A = [module_file] __A = [] # Let's recurse through all relative imports while not no_change: __A = [] for f in files_to_check: new_imports.extend(get_relative_imports(__UpperCamelCase ) ) __A = Path(__UpperCamelCase ).parent __A = [str(module_path / m ) for m in new_imports] __A = [f for f in new_import_files if f not in all_relative_imports] __A = [f'{f}.py' for f in new_import_files] __A = len(__UpperCamelCase ) == 0 all_relative_imports.extend(__UpperCamelCase ) return all_relative_imports def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import xxx` __A = re.findall('''^\s*import\s+(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Only keep the top-level module __A = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all __A = list(set(__UpperCamelCase ) ) __A = [] for imp in imports: try: importlib.import_module(__UpperCamelCase ) except ImportError: missing_packages.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' f'{", ".join(__UpperCamelCase )}. Run `pip install {" ".join(__UpperCamelCase )}`' ) return get_relative_imports(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" __A = module_path.replace(os.path.sep , '''.''' ) __A = importlib.import_module(__UpperCamelCase ) if class_name is None: return find_pipeline_class(__UpperCamelCase ) return getattr(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" from ..pipelines import DiffusionPipeline __A = dict(inspect.getmembers(__UpperCamelCase , inspect.isclass ) ) __A = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __UpperCamelCase ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:' f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in' f' {loaded_module}.' ) __A = cls return pipeline_class def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , ): """simple docstring""" __A = str(__UpperCamelCase ) __A = os.path.join(__UpperCamelCase , __UpperCamelCase ) if os.path.isfile(__UpperCamelCase ): __A = module_file_or_url __A = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: __A = get_diffusers_versions() # cut ".dev0" __A = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: __A = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(f'Defaulting to latest_version: {revision}.' ) elif revision in available_versions: __A = f'v{revision}' elif revision == "main": __A = revision else: raise ValueError( f'`custom_revision`: {revision} does not exist. Please make sure to choose one of' f' {", ".join(available_versions + ["main"] )}.' ) # community pipeline on GitHub __A = COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase , pipeline=__UpperCamelCase ) try: __A = cached_download( __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = '''git''' __A = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise else: try: # Load from URL or cache if already cached __A = hf_hub_download( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise # Check we have all the requirements in our environment __A = check_imports(__UpperCamelCase ) # Now we move the module inside our cached dynamic modules. __A = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__UpperCamelCase ) __A = Path(__UpperCamelCase ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__UpperCamelCase , submodule_path / module_file ) for module_needed in modules_needed: __A = f'{module_needed}.py' shutil.copy(os.path.join(__UpperCamelCase , __UpperCamelCase ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__UpperCamelCase , __UpperCamelCase ): __A = use_auth_token elif use_auth_token is True: __A = HfFolder.get_token() else: __A = None __A = model_info(__UpperCamelCase , revision=__UpperCamelCase , token=__UpperCamelCase ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. __A = submodule_path / commit_hash __A = full_submodule + os.path.sep + commit_hash create_dynamic_module(__UpperCamelCase ) if not (submodule_path / module_file).exists(): shutil.copy(__UpperCamelCase , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __UpperCamelCase , f'{module_needed}.py' , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return os.path.join(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , **__UpperCamelCase , ): """simple docstring""" __A = get_cached_module_file( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return get_class_in_module(__UpperCamelCase , final_module.replace('''.py''' , '''''' ) )
266
0
"""simple docstring""" from __future__ import annotations import math def lowercase_ ( _snake_case ): if num <= 0: SCREAMING_SNAKE_CASE__ : List[str] = f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [True] * (num + 1) SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2 SCREAMING_SNAKE_CASE__ : Tuple = int(math.sqrt(__UpperCamelCase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__UpperCamelCase ) # Set multiples of start be False for i in range(start * start ,num + 1 ,__UpperCamelCase ): if sieve[i] is True: SCREAMING_SNAKE_CASE__ : Dict = False start += 1 for j in range(end + 1 ,num + 1 ): if sieve[j] is True: prime.append(__UpperCamelCase ) return prime if __name__ == "__main__": print(prime_sieve(int(input('Enter a positive integer: ').strip())))
25
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[int] ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''], model_result['''ss'''] ): __A = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sgugger/tiny-distilbert-classification''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, only_pretrain_model=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, torchscript=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''', '''Cant do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, fpaa=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) # set architectures equal to `None` __A = None __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''', '''Can\'t do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], fpaa=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, save_to_csv=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], inference_time_csv_file=os.path.join(_lowerCamelCase, '''inf_time.csv''' ), train_memory_csv_file=os.path.join(_lowerCamelCase, '''train_mem.csv''' ), inference_memory_csv_file=os.path.join(_lowerCamelCase, '''inf_mem.csv''' ), train_time_csv_file=os.path.join(_lowerCamelCase, '''train_time.csv''' ), env_info_csv_file=os.path.join(_lowerCamelCase, '''env.csv''' ), multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''env.csv''' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_lowerCamelCase : List[Any] ): self.assertTrue(hasattr(_lowerCamelCase, '''sequential''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''cumulative''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''current''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], log_filename=os.path.join(_lowerCamelCase, '''log.txt''' ), log_print=_lowerCamelCase, trace_memory_line_by_line=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''log.txt''' ) ).exists() )
266
0
from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig 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 TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A( _lowerCAmelCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_lowerCamelCase , """embed_dim""" ) ) self.parent.assertTrue(hasattr(_lowerCamelCase , """num_heads""" ) ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[16, 48, 96] , SCREAMING_SNAKE_CASE_=[1, 3, 6] , SCREAMING_SNAKE_CASE_=[1, 2, 10] , SCREAMING_SNAKE_CASE_=[7, 3, 3] , SCREAMING_SNAKE_CASE_=[4, 2, 2] , SCREAMING_SNAKE_CASE_=[2, 1, 1] , SCREAMING_SNAKE_CASE_=[2, 2, 2] , SCREAMING_SNAKE_CASE_=[False, False, True] , SCREAMING_SNAKE_CASE_=[0.0, 0.0, 0.0] , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1E-12 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = patch_sizes UpperCamelCase__ = patch_stride UpperCamelCase__ = patch_padding UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = num_labels UpperCamelCase__ = num_channels UpperCamelCase__ = embed_dim UpperCamelCase__ = num_heads UpperCamelCase__ = stride_kv UpperCamelCase__ = depth UpperCamelCase__ = cls_token UpperCamelCase__ = attention_drop_rate UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps def UpperCAmelCase_ (self ): UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None if self.use_labels: # create a random int32 tensor of given shape UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase__ = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ (self ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = TFCvtModel(config=_lowerCamelCase ) UpperCamelCase__ = model(_lowerCamelCase , training=_lowerCamelCase ) UpperCamelCase__ = (self.image_size, self.image_size) UpperCamelCase__ , UpperCamelCase__ = image_size[0], image_size[1] for i in range(len(self.depth ) ): UpperCamelCase__ = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) UpperCamelCase__ = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFCvtForImageClassification(_lowerCamelCase ) UpperCamelCase__ = model(_lowerCamelCase , labels=_lowerCamelCase , training=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = config_and_inputs UpperCamelCase__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class __A( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () SCREAMING_SNAKE_CASE__ = ( {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification} if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = TFCvtModelTester(self ) UpperCamelCase__ = TFCvtConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason="""Cvt does not output attentions""" ) def UpperCAmelCase_ (self ): pass @unittest.skip(reason="""Cvt does not use inputs_embeds""" ) def UpperCAmelCase_ (self ): pass @unittest.skip(reason="""Cvt does not support input and output embeddings""" ) def UpperCAmelCase_ (self ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) def UpperCAmelCase_ (self ): super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) @slow def UpperCAmelCase_ (self ): super().test_keras_fit() @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8""" ) def UpperCAmelCase_ (self ): UpperCamelCase__ = tf.keras.mixed_precision.Policy("""mixed_float16""" ) tf.keras.mixed_precision.set_global_policy(_lowerCamelCase ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("""float32""" ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(_lowerCamelCase ) UpperCamelCase__ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def UpperCAmelCase_ (self ): def check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = model_class(_lowerCamelCase ) UpperCamelCase__ = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) UpperCamelCase__ = outputs.hidden_states UpperCamelCase__ = len(self.model_tester.depth ) self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase__ = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @slow def UpperCAmelCase_ (self ): for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = TFCvtModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class __A( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase_ (self ): return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=_lowerCamelCase , return_tensors="""tf""" ) # forward pass UpperCamelCase__ = model(**_lowerCamelCase ) # verify the logits UpperCamelCase__ = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) UpperCamelCase__ = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , _lowerCamelCase , atol=1E-4 ) )
244
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast 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 lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = PegasusTokenizer A_ : int = PegasusTokenizerFast A_ : Optional[Any] = True A_ : Union[str, Any] = True def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def _SCREAMING_SNAKE_CASE ( self : int, **_lowerCamelCase : List[Any] ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = '''</s>''' __A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ), _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ), _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], '''<pad>''' ) self.assertEqual(vocab_keys[1], '''</s>''' ) self.assertEqual(vocab_keys[-1], '''v''' ) self.assertEqual(len(_lowerCamelCase ), 11_03 ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 11_03 ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __A = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' __A = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 __A = '''To ensure a smooth flow of bank resolutions.''' __A = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 1_50, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # fmt: off __A = {'''input_ids''': [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 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], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 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]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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='''google/bigbird-pegasus-large-arxiv''', revision='''ba85d0851d708441f91440d509690f1ab6353415''', ) @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = PegasusTokenizer A_ : Union[str, Any] = PegasusTokenizerFast A_ : Any = True A_ : str = True def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase, offset=0, mask_token_sent=_lowerCamelCase, mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], **_lowerCamelCase : Dict ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : List[str] ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 10_00, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) __A = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase, [1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1], )
266
0
'''simple docstring''' import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : int , UpperCamelCase__ : int , UpperCamelCase__ : str=None , UpperCamelCase__ : str=None , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : int="resnet50" , UpperCamelCase__ : Tuple=3 , UpperCamelCase__ : List[str]=3_2 , UpperCamelCase__ : int=3 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Tuple=True , ): """simple docstring""" UpperCamelCase = parent UpperCamelCase = out_indices if out_indices is not None else [4] UpperCamelCase = stage_names UpperCamelCase = out_features UpperCamelCase = backbone UpperCamelCase = batch_size UpperCamelCase = image_size UpperCamelCase = num_channels UpperCamelCase = use_pretrained_backbone UpperCamelCase = is_training def A ( self : Optional[int] ): """simple docstring""" UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase = self.get_config() return config, pixel_values def A ( self : Any ): """simple docstring""" return TimmBackboneConfig( image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , ) def A ( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[Any] ): """simple docstring""" UpperCamelCase = TimmBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase = model(_lowerCamelCase ) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 1_4, 1_4) , ) def A ( self : Dict ): """simple docstring""" UpperCamelCase = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase = config_and_inputs UpperCamelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch @require_timm class SCREAMING_SNAKE_CASE ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = (TimmBackbone,) if is_torch_available() else () _SCREAMING_SNAKE_CASE = {"feature-extraction": TimmBackbone} if is_torch_available() else {} _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def A ( self : Dict ): """simple docstring""" UpperCamelCase = TimmBackboneModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def A ( self : int ): """simple docstring""" self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def A ( self : str ): """simple docstring""" UpperCamelCase = 'resnet18' UpperCamelCase = 'microsoft/resnet-18' UpperCamelCase = AutoBackbone.from_pretrained(_lowerCamelCase , use_timm_backbone=_lowerCamelCase ) UpperCamelCase = AutoBackbone.from_pretrained(_lowerCamelCase ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices , (-1,) ) self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] ) UpperCamelCase = AutoBackbone.from_pretrained(_lowerCamelCase , use_timm_backbone=_lowerCamelCase , out_indices=[1, 2, 3] ) UpperCamelCase = AutoBackbone.from_pretrained(_lowerCamelCase , out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices , transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) @unittest.skip('TimmBackbone doesn\'t support feed forward chunking' ) def A ( self : Dict ): """simple docstring""" pass @unittest.skip('TimmBackbone doesn\'t have num_hidden_layers attribute' ) def A ( self : List[Any] ): """simple docstring""" pass @unittest.skip('TimmBackbone initialization is managed on the timm side' ) def A ( self : Optional[int] ): """simple docstring""" pass @unittest.skip('TimmBackbone models doesn\'t have inputs_embeds' ) def A ( self : int ): """simple docstring""" pass @unittest.skip('TimmBackbone models doesn\'t have inputs_embeds' ) def A ( self : str ): """simple docstring""" pass @unittest.skip('TimmBackbone model cannot be created without specifying a backbone checkpoint' ) def A ( self : Dict ): """simple docstring""" pass @unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' ) def A ( self : Optional[int] ): """simple docstring""" pass @unittest.skip('model weights aren\'t tied in TimmBackbone.' ) def A ( self : Any ): """simple docstring""" pass @unittest.skip('model weights aren\'t tied in TimmBackbone.' ) def A ( self : List[str] ): """simple docstring""" pass @unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' ) def A ( self : Optional[Any] ): """simple docstring""" pass @unittest.skip('Only checkpoints on timm can be loaded into TimmBackbone' ) def A ( self : Optional[Any] ): """simple docstring""" pass @unittest.skip('TimmBackbone doesn\'t have hidden size info in its configuration.' ) def A ( self : Dict ): """simple docstring""" pass @unittest.skip('TimmBackbone doesn\'t support output_attentions.' ) def A ( self : Dict ): """simple docstring""" pass @unittest.skip('Safetensors is not supported by timm.' ) def A ( self : Optional[Any] ): """simple docstring""" pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def A ( self : str ): """simple docstring""" pass def A ( self : Tuple ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_lowerCamelCase ) UpperCamelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase = [*signature.parameters.keys()] UpperCamelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def A ( self : int ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase = True UpperCamelCase = self.has_attentions # no need to test all models as different heads yield the same functionality UpperCamelCase = self.all_model_classes[0] UpperCamelCase = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) UpperCamelCase = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) UpperCamelCase = model(**_lowerCamelCase ) UpperCamelCase = outputs[0][-1] # Encoder-/Decoder-only models UpperCamelCase = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: UpperCamelCase = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def A ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase = model(**_lowerCamelCase ) self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) ) self.assertEqual(len(model.channels ) , len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None UpperCamelCase = copy.deepcopy(_lowerCamelCase ) UpperCamelCase = None UpperCamelCase = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase = model(**_lowerCamelCase ) self.assertEqual(len(result.feature_maps ) , 1 ) self.assertEqual(len(model.channels ) , 1 ) # Check backbone can be initialized with fresh weights UpperCamelCase = copy.deepcopy(_lowerCamelCase ) UpperCamelCase = False UpperCamelCase = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase = model(**_lowerCamelCase )
28
"""simple docstring""" import re def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return [char.split() for char in re.split(r'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" try: __A = split_input(__UpperCamelCase ) if upper: __A = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __A = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return to_simple_case(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" try: __A = to_simple_case(__UpperCamelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''_''' ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
266
0
"""simple docstring""" import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 __UpperCamelCase : Optional[Any] = 0B10_11_00_11_11_10_11_00_10_01_00_00_01_11_10_11_10_11_00_01_10_01_11_10 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 __UpperCamelCase : int = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Union[str, Any] ): lowerCAmelCase__ : Tuple = WATERMARK_BITS lowerCAmelCase__ : Dict = WatermarkEncoder() self.encoder.set_watermark('''bits''' ,self.watermark ) def __lowerCAmelCase ( self : Any ,lowercase_ : torch.FloatTensor ): # can't encode images that are smaller than 256 if images.shape[-1] < 2_5_6: return images lowerCAmelCase__ : Any = (2_5_5 * (images / 2 + 0.5)).cpu().permute(0 ,2 ,3 ,1 ).float().numpy() lowerCAmelCase__ : List[str] = [self.encoder.encode(_lowerCamelCase ,'''dwtDct''' ) for image in images] lowerCAmelCase__ : Any = torch.from_numpy(np.array(_lowerCamelCase ) ).permute(0 ,3 ,1 ,2 ) lowerCAmelCase__ : List[Any] = torch.clamp(2 * (images / 2_5_5 - 0.5) ,min=-1.0 ,max=1.0 ) return images
106
"""simple docstring""" from __future__ import annotations class snake_case : '''simple docstring''' def __init__( self : int, _lowerCamelCase : List[Any]=None ): '''simple docstring''' __A = data __A = None def __repr__( self : Union[str, Any] ): '''simple docstring''' __A = [] __A = self while temp: string_rep.append(f'{temp.data}' ) __A = temp.next return "->".join(_lowerCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not elements_list: raise Exception('''The Elements List is empty''' ) __A = __A = Node(elements_list[0] ) for i in range(1 , len(__UpperCamelCase ) ): __A = Node(elements_list[i] ) __A = current.next return head def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if head_node is not None and isinstance(__UpperCamelCase , __UpperCamelCase ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase ( ): """simple docstring""" from doctest import testmod testmod() __A = make_linked_list([1_4, 5_2, 1_4, 1_2, 4_3] ) print('''Linked List:''' ) print(__UpperCamelCase ) print('''Elements in Reverse:''' ) print_reverse(__UpperCamelCase ) if __name__ == "__main__": main()
266
0
import json import os import re import unicodedata from json.encoder import INFINITY from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import regex from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging from ...utils.generic import _is_jax, _is_numpy a_ = logging.get_logger(__name__) a_ = { 'artists_file': 'artists.json', 'lyrics_file': 'lyrics.json', 'genres_file': 'genres.json', } a_ = { 'artists_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json', }, 'genres_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json', }, 'lyrics_file': { 'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json', }, } a_ = { 'jukebox': 512, } class _lowercase ( _lowerCAmelCase ): lowercase = VOCAB_FILES_NAMES lowercase = PRETRAINED_VOCAB_FILES_MAP lowercase = PRETRAINED_LYRIC_TOKENS_SIZES lowercase = ["input_ids", "attention_mask"] def __init__( self : Optional[int] , snake_case : Optional[int] , snake_case : str , snake_case : List[str] , snake_case : int=["v3", "v2", "v2"] , snake_case : Optional[int]=5_1_2 , snake_case : Tuple=5 , snake_case : Tuple="<|endoftext|>" , **snake_case : Union[str, Any] , ) -> Any: """simple docstring""" UpperCamelCase_ : str = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else unk_token super().__init__( unk_token=_lowerCamelCase , n_genres=_lowerCamelCase , version=_lowerCamelCase , max_n_lyric_tokens=_lowerCamelCase , **_lowerCamelCase , ) UpperCamelCase_ : Dict = version UpperCamelCase_ : Optional[Any] = max_n_lyric_tokens UpperCamelCase_ : Tuple = n_genres with open(_lowerCamelCase , encoding='utf-8' ) as vocab_handle: UpperCamelCase_ : str = json.load(_lowerCamelCase ) with open(_lowerCamelCase , encoding='utf-8' ) as vocab_handle: UpperCamelCase_ : Union[str, Any] = json.load(_lowerCamelCase ) with open(_lowerCamelCase , encoding='utf-8' ) as vocab_handle: UpperCamelCase_ : Tuple = json.load(_lowerCamelCase ) UpperCamelCase_ : Dict = R'[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+' # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters. if len(self.lyrics_encoder ) == 7_9: UpperCamelCase_ : List[Any] = oov.replace(R'\-\'' , R'\-+\'' ) UpperCamelCase_ : str = regex.compile(_lowerCamelCase ) UpperCamelCase_ : Union[str, Any] = {v: k for k, v in self.artists_encoder.items()} UpperCamelCase_ : Dict = {v: k for k, v in self.genres_encoder.items()} UpperCamelCase_ : Union[str, Any] = {v: k for k, v in self.lyrics_encoder.items()} @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> Any: """simple docstring""" return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> List[Any]: """simple docstring""" return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder ) def SCREAMING_SNAKE_CASE__ ( self : Any , snake_case : Optional[int] , snake_case : Optional[int] , snake_case : Optional[int] ) -> Tuple: """simple docstring""" UpperCamelCase_ : Optional[Any] = [self.artists_encoder.get(_lowerCamelCase , 0 ) for artist in list_artists] for genres in range(len(_lowerCamelCase ) ): UpperCamelCase_ : List[Any] = [self.genres_encoder.get(_lowerCamelCase , 0 ) for genre in list_genres[genres]] UpperCamelCase_ : Union[str, Any] = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] )) UpperCamelCase_ : Tuple = [[self.lyrics_encoder.get(_lowerCamelCase , 0 ) for character in list_lyrics[0]], [], []] return artists_id, list_genres, lyric_ids def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , snake_case : Any ) -> Tuple: """simple docstring""" return list(_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case : List[str] , snake_case : Any , snake_case : Optional[int] , **snake_case : Union[str, Any] ) -> str: """simple docstring""" UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ : Tuple = self.prepare_for_tokenization(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) UpperCamelCase_ : Optional[int] = self._tokenize(_lowerCamelCase ) return artist, genre, lyrics def SCREAMING_SNAKE_CASE__ ( self : str , snake_case : str , snake_case : str , snake_case : str , snake_case : bool = False ) -> Dict: """simple docstring""" for idx in range(len(self.version ) ): if self.version[idx] == "v3": UpperCamelCase_ : Optional[int] = artists[idx].lower() UpperCamelCase_ : Tuple = [genres[idx].lower()] else: UpperCamelCase_ : str = self._normalize(artists[idx] ) + '.v2' UpperCamelCase_ : Any = [ self._normalize(_lowerCamelCase ) + '.v2' for genre in genres[idx].split('_' ) ] # split is for the full dictionary with combined genres if self.version[0] == "v2": UpperCamelCase_ : Tuple = regex.compile(R'[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+' ) UpperCamelCase_ : List[Any] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n' UpperCamelCase_ : Union[str, Any] = {vocab[index]: index + 1 for index in range(len(_lowerCamelCase ) )} UpperCamelCase_ : Any = 0 UpperCamelCase_ : List[str] = len(_lowerCamelCase ) + 1 UpperCamelCase_ : Union[str, Any] = self.vocab UpperCamelCase_ : str = {v: k for k, v in self.vocab.items()} UpperCamelCase_ : Tuple = '' else: UpperCamelCase_ : Optional[Any] = regex.compile(R'[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+' ) UpperCamelCase_ : Optional[int] = self._run_strip_accents(_lowerCamelCase ) UpperCamelCase_ : List[str] = lyrics.replace('\\' , '\n' ) UpperCamelCase_ : str = self.out_of_vocab.sub('' , _lowerCamelCase ), [], [] return artists, genres, lyrics def SCREAMING_SNAKE_CASE__ ( self : str , snake_case : Optional[Any] ) -> int: """simple docstring""" UpperCamelCase_ : Union[str, Any] = unicodedata.normalize('NFD' , _lowerCamelCase ) UpperCamelCase_ : List[str] = [] for char in text: UpperCamelCase_ : List[Any] = unicodedata.category(_lowerCamelCase ) if cat == "Mn": continue output.append(_lowerCamelCase ) return "".join(_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case : str ) -> int: """simple docstring""" UpperCamelCase_ : Dict = ( [chr(_lowerCamelCase ) for i in range(ord('a' ) , ord('z' ) + 1 )] + [chr(_lowerCamelCase ) for i in range(ord('A' ) , ord('Z' ) + 1 )] + [chr(_lowerCamelCase ) for i in range(ord('0' ) , ord('9' ) + 1 )] + ['.'] ) UpperCamelCase_ : Dict = frozenset(_lowerCamelCase ) UpperCamelCase_ : Dict = re.compile(R'_+' ) UpperCamelCase_ : Dict = ''.join([c if c in accepted else '_' for c in text.lower()] ) UpperCamelCase_ : List[Any] = pattern.sub('_' , _lowerCamelCase ).strip('_' ) return text def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case : List[str] ) -> Union[str, Any]: """simple docstring""" return " ".join(_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self : List[str] , snake_case : Optional[int] , snake_case : Optional[Union[str, TensorType]] = None , snake_case : bool = False ) -> Any: """simple docstring""" if not isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCamelCase_ : str = TensorType(_lowerCamelCase ) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( 'Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.' ) import tensorflow as tf UpperCamelCase_ : Union[str, Any] = tf.constant UpperCamelCase_ : List[Any] = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError('Unable to convert output to PyTorch tensors format, PyTorch is not installed.' ) import torch UpperCamelCase_ : Tuple = torch.tensor UpperCamelCase_ : Optional[int] = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError('Unable to convert output to JAX tensors format, JAX is not installed.' ) import jax.numpy as jnp # noqa: F811 UpperCamelCase_ : Union[str, Any] = jnp.array UpperCamelCase_ : Optional[Any] = _is_jax else: UpperCamelCase_ : Dict = np.asarray UpperCamelCase_ : int = _is_numpy # Do the tensor conversion in batch try: if prepend_batch_axis: UpperCamelCase_ : str = [inputs] if not is_tensor(_lowerCamelCase ): UpperCamelCase_ : List[Any] = as_tensor(_lowerCamelCase ) except: # noqa E722 raise ValueError( 'Unable to create tensor, you should probably activate truncation and/or padding ' 'with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.' ) return inputs def __call__( self : int , snake_case : List[Any] , snake_case : Optional[Any] , snake_case : str="" , snake_case : Optional[Any]="pt" ) -> Any: """simple docstring""" UpperCamelCase_ : Optional[int] = [0, 0, 0] UpperCamelCase_ : int = [artist] * len(self.version ) UpperCamelCase_ : Dict = [genres] * len(self.version ) UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ : Dict = self.tokenize(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ : Any = self._convert_token_to_id(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) UpperCamelCase_ : int = [-INFINITY] * len(full_tokens[-1] ) UpperCamelCase_ : int = [ self.convert_to_tensors( [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=_lowerCamelCase ) for i in range(len(self.version ) ) ] return BatchEncoding({'input_ids': input_ids, 'attention_masks': attention_masks} ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , snake_case : str , snake_case : Optional[str] = None ) -> List[Any]: """simple docstring""" if not os.path.isdir(_lowerCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return UpperCamelCase_ : Any = os.path.join( _lowerCamelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['artists_file'] ) with open(_lowerCamelCase , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.artists_encoder , ensure_ascii=_lowerCamelCase ) ) UpperCamelCase_ : Dict = os.path.join( _lowerCamelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['genres_file'] ) with open(_lowerCamelCase , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.genres_encoder , ensure_ascii=_lowerCamelCase ) ) UpperCamelCase_ : Optional[Any] = os.path.join( _lowerCamelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['lyrics_file'] ) with open(_lowerCamelCase , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.lyrics_encoder , ensure_ascii=_lowerCamelCase ) ) return (artists_file, genres_file, lyrics_file) def SCREAMING_SNAKE_CASE__ ( self : Dict , snake_case : List[Any] , snake_case : Optional[int] , snake_case : Tuple ) -> int: """simple docstring""" UpperCamelCase_ : List[str] = self.artists_decoder.get(_lowerCamelCase ) UpperCamelCase_ : int = [self.genres_decoder.get(_lowerCamelCase ) for genre in genres_index] UpperCamelCase_ : str = [self.lyrics_decoder.get(_lowerCamelCase ) for character in lyric_index] return artist, genres, lyrics
175
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : int = ["input_features", "attention_mask"] def __init__( self : Optional[Any], _lowerCamelCase : Union[str, Any]=80, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Any=80, _lowerCamelCase : List[str]=0.0, _lowerCamelCase : int=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Optional[int]=True, **_lowerCamelCase : List[str], ): '''simple docstring''' super().__init__(feature_size=_lowerCamelCase, sampling_rate=_lowerCamelCase, padding_value=_lowerCamelCase, **_lowerCamelCase ) __A = num_mel_bins __A = do_ceptral_normalize __A = normalize_means __A = normalize_vars __A = True def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : np.ndarray, ): '''simple docstring''' __A = waveform * (2**15) # Kaldi compliance: 16-bit signed integers __A = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ) __A = ta_kaldi.fbank(_lowerCamelCase, num_mel_bins=self.num_mel_bins, sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray, _lowerCamelCase : int, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : float = 0.0, ): '''simple docstring''' # make sure we normalize float32 arrays if normalize_means: __A = x[:input_length].mean(axis=0 ) __A = np.subtract(_lowerCamelCase, _lowerCamelCase ) if normalize_vars: __A = x[:input_length].std(axis=0 ) __A = np.divide(_lowerCamelCase, _lowerCamelCase ) if input_length < x.shape[0]: __A = padding_value # make sure array is in float32 __A = x.astype(np.floataa ) return x def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[np.ndarray], _lowerCamelCase : Optional[np.ndarray] = None ): '''simple docstring''' __A = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_lowerCamelCase, _lowerCamelCase, self.normalize_means, self.normalize_vars, self.padding_value ) for x, n in zip(_lowerCamelCase, _lowerCamelCase ) ] def __call__( self : Optional[Any], _lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], _lowerCamelCase : Union[bool, str, PaddingStrategy] = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : bool = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[Union[str, TensorType]] = None, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[bool] = None, **_lowerCamelCase : Optional[Any], ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __A = isinstance(_lowerCamelCase, np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __A = is_batched_numpy or ( isinstance(_lowerCamelCase, (list, tuple) ) and (isinstance(raw_speech[0], (np.ndarray, tuple, list) )) ) if is_batched: __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_lowerCamelCase, np.ndarray ): __A = np.asarray(_lowerCamelCase, dtype=np.floataa ) elif isinstance(_lowerCamelCase, np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __A = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __A = [raw_speech] # extract fbank features __A = [self._extract_fbank_features(_lowerCamelCase ) for waveform in raw_speech] # convert into correct format for padding __A = BatchFeature({'''input_features''': features} ) __A = self.pad( _lowerCamelCase, padding=_lowerCamelCase, max_length=_lowerCamelCase, truncation=_lowerCamelCase, pad_to_multiple_of=_lowerCamelCase, return_attention_mask=_lowerCamelCase, **_lowerCamelCase, ) # make sure list is in array format __A = padded_inputs.get('''input_features''' ) if isinstance(input_features[0], _lowerCamelCase ): __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for feature in input_features] __A = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __A = [np.asarray(_lowerCamelCase, dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: __A = ( np.array(_lowerCamelCase, dtype=np.intaa ) if self._get_padding_strategies(_lowerCamelCase, max_length=_lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) __A = self.normalize( padded_inputs['''input_features'''], attention_mask=_lowerCamelCase ) if return_tensors is not None: __A = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs
266
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer __lowercase : List[str] = logging.get_logger(__name__) __lowercase : List[str] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} __lowercase : List[Any] = { '''vocab_file''': { '''google/realm-cc-news-pretrained-embedder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt''' ), '''google/realm-cc-news-pretrained-encoder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt''' ), '''google/realm-cc-news-pretrained-scorer''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt''' ), '''google/realm-cc-news-pretrained-openqa''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt''' ), '''google/realm-orqa-nq-openqa''': '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt''', '''google/realm-orqa-nq-reader''': '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt''', '''google/realm-orqa-wq-openqa''': '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt''', '''google/realm-orqa-wq-reader''': '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt''', }, '''tokenizer_file''': { '''google/realm-cc-news-pretrained-embedder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont''' ), '''google/realm-cc-news-pretrained-encoder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json''' ), '''google/realm-cc-news-pretrained-scorer''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json''' ), '''google/realm-cc-news-pretrained-openqa''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json''' ), '''google/realm-orqa-nq-openqa''': ( '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json''' ), '''google/realm-orqa-nq-reader''': ( '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json''' ), '''google/realm-orqa-wq-openqa''': ( '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json''' ), '''google/realm-orqa-wq-reader''': ( '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json''' ), }, } __lowercase : List[str] = { '''google/realm-cc-news-pretrained-embedder''': 512, '''google/realm-cc-news-pretrained-encoder''': 512, '''google/realm-cc-news-pretrained-scorer''': 512, '''google/realm-cc-news-pretrained-openqa''': 512, '''google/realm-orqa-nq-openqa''': 512, '''google/realm-orqa-nq-reader''': 512, '''google/realm-orqa-wq-openqa''': 512, '''google/realm-orqa-wq-reader''': 512, } __lowercase : Dict = { '''google/realm-cc-news-pretrained-embedder''': {'''do_lower_case''': True}, '''google/realm-cc-news-pretrained-encoder''': {'''do_lower_case''': True}, '''google/realm-cc-news-pretrained-scorer''': {'''do_lower_case''': True}, '''google/realm-cc-news-pretrained-openqa''': {'''do_lower_case''': True}, '''google/realm-orqa-nq-openqa''': {'''do_lower_case''': True}, '''google/realm-orqa-nq-reader''': {'''do_lower_case''': True}, '''google/realm-orqa-wq-openqa''': {'''do_lower_case''': True}, '''google/realm-orqa-wq-reader''': {'''do_lower_case''': True}, } class __lowercase ( _lowerCAmelCase ): lowerCamelCase : Optional[int] = VOCAB_FILES_NAMES lowerCamelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : Tuple = PRETRAINED_INIT_CONFIGURATION lowerCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : str = RealmTokenizer def __init__(self , A=None , A=None , A=True , A="[UNK]" , A="[SEP]" , A="[PAD]" , A="[CLS]" , A="[MASK]" , A=True , A=None , **A , ): super().__init__( _lowerCamelCase , tokenizer_file=_lowerCamelCase , do_lower_case=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , tokenize_chinese_chars=_lowerCamelCase , strip_accents=_lowerCamelCase , **_lowerCamelCase , ) lowerCamelCase_ : Any = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , _lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _lowerCamelCase ) != tokenize_chinese_chars ): lowerCamelCase_ : List[Any] = getattr(_lowerCamelCase , normalizer_state.pop('''type''' ) ) lowerCamelCase_ : Dict = do_lower_case lowerCamelCase_ : Tuple = strip_accents lowerCamelCase_ : int = tokenize_chinese_chars lowerCamelCase_ : Union[str, Any] = normalizer_class(**_lowerCamelCase ) lowerCamelCase_ : Dict = do_lower_case def UpperCAmelCase__ (self , A , **A ): lowerCamelCase_ : Union[str, Any] = PaddingStrategy.MAX_LENGTH lowerCamelCase_ : Union[str, Any] = text lowerCamelCase_ : Union[str, Any] = kwargs.pop('''text_pair''' , _lowerCamelCase ) lowerCamelCase_ : Optional[Any] = kwargs.pop('''return_tensors''' , _lowerCamelCase ) lowerCamelCase_ : Any = { '''input_ids''': [], '''attention_mask''': [], '''token_type_ids''': [], } for idx, candidate_text in enumerate(_lowerCamelCase ): if batch_text_pair is not None: lowerCamelCase_ : Dict = batch_text_pair[idx] else: lowerCamelCase_ : Optional[Any] = None lowerCamelCase_ : str = super().__call__(_lowerCamelCase , _lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) lowerCamelCase_ : Optional[Any] = encoded_candidates.get('''input_ids''' ) lowerCamelCase_ : List[str] = encoded_candidates.get('''attention_mask''' ) lowerCamelCase_ : Optional[int] = encoded_candidates.get('''token_type_ids''' ) if encoded_input_ids is not None: output_data["input_ids"].append(_lowerCamelCase ) if encoded_attention_mask is not None: output_data["attention_mask"].append(_lowerCamelCase ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(_lowerCamelCase ) lowerCamelCase_ : Union[str, Any] = {key: item for key, item in output_data.items() if len(_lowerCamelCase ) != 0} return BatchEncoding(_lowerCamelCase , tensor_type=_lowerCamelCase ) def UpperCAmelCase__ (self , A , A=None ): lowerCamelCase_ : Any = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase__ (self , A , A = None ): lowerCamelCase_ : Tuple = [self.sep_token_id] lowerCamelCase_ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase__ (self , A , A = None ): lowerCamelCase_ : int = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
318
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : Optional[Any], _lowerCamelCase : Union[str, Any]=13, _lowerCamelCase : Any=3, _lowerCamelCase : Optional[int]=2_24, _lowerCamelCase : str=30, _lowerCamelCase : Dict=4_00, _lowerCamelCase : Union[str, Any]=True, _lowerCamelCase : Any=None, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Any=[0.5, 0.5, 0.5], _lowerCamelCase : List[str]=[0.5, 0.5, 0.5], ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_normalize __A = image_mean __A = image_std def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = ViTImageProcessor if is_vision_available() else None def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = EfficientFormerImageProcessorTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' return self.image_proc_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase, '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''size''' ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, np.ndarray ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_proc_tester, equal_resolution=_lowerCamelCase, torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, torch.Tensor ) # Test not batched input __A = image_processor(image_inputs[0], return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), ) # Test batched __A = image_processor(_lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ), )
266
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 UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = [] if isinstance(__UpperCamelCase , __UpperCamelCase ): for v in tree.values(): shapes.extend(_fetch_dims(__UpperCamelCase ) ) elif isinstance(__UpperCamelCase , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(__UpperCamelCase ) ) elif isinstance(__UpperCamelCase , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError('''Not supported''' ) return shapes @torch.jit.ignore def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = [] for d in reversed(__UpperCamelCase ): idx.append(flat_idx % d ) lowercase = flat_idx // d return tuple(reversed(__UpperCamelCase ) ) @torch.jit.ignore def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = None , ): '''simple docstring''' def reduce_edge_list(lowerCAmelCase__ ) -> None: lowercase = True for i in range(len(__UpperCamelCase ) ): lowercase = -1 * (i + 1) l[reversed_idx] &= tally lowercase = l[reversed_idx] if start_edges is None: lowercase = [s == 0 for s in start] reduce_edge_list(__UpperCamelCase ) if end_edges is None: lowercase = [e == (d - 1) for e, d in zip(__UpperCamelCase , __UpperCamelCase )] reduce_edge_list(__UpperCamelCase ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(__UpperCamelCase ) == 0: return [()] elif len(__UpperCamelCase ) == 1: return [(slice(start[0] , end[0] + 1 ),)] lowercase = [] lowercase = [] # Dimensions common to start and end can be selected directly for s, e in zip(__UpperCamelCase , __UpperCamelCase ): if s == e: path_list.append(slice(__UpperCamelCase , s + 1 ) ) else: break lowercase = tuple(__UpperCamelCase ) lowercase = len(__UpperCamelCase ) # start == end, and we're done if divergence_idx == len(__UpperCamelCase ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowercase = start[divergence_idx] return tuple( path + (slice(__UpperCamelCase , 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 lowercase = end[divergence_idx] return tuple( path + (slice(__UpperCamelCase , 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() ) lowercase = 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 UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = t.shape[:no_batch_dims] lowercase = list(_flat_idx_to_idx(__UpperCamelCase , __UpperCamelCase ) ) # _get_minimal_slice_set is inclusive lowercase = list(_flat_idx_to_idx(flat_end - 1 , __UpperCamelCase ) ) # Get an ordered list of slices to perform lowercase = _get_minimal_slice_set( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , ) lowercase = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = False , ): '''simple docstring''' if not (len(__UpperCamelCase ) > 0): raise ValueError('''Must provide at least one input''' ) lowercase = [shape[:no_batch_dims] for shape in _fetch_dims(__UpperCamelCase )] lowercase = tuple([max(__UpperCamelCase ) for s in zip(*__UpperCamelCase )] ) def _prep_inputs(lowerCAmelCase__ ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: lowercase = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) lowercase = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: lowercase = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t lowercase = tensor_tree_map(_prep_inputs , __UpperCamelCase ) lowercase = None if _out is not None: lowercase = tensor_tree_map(lambda lowerCAmelCase__ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) lowercase = 1 for d in orig_batch_dims: flat_batch_dim *= d lowercase = 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 lowercase = 0 lowercase = prepped_outputs for _ in range(__UpperCamelCase ): # Chunk the input if not low_mem: lowercase = _select_chunk else: lowercase = partial( _chunk_slice , flat_start=__UpperCamelCase , flat_end=min(__UpperCamelCase , i + chunk_size ) , no_batch_dims=len(__UpperCamelCase ) , ) lowercase = tensor_tree_map(__UpperCamelCase , __UpperCamelCase ) # Run the layer on the chunk lowercase = layer(**__UpperCamelCase ) # Allocate space for the output if out is None: lowercase = tensor_tree_map(lambda lowerCAmelCase__ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , __UpperCamelCase ) # Put the chunk in its pre-allocated space if isinstance(__UpperCamelCase , __UpperCamelCase ): def assign(lowerCAmelCase__ , lowerCAmelCase__ ) -> None: for k, v in da.items(): if isinstance(__UpperCamelCase , __UpperCamelCase ): assign(__UpperCamelCase , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: lowercase = da[k] assign(__UpperCamelCase , __UpperCamelCase ) elif isinstance(__UpperCamelCase , __UpperCamelCase ): for xa, xa in zip(__UpperCamelCase , __UpperCamelCase ): if _add_into_out: xa[i : i + chunk_size] += xa else: lowercase = xa elif isinstance(__UpperCamelCase , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: lowercase = output_chunk else: raise ValueError('''Not supported''' ) i += chunk_size lowercase = tensor_tree_map(lambda lowerCAmelCase__ : t.view(orig_batch_dims + t.shape[1:] ) , __UpperCamelCase ) return out class lowercase : def __init__( self ,A__ = 5_1_2 ,): lowercase = max_chunk_size lowercase = None lowercase = None def A__ ( self ,A__ ,A__ ,A__): logging.info('''Tuning chunk size...''') if min_chunk_size >= self.max_chunk_size: return min_chunk_size lowercase = [2**l for l in range(int(math.log(self.max_chunk_size ,2)) + 1)] lowercase = [c for c in candidates if c > min_chunk_size] lowercase = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(A__) -> bool: try: with torch.no_grad(): fn(*_lowerCamelCase ,chunk_size=_lowerCamelCase) return True except RuntimeError: return False lowercase = 0 lowercase = len(_lowerCamelCase) - 1 while i > min_viable_chunk_size_index: lowercase = test_chunk_size(candidates[i]) if not viable: lowercase = (min_viable_chunk_size_index + i) // 2 else: lowercase = i lowercase = (i + len(_lowerCamelCase) - 1) // 2 return candidates[min_viable_chunk_size_index] def A__ ( self ,A__ ,A__): lowercase = True for aa, aa in zip(_lowerCamelCase ,_lowerCamelCase): assert type(_lowerCamelCase) == type(_lowerCamelCase) if isinstance(_lowerCamelCase ,(list, tuple)): consistent &= self._compare_arg_caches(_lowerCamelCase ,_lowerCamelCase) elif isinstance(_lowerCamelCase ,_lowerCamelCase): lowercase = [v for _, v in sorted(aa.items() ,key=lambda A__: x[0])] lowercase = [v for _, v in sorted(aa.items() ,key=lambda A__: x[0])] consistent &= self._compare_arg_caches(_lowerCamelCase ,_lowerCamelCase) else: consistent &= aa == aa return consistent def A__ ( self ,A__ ,A__ ,A__ ,): lowercase = True lowercase = tree_map(lambda A__: a.shape if isinstance(_lowerCamelCase ,torch.Tensor) else a ,_lowerCamelCase ,_lowerCamelCase) 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(_lowerCamelCase) lowercase = self._compare_arg_caches(self.cached_arg_data ,_lowerCamelCase) else: # Otherwise, we can reuse the precomputed value lowercase = False if not consistent: lowercase = self._determine_favorable_chunk_size( _lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,) lowercase = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
101
"""simple docstring""" import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' def __init__( self : Optional[int], *_lowerCamelCase : Union[str, Any], **_lowerCamelCase : Dict ): '''simple docstring''' warnings.warn( '''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use SegformerImageProcessor instead.''', _lowerCamelCase, ) super().__init__(*_lowerCamelCase, **_lowerCamelCase )
266
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ : List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ : int = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class a ( _lowerCAmelCase ): """simple docstring""" UpperCAmelCase = "realm" def __init__( self: Optional[int] , UpperCamelCase: List[Any]=3_05_22 , UpperCamelCase: Optional[int]=7_68 , UpperCamelCase: List[Any]=1_28 , UpperCamelCase: str=12 , UpperCamelCase: int=12 , UpperCamelCase: int=8 , UpperCamelCase: Any=30_72 , UpperCamelCase: Any="gelu_new" , UpperCamelCase: List[str]=0.1 , UpperCamelCase: Optional[int]=0.1 , UpperCamelCase: int=5_12 , UpperCamelCase: str=2 , UpperCamelCase: int=0.02 , UpperCamelCase: Optional[Any]=1e-1_2 , UpperCamelCase: str=2_56 , UpperCamelCase: Dict=10 , UpperCamelCase: List[Any]=1e-3 , UpperCamelCase: Optional[Any]=5 , UpperCamelCase: str=3_20 , UpperCamelCase: int=13_35_37_18 , UpperCamelCase: Any=50_00 , UpperCamelCase: Dict=1 , UpperCamelCase: Union[str, Any]=0 , UpperCamelCase: Any=2 , **UpperCamelCase: List[Any] , ): """simple docstring""" super().__init__(pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase ) # Common config A__ = vocab_size A__ = max_position_embeddings A__ = hidden_size A__ = retriever_proj_size A__ = num_hidden_layers A__ = num_attention_heads A__ = num_candidates A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = initializer_range A__ = type_vocab_size A__ = layer_norm_eps # Reader config A__ = span_hidden_size A__ = max_span_width A__ = reader_layer_norm_eps A__ = reader_beam_size A__ = reader_seq_len # Retrieval config A__ = num_block_records A__ = searcher_beam_size
335
"""simple docstring""" 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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : List[Any]=7, _lowerCamelCase : int=3, _lowerCamelCase : Optional[Any]=18, _lowerCamelCase : Any=30, _lowerCamelCase : str=4_00, _lowerCamelCase : int=True, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str=True, ): '''simple docstring''' __A = size if size is not None else {'''height''': 18, '''width''': 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = apply_ocr def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[int] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = LayoutLMvaImageProcessingTester(self ) @property def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = 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 : Union[str, Any] ): '''simple docstring''' __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'''height''': 18, '''width''': 18} ) __A = 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 : Optional[Any] ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester, equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase, Image.Image ) # Test not batched input __A = 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 __A = 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 : Any ): '''simple docstring''' # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = 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 __A = 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 __A = 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 __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = 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 __A = 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 __A = 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 : List[str] ): '''simple docstring''' # with apply_OCR = True __A = LayoutLMvaImageProcessor() from datasets import load_dataset __A = load_dataset('''hf-internal-testing/fixtures_docvqa''', split='''test''' ) __A = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ), len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __A = [['''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 __A = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words, _lowerCamelCase ) self.assertListEqual(encoding.boxes, _lowerCamelCase ) # with apply_OCR = False __A = LayoutLMvaImageProcessor(apply_ocr=_lowerCamelCase ) __A = image_processing(_lowerCamelCase, return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape, (1, 3, 2_24, 2_24) )
266
0
'''simple docstring''' def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> Optional[int]: return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(__UpperCamelCase ) ) def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A ) -> Union[str, Any]: if index == len(__UpperCamelCase ): return True # Recursive Step for i in range(__UpperCamelCase ): if valid_coloring(graph[index] , __UpperCamelCase , __UpperCamelCase ): # Color current vertex _snake_case = i # Validate coloring if util_color(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , index + 1 ): return True # Backtrack _snake_case = -1 return False def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> List[Any]: _snake_case = [-1] * len(__UpperCamelCase ) if util_color(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , 0 ): return colored_vertices return []
42
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class snake_case ( ctypes.Structure ): '''simple docstring''' A_ : List[str] = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = False ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def lowerCAmelCase ( ): """simple docstring""" if os.name == "nt": __A = CursorInfo() __A = ctypes.windll.kernelaa.GetStdHandle(-1_1 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) __A = True ctypes.windll.kernelaa.SetConsoleCursorInfo(__UpperCamelCase , ctypes.byref(__UpperCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def lowerCAmelCase ( ): """simple docstring""" try: hide_cursor() yield finally: show_cursor()
266
0
"""simple docstring""" import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class __UpperCamelCase ( _lowerCAmelCase ): lowerCamelCase : Any =(UnCLIPScheduler,) def __a ( self , **lowerCAmelCase__ ) -> List[Any]: a : Optional[Any] = { "num_train_timesteps": 1000, "variance_type": "fixed_small_log", "clip_sample": True, "clip_sample_range": 1.0, "prediction_type": "epsilon", } config.update(**_lowerCamelCase ) return config def __a ( self ) -> Any: for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=_lowerCamelCase ) def __a ( self ) -> Dict: for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=_lowerCamelCase ) def __a ( self ) -> Optional[int]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=_lowerCamelCase ) def __a ( self ) -> Union[str, Any]: for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=_lowerCamelCase ) def __a ( self ) -> Tuple: for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=_lowerCamelCase ) def __a ( self ) -> Optional[Any]: for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=_lowerCamelCase , prev_timestep=_lowerCamelCase ) def __a ( self ) -> Optional[Any]: a : int = self.scheduler_classes[0] a : Union[str, Any] = self.get_scheduler_config(variance_type="fixed_small_log" ) a : int = scheduler_class(**_lowerCamelCase ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0_000E-10 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_549_625 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.9_994_987 ) ) < 1E-5 def __a ( self ) -> Optional[int]: a : Union[str, Any] = self.scheduler_classes[0] a : Dict = self.get_scheduler_config(variance_type="learned_range" ) a : Any = scheduler_class(**_lowerCamelCase ) a : int = 0.5 assert scheduler._get_variance(1 , predicted_variance=_lowerCamelCase ) - -10.1_712_790 < 1E-5 assert scheduler._get_variance(487 , predicted_variance=_lowerCamelCase ) - -5.7_998_052 < 1E-5 assert scheduler._get_variance(999 , predicted_variance=_lowerCamelCase ) - -0.0_010_011 < 1E-5 def __a ( self ) -> Tuple: a : Optional[int] = self.scheduler_classes[0] a : str = self.get_scheduler_config() a : Union[str, Any] = scheduler_class(**_lowerCamelCase ) a : List[Any] = scheduler.timesteps a : Any = self.dummy_model() a : Tuple = self.dummy_sample_deter a : int = torch.manual_seed(0 ) for i, t in enumerate(_lowerCamelCase ): # 1. predict noise residual a : Optional[int] = model(_lowerCamelCase , _lowerCamelCase ) # 2. predict previous mean of sample x_t-1 a : Dict = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase ).prev_sample a : List[Any] = pred_prev_sample a : Optional[int] = torch.sum(torch.abs(_lowerCamelCase ) ) a : Union[str, Any] = torch.mean(torch.abs(_lowerCamelCase ) ) assert abs(result_sum.item() - 252.268_2495 ) < 1E-2 assert abs(result_mean.item() - 0.3_284_743 ) < 1E-3 def __a ( self ) -> Optional[int]: a : str = self.scheduler_classes[0] a : Optional[int] = self.get_scheduler_config() a : Tuple = scheduler_class(**_lowerCamelCase ) scheduler.set_timesteps(25 ) a : Any = scheduler.timesteps a : int = self.dummy_model() a : str = self.dummy_sample_deter a : str = torch.manual_seed(0 ) for i, t in enumerate(_lowerCamelCase ): # 1. predict noise residual a : int = model(_lowerCamelCase , _lowerCamelCase ) if i + 1 == timesteps.shape[0]: a : Optional[int] = None else: a : Dict = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 a : Optional[int] = scheduler.step( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , prev_timestep=_lowerCamelCase , generator=_lowerCamelCase ).prev_sample a : Any = pred_prev_sample a : Union[str, Any] = torch.sum(torch.abs(_lowerCamelCase ) ) a : Any = torch.mean(torch.abs(_lowerCamelCase ) ) assert abs(result_sum.item() - 258.204_4983 ) < 1E-2 assert abs(result_mean.item() - 0.3_362_038 ) < 1E-3 def __a ( self ) -> Optional[int]: pass def __a ( self ) -> Optional[Any]: pass
105
"""simple docstring""" import argparse import struct import unittest class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : bytes ): '''simple docstring''' __A = data # Initialize hash values __A = [ 0X6a_09e_667, 0Xbb_67a_e85, 0X3c_6ef_372, 0Xa5_4ff_53a, 0X51_0e5_27f, 0X9b_056_88c, 0X1f_83d_9ab, 0X5b_e0c_d19, ] # Initialize round constants __A = [ 0X42_8a2_f98, 0X71_374_491, 0Xb5_c0f_bcf, 0Xe9_b5d_ba5, 0X39_56c_25b, 0X59_f11_1f1, 0X92_3f8_2a4, 0Xab_1c5_ed5, 0Xd8_07a_a98, 0X12_835_b01, 0X24_318_5be, 0X55_0c7_dc3, 0X72_be5_d74, 0X80_deb_1fe, 0X9b_dc0_6a7, 0Xc1_9bf_174, 0Xe4_9b6_9c1, 0Xef_be4_786, 0X0f_c19_dc6, 0X24_0ca_1cc, 0X2d_e92_c6f, 0X4a_748_4aa, 0X5c_b0a_9dc, 0X76_f98_8da, 0X98_3e5_152, 0Xa8_31c_66d, 0Xb0_032_7c8, 0Xbf_597_fc7, 0Xc6_e00_bf3, 0Xd5_a79_147, 0X06_ca6_351, 0X14_292_967, 0X27_b70_a85, 0X2e_1b2_138, 0X4d_2c6_dfc, 0X53_380_d13, 0X65_0a7_354, 0X76_6a0_abb, 0X81_c2c_92e, 0X92_722_c85, 0Xa2_bfe_8a1, 0Xa8_1a6_64b, 0Xc2_4b8_b70, 0Xc7_6c5_1a3, 0Xd1_92e_819, 0Xd6_990_624, 0Xf4_0e3_585, 0X10_6aa_070, 0X19_a4c_116, 0X1e_376_c08, 0X27_487_74c, 0X34_b0b_cb5, 0X39_1c0_cb3, 0X4e_d8a_a4a, 0X5b_9cc_a4f, 0X68_2e6_ff3, 0X74_8f8_2ee, 0X78_a56_36f, 0X84_c87_814, 0X8c_c70_208, 0X90_bef_ffa, 0Xa4_506_ceb, 0Xbe_f9a_3f7, 0Xc6_717_8f2, ] __A = self.preprocessing(self.data ) self.final_hash() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : bytes ): '''simple docstring''' __A = b'''\x80''' + (b'''\x00''' * (63 - (len(_lowerCamelCase ) + 8) % 64)) __A = struct.pack('''>Q''', (len(_lowerCamelCase ) * 8) ) return data + padding + big_endian_integer def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' # Convert into blocks of 64 bytes __A = [ self.preprocessed_data[x : x + 64] for x in range(0, len(self.preprocessed_data ), 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers __A = list(struct.unpack('''>16L''', _lowerCamelCase ) ) # add 48 0-ed integers words += [0] * 48 __A , __A , __A , __A , __A , __A , __A , __A = self.hashes for index in range(0, 64 ): if index > 15: # modify the zero-ed indexes at the end of the array __A = ( self.ror(words[index - 15], 7 ) ^ self.ror(words[index - 15], 18 ) ^ (words[index - 15] >> 3) ) __A = ( self.ror(words[index - 2], 17 ) ^ self.ror(words[index - 2], 19 ) ^ (words[index - 2] >> 10) ) __A = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X100_000_000 # Compression __A = self.ror(_lowerCamelCase, 6 ) ^ self.ror(_lowerCamelCase, 11 ) ^ self.ror(_lowerCamelCase, 25 ) __A = (e & f) ^ ((~e & 0Xff_fff_fff) & g) __A = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X100_000_000 __A = self.ror(_lowerCamelCase, 2 ) ^ self.ror(_lowerCamelCase, 13 ) ^ self.ror(_lowerCamelCase, 22 ) __A = (a & b) ^ (a & c) ^ (b & c) __A = (sa + maj) % 0X100_000_000 __A , __A , __A , __A , __A , __A , __A , __A = ( g, f, e, ((d + tempa) % 0X100_000_000), c, b, a, ((tempa + tempa) % 0X100_000_000), ) __A = [a, b, c, d, e, f, g, h] # Modify final values __A = [ ((element + mutated_hash_values[index]) % 0X100_000_000) for index, element in enumerate(self.hashes ) ] __A = ''''''.join([hex(_lowerCamelCase )[2:].zfill(8 ) for value in self.hashes] ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' return 0Xff_fff_fff & (value << (32 - rotations)) | (value >> rotations) class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' import hashlib __A = bytes('''Test String''', '''utf-8''' ) self.assertEqual(SHAaaa(_lowerCamelCase ).hash, hashlib.shaaaa(_lowerCamelCase ).hexdigest() ) def lowerCAmelCase ( ): """simple docstring""" import doctest doctest.testmod() __A = argparse.ArgumentParser() parser.add_argument( '''-s''' , '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument( '''-f''' , '''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) __A = parser.parse_args() __A = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: __A = f.read() else: __A = bytes(__UpperCamelCase , '''utf-8''' ) print(SHAaaa(__UpperCamelCase ).hash ) if __name__ == "__main__": main()
266
0
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A , A ) -> List[Any]: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
2
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowercase_ = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' lowercase_ = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' lowercase_ = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, homepage='''https://github.com/krishnap25/mauve''', inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''string''', id='''sequence''' ), '''references''': datasets.Value('''string''', id='''sequence''' ), } ), codebase_urls=['''https://github.com/krishnap25/mauve'''], reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ], ) def _SCREAMING_SNAKE_CASE ( self : int, _lowerCamelCase : str, _lowerCamelCase : Optional[Any], _lowerCamelCase : Any=None, _lowerCamelCase : Tuple=None, _lowerCamelCase : Optional[Any]=None, _lowerCamelCase : Union[str, Any]=None, _lowerCamelCase : str="auto", _lowerCamelCase : Union[str, Any]=-1, _lowerCamelCase : List[str]=0.9, _lowerCamelCase : int=5, _lowerCamelCase : Tuple=5_00, _lowerCamelCase : Union[str, Any]="gpt2-large", _lowerCamelCase : int=-1, _lowerCamelCase : Union[str, Any]=10_24, _lowerCamelCase : Union[str, Any]=25, _lowerCamelCase : str=5, _lowerCamelCase : Any=True, _lowerCamelCase : Union[str, Any]=25, ): '''simple docstring''' __A = compute_mauve( p_text=_lowerCamelCase, q_text=_lowerCamelCase, p_features=_lowerCamelCase, q_features=_lowerCamelCase, p_tokens=_lowerCamelCase, q_tokens=_lowerCamelCase, num_buckets=_lowerCamelCase, pca_max_data=_lowerCamelCase, kmeans_explained_var=_lowerCamelCase, kmeans_num_redo=_lowerCamelCase, kmeans_max_iter=_lowerCamelCase, featurize_model_name=_lowerCamelCase, device_id=_lowerCamelCase, max_text_length=_lowerCamelCase, divergence_curve_discretization_size=_lowerCamelCase, mauve_scaling_factor=_lowerCamelCase, verbose=_lowerCamelCase, seed=_lowerCamelCase, ) return out
266
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') UpperCAmelCase__ : Any = logging.getLogger(__name__) @dataclass class lowerCAmelCase_ : """simple docstring""" __UpperCamelCase : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) __UpperCamelCase : Optional[str] = field( default=_lowerCAmelCase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) __UpperCamelCase : Optional[str] = field( default=_lowerCAmelCase , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) __UpperCamelCase : Optional[str] = field( default=_lowerCAmelCase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) __UpperCamelCase : bool = field( default=_lowerCAmelCase , metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''} , ) __UpperCamelCase : str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) __UpperCamelCase : bool = field( default=_lowerCAmelCase , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) @dataclass class lowerCAmelCase_ : """simple docstring""" __UpperCamelCase : Optional[str] = field(default=_lowerCAmelCase , metadata={'''help''': '''The input training data file (a text file).'''} ) __UpperCamelCase : Optional[str] = field( default=_lowerCAmelCase , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) __UpperCamelCase : bool = field( default=_lowerCAmelCase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) __UpperCamelCase : Optional[int] = field( default=_lowerCAmelCase , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) __UpperCamelCase : Optional[int] = field( default=_lowerCAmelCase , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. If passed, sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) __UpperCamelCase : bool = field( default=_lowerCAmelCase , metadata={ '''help''': ( '''Whether to pad all samples to the maximum sentence length. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch. More ''' '''efficient on GPU but very bad for TPU.''' ) } , ) __UpperCamelCase : Optional[int] = field( default=_lowerCAmelCase , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) __UpperCamelCase : Optional[int] = field( default=_lowerCAmelCase , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def __magic_name__ (self ) -> Any: """simple docstring""" if self.train_file is not None: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.train_file.split(""".""" )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.validation_file.split(""".""" )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class lowerCAmelCase_ : """simple docstring""" __UpperCamelCase : PreTrainedTokenizerBase __UpperCamelCase : Union[bool, str, PaddingStrategy] = True __UpperCamelCase : Optional[int] = None __UpperCamelCase : Optional[int] = None def __call__(self , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = """label""" if """label""" in features[0].keys() else """labels""" SCREAMING_SNAKE_CASE__ : int = [feature.pop(_lowerCamelCase ) for feature in features] SCREAMING_SNAKE_CASE__ : Optional[int] = len(_lowerCamelCase ) SCREAMING_SNAKE_CASE__ : Tuple = len(features[0]["""input_ids"""] ) SCREAMING_SNAKE_CASE__ : List[Any] = [ [{k: v[i] for k, v in feature.items()} for i in range(_lowerCamelCase )] for feature in features ] SCREAMING_SNAKE_CASE__ : Dict = list(chain(*_lowerCamelCase ) ) SCREAMING_SNAKE_CASE__ : Any = self.tokenizer.pad( _lowerCamelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" , ) # Un-flatten SCREAMING_SNAKE_CASE__ : int = {k: v.view(_lowerCamelCase , _lowerCamelCase , -1 ) for k, v in batch.items()} # Add back labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor(_lowerCamelCase , dtype=torch.intaa ) return batch def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : int = 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. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = 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_swag""" ,__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() SCREAMING_SNAKE_CASE__ : Dict = training_args.get_process_log_level() logger.setLevel(__UpperCamelCase ) datasets.utils.logging.set_verbosity(__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}''' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE__ : Optional[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE__ : str = 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 overcome.""" ) 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.""" ) # Set seed before initializing model. set_seed(training_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). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: SCREAMING_SNAKE_CASE__ : List[str] = {} if data_args.train_file is not None: SCREAMING_SNAKE_CASE__ : List[Any] = data_args.train_file if data_args.validation_file is not None: SCREAMING_SNAKE_CASE__ : Any = data_args.validation_file SCREAMING_SNAKE_CASE__ : Optional[int] = data_args.train_file.split(""".""" )[-1] SCREAMING_SNAKE_CASE__ : Any = load_dataset( __UpperCamelCase ,data_files=__UpperCamelCase ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,) else: # Downloading and loading the swag dataset from the hub. SCREAMING_SNAKE_CASE__ : Optional[int] = load_dataset( """swag""" ,"""regular""" ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,) # 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. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__ : int = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) SCREAMING_SNAKE_CASE__ : List[str] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path ,cache_dir=model_args.cache_dir ,use_fast=model_args.use_fast_tokenizer ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) SCREAMING_SNAKE_CASE__ : str = AutoModelForMultipleChoice.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 ,) # When using your own dataset or a different dataset from swag, you will probably need to change this. SCREAMING_SNAKE_CASE__ : Any = [f'''ending{i}''' for i in range(4 )] SCREAMING_SNAKE_CASE__ : int = """sent1""" SCREAMING_SNAKE_CASE__ : int = """sent2""" if data_args.max_seq_length is None: SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.model_max_length if max_seq_length > 1_024: logger.warning( """The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value""" """ of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can""" """ override this default with `--block_size xxx`.""" ) SCREAMING_SNAKE_CASE__ : Tuple = 1_024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f'''The max_seq_length passed ({data_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}.''' ) SCREAMING_SNAKE_CASE__ : int = min(data_args.max_seq_length ,tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(_snake_case ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[context] * 4 for context in examples[context_name]] SCREAMING_SNAKE_CASE__ : List[str] = examples[question_header_name] SCREAMING_SNAKE_CASE__ : List[str] = [ [f'''{header} {examples[end][i]}''' for end in ending_names] for i, header in enumerate(__UpperCamelCase ) ] # Flatten out SCREAMING_SNAKE_CASE__ : List[Any] = list(chain(*__UpperCamelCase ) ) SCREAMING_SNAKE_CASE__ : List[str] = list(chain(*__UpperCamelCase ) ) # Tokenize SCREAMING_SNAKE_CASE__ : str = tokenizer( __UpperCamelCase ,__UpperCamelCase ,truncation=__UpperCamelCase ,max_length=__UpperCamelCase ,padding="""max_length""" if data_args.pad_to_max_length else False ,) # Un-flatten return {k: [v[i : i + 4] for i in range(0 ,len(__UpperCamelCase ) ,4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("""--do_train requires a train dataset""" ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = raw_datasets["""train"""] if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE__ : Tuple = min(len(__UpperCamelCase ) ,data_args.max_train_samples ) SCREAMING_SNAKE_CASE__ : str = train_dataset.select(range(__UpperCamelCase ) ) with training_args.main_process_first(desc="""train dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = train_dataset.map( __UpperCamelCase ,batched=__UpperCamelCase ,num_proc=data_args.preprocessing_num_workers ,load_from_cache_file=not data_args.overwrite_cache ,) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("""--do_eval requires a validation dataset""" ) SCREAMING_SNAKE_CASE__ : Tuple = raw_datasets["""validation"""] if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE__ : int = min(len(__UpperCamelCase ) ,data_args.max_eval_samples ) SCREAMING_SNAKE_CASE__ : List[Any] = eval_dataset.select(range(__UpperCamelCase ) ) with training_args.main_process_first(desc="""validation dataset map pre-processing""" ): SCREAMING_SNAKE_CASE__ : Tuple = eval_dataset.map( __UpperCamelCase ,batched=__UpperCamelCase ,num_proc=data_args.preprocessing_num_workers ,load_from_cache_file=not data_args.overwrite_cache ,) # Data collator SCREAMING_SNAKE_CASE__ : List[Any] = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=__UpperCamelCase ,pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(_snake_case ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = eval_predictions SCREAMING_SNAKE_CASE__ : Dict = np.argmax(__UpperCamelCase ,axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer SCREAMING_SNAKE_CASE__ : str = Trainer( model=__UpperCamelCase ,args=__UpperCamelCase ,train_dataset=train_dataset if training_args.do_train else None ,eval_dataset=eval_dataset if training_args.do_eval else None ,tokenizer=__UpperCamelCase ,data_collator=__UpperCamelCase ,compute_metrics=__UpperCamelCase ,) # Training if training_args.do_train: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE__ : List[str] = training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE__ : str = last_checkpoint SCREAMING_SNAKE_CASE__ : Tuple = trainer.train(resume_from_checkpoint=__UpperCamelCase ) trainer.save_model() # Saves the tokenizer too for easy upload SCREAMING_SNAKE_CASE__ : Dict = train_result.metrics SCREAMING_SNAKE_CASE__ : Dict = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__UpperCamelCase ) ) SCREAMING_SNAKE_CASE__ : int = min(__UpperCamelCase ,len(__UpperCamelCase ) ) trainer.log_metrics("""train""" ,__UpperCamelCase ) trainer.save_metrics("""train""" ,__UpperCamelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) SCREAMING_SNAKE_CASE__ : List[Any] = trainer.evaluate() SCREAMING_SNAKE_CASE__ : Tuple = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : Dict = min(__UpperCamelCase ,len(__UpperCamelCase ) ) trainer.log_metrics("""eval""" ,__UpperCamelCase ) trainer.save_metrics("""eval""" ,__UpperCamelCase ) SCREAMING_SNAKE_CASE__ : Dict = { """finetuned_from""": model_args.model_name_or_path, """tasks""": """multiple-choice""", """dataset_tags""": """swag""", """dataset_args""": """regular""", """dataset""": """SWAG""", """language""": """en""", } if training_args.push_to_hub: trainer.push_to_hub(**__UpperCamelCase ) else: trainer.create_model_card(**__UpperCamelCase ) def lowercase_ ( _snake_case ): main() if __name__ == "__main__": main()
25
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowercase_ = imread(R'digital_image_processing/image_data/lena_small.jpg') lowercase_ = cvtColor(img, COLOR_BGR2GRAY) def lowerCAmelCase ( ): """simple docstring""" __A = cn.convert_to_negative(__UpperCamelCase ) # assert negative_img array for at least one True assert negative_img.any() def lowerCAmelCase ( ): """simple docstring""" with Image.open('''digital_image_processing/image_data/lena_small.jpg''' ) as img: # Work around assertion for response assert str(cc.change_contrast(__UpperCamelCase , 1_1_0 ) ).startswith( '''<PIL.Image.Image image mode=RGB size=100x100 at''' ) def lowerCAmelCase ( ): """simple docstring""" __A = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def lowerCAmelCase ( ): """simple docstring""" __A = imread('''digital_image_processing/image_data/lena_small.jpg''' , 0 ) # assert ambiguous array for all == True assert canny_img.all() __A = canny.canny(__UpperCamelCase ) # assert canny array for at least one True assert canny_array.any() def lowerCAmelCase ( ): """simple docstring""" assert gg.gaussian_filter(__UpperCamelCase , 5 , sigma=0.9 ).all() def lowerCAmelCase ( ): """simple docstring""" __A = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __A = conv.img_convolve(__UpperCamelCase , __UpperCamelCase ).astype(__UpperCamelCase ) assert res.any() def lowerCAmelCase ( ): """simple docstring""" assert med.median_filter(__UpperCamelCase , 3 ).any() def lowerCAmelCase ( ): """simple docstring""" __A , __A = sob.sobel_filter(__UpperCamelCase ) assert grad.any() and theta.any() def lowerCAmelCase ( ): """simple docstring""" __A = sp.make_sepia(__UpperCamelCase , 2_0 ) assert sepia.all() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" ): """simple docstring""" __A = bs.Burkes(imread(__UpperCamelCase , 1 ) , 1_2_0 ) burkes.process() assert burkes.output_img.any() def lowerCAmelCase ( __UpperCamelCase = "digital_image_processing/image_data/lena_small.jpg" , ): """simple docstring""" __A = rs.NearestNeighbour(imread(__UpperCamelCase , 1 ) , 4_0_0 , 2_0_0 ) nn.process() assert nn.output.any() def lowerCAmelCase ( ): """simple docstring""" __A = '''digital_image_processing/image_data/lena.jpg''' # Reading the image and converting it to grayscale. __A = imread(__UpperCamelCase , 0 ) # Test for get_neighbors_pixel function() return not None __A = 0 __A = 0 __A = image[x_coordinate][y_coordinate] __A = lbp.get_neighbors_pixel( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __A = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): __A = lbp.local_binary_value(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) assert lbp_image.any()
266
0
import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, 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 ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=1_28 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels 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__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def UpperCAmelCase_ (self ): 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] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ (self ): return NezhaConfig( 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 UpperCAmelCase_ (self ): ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( 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, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = NezhaModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase ) UpperCamelCase__ = model(_lowerCamelCase , token_type_ids=_lowerCamelCase ) UpperCamelCase__ = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = True UpperCamelCase__ = NezhaModel(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase__ = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , encoder_attention_mask=_lowerCamelCase , ) UpperCamelCase__ = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , ) UpperCamelCase__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = NezhaForMaskedLM(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase__ = 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 UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = NezhaForNextSentencePrediction(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase__ = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = NezhaForPreTraining(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase__ = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase , next_sentence_label=_lowerCamelCase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = NezhaForQuestionAnswering(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase__ = 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 UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = NezhaForSequenceClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = NezhaForTokenClassification(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase__ = 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 UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_choices UpperCamelCase__ = NezhaForMultipleChoice(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = True def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = super()._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) if return_labels: if model_class in get_values(_lowerCamelCase ): UpperCamelCase__ = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_lowerCamelCase ) UpperCamelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_lowerCamelCase ) return inputs_dict def UpperCAmelCase_ (self ): UpperCamelCase__ = NezhaModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=_lowerCamelCase , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_lowerCamelCase ) def UpperCAmelCase_ (self ): ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( 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( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*_lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_lowerCamelCase ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase ) @slow def UpperCAmelCase_ (self ): for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = NezhaModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @slow @require_torch_gpu def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return UpperCamelCase__ = True UpperCamelCase__ = model_class(config=_lowerCamelCase ) UpperCamelCase__ = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) UpperCamelCase__ = torch.jit.trace( _lowerCamelCase , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_lowerCamelCase , os.path.join(_lowerCamelCase , """bert.pt""" ) ) UpperCamelCase__ = torch.jit.load(os.path.join(_lowerCamelCase , """bert.pt""" ) , map_location=_lowerCamelCase ) loaded(inputs_dict["""input_ids"""].to(_lowerCamelCase ) , inputs_dict["""attention_mask"""].to(_lowerCamelCase ) ) @require_torch class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = NezhaModel.from_pretrained("""sijunhe/nezha-cn-base""" ) UpperCamelCase__ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase__ = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCamelCase__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] UpperCamelCase__ = torch.Size((1, 6, 7_68) ) self.assertEqual(output.shape , _lowerCamelCase ) UpperCamelCase__ = torch.tensor([[[0.0685, 0.2441, 0.1102], [0.0600, 0.1906, 0.1349], [0.0221, 0.0819, 0.0586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _lowerCamelCase , atol=1E-4 ) ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = NezhaForMaskedLM.from_pretrained("""sijunhe/nezha-cn-base""" ) UpperCamelCase__ = torch.tensor([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase__ = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCamelCase__ = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] UpperCamelCase__ = torch.Size((1, 6, 2_11_28) ) self.assertEqual(output.shape , _lowerCamelCase ) UpperCamelCase__ = torch.tensor( [[-2.7939, -1.7902, -2.2189], [-2.8585, -1.8908, -2.3723], [-2.6499, -1.7750, -2.2558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _lowerCamelCase , atol=1E-4 ) )
244
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase_ = random.Random() if is_torch_available(): import torch def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase=1.0 , __UpperCamelCase=None , __UpperCamelCase=None ): """simple docstring""" if rng is None: __A = global_rng __A = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any, _lowerCamelCase : List[str], _lowerCamelCase : Any=7, _lowerCamelCase : Optional[int]=4_00, _lowerCamelCase : Optional[int]=20_00, _lowerCamelCase : Dict=1, _lowerCamelCase : Optional[Any]=0.0, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : Dict=True, ): '''simple docstring''' __A = parent __A = batch_size __A = min_seq_length __A = max_seq_length __A = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __A = feature_size __A = padding_value __A = sampling_rate __A = return_attention_mask __A = do_normalize def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[Any]=False, _lowerCamelCase : int=False ): '''simple docstring''' def _flatten(_lowerCamelCase : List[str] ): return list(itertools.chain(*_lowerCamelCase ) ) if equal_length: __A = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __A = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff ) ] if numpify: __A = [np.asarray(_lowerCamelCase ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : int = ASTFeatureExtractor def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ASTFeatureExtractionTester(self ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' # Tests that all call wrap to encode_plus and batch_encode_plus __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __A = [floats_list((1, x) )[0] for x in range(8_00, 14_00, 2_00 )] __A = [np.asarray(_lowerCamelCase ) for speech_input in speech_inputs] # Test not batched input __A = feat_extract(speech_inputs[0], return_tensors='''np''' ).input_values __A = feat_extract(np_speech_inputs[0], return_tensors='''np''' ).input_values self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test batched __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, padding=_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) # Test 2-D numpy arrays are batched. __A = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] __A = np.asarray(_lowerCamelCase ) __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values __A = feat_extract(_lowerCamelCase, return_tensors='''np''' ).input_values for enc_seq_a, enc_seq_a in zip(_lowerCamelCase, _lowerCamelCase ): self.assertTrue(np.allclose(_lowerCamelCase, _lowerCamelCase, atol=1e-3 ) ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' import torch __A = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __A = np.random.rand(1_00 ).astype(np.floataa ) __A = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''np''' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __A = feature_extractor.pad([{'''input_values''': inputs}], return_tensors='''pt''' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Union[str, Any] ): '''simple docstring''' from datasets import load_dataset __A = load_dataset('''hf-internal-testing/librispeech_asr_dummy''', '''clean''', split='''validation''' ) # automatic decoding with librispeech __A = ds.sort('''id''' ).select(range(_lowerCamelCase ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] @require_torch def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' # fmt: off __A = torch.tensor( [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76, -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33, -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36, -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69] ) # fmt: on __A = self._load_datasamples(1 ) __A = ASTFeatureExtractor() __A = feature_extractor(_lowerCamelCase, return_tensors='''pt''' ).input_values self.assertEquals(input_values.shape, (1, 10_24, 1_28) ) self.assertTrue(torch.allclose(input_values[0, 0, :30], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' from __future__ import annotations def __lowerCamelCase ( A__ , A__ , A__ , A__ ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = [] UpperCamelCase , UpperCamelCase = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) UpperCamelCase = result + left + right return input_list def __lowerCamelCase ( A__ ) -> str: """simple docstring""" if len(__UpperCamelCase ) <= 1: return input_list UpperCamelCase = list(__UpperCamelCase ) # iteration for two-way merging UpperCamelCase = 2 while p <= len(__UpperCamelCase ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(__UpperCamelCase ) , __UpperCamelCase ): UpperCamelCase = i UpperCamelCase = i + p - 1 UpperCamelCase = (low + high + 1) // 2 UpperCamelCase = merge(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # final merge of last two parts if p * 2 >= len(__UpperCamelCase ): UpperCamelCase = i UpperCamelCase = merge(__UpperCamelCase , 0 , __UpperCamelCase , len(__UpperCamelCase ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": _lowerCamelCase : Optional[int] = input("Enter numbers separated by a comma:\n").strip() if user_input == "": _lowerCamelCase : int = [] else: _lowerCamelCase : Union[str, Any] = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
28
"""simple docstring""" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = current_set.copy() for row_index, row in enumerate(__UpperCamelCase ): __A = row[0] for column_index, column in enumerate(__UpperCamelCase ): if magnitude == 0: __A = column continue __A = column / magnitude # Subtract to cancel term __A = current_set[0] __A = [first_row] __A = current_set[1::] for row in current_set: __A = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(__UpperCamelCase ) continue for column_index in range(len(__UpperCamelCase ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(__UpperCamelCase ) # Create next recursion iteration set if len(final_set[0] ) != 3: __A = final_set[0] __A = [] __A = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __A = simplify(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , __UpperCamelCase ) __A = resultant return final_set def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if len(__UpperCamelCase ) == 0: raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) __A = len(__UpperCamelCase ) + 1 if any(len(__UpperCamelCase ) != _length for item in equations ): raise IndexError('''solve_simultaneous() requires n lists of length n+1''' ) for row in equations: if any(not isinstance(__UpperCamelCase , (int, float) ) for column in row ): raise ValueError('''solve_simultaneous() requires lists of integers''' ) if len(__UpperCamelCase ) == 1: return [equations[0][-1] / equations[0][0]] __A = equations.copy() if any(0 in row for row in data_set ): __A = data_set.copy() __A = [] for row_index, row in enumerate(__UpperCamelCase ): if 0 not in row: __A = data_set.pop(__UpperCamelCase ) break if not full_row: raise ValueError('''solve_simultaneous() requires at least 1 full equation''' ) data_set.insert(0 , __UpperCamelCase ) __A = data_set.copy() __A = simplify(__UpperCamelCase ) __A = simplified[::-1] __A = [] for row in simplified: __A = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __A = row.copy()[: len(__UpperCamelCase ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(__UpperCamelCase ) == 0: solutions.append(0 ) continue __A = temp_row[1::] __A = temp_row[::-1] for column_index, column in enumerate(__UpperCamelCase ): current_solution -= column * solutions[column_index] solutions.append(__UpperCamelCase ) __A = [] for item in solutions: final.append(float(round(__UpperCamelCase , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
266
0
"""simple docstring""" __UpperCamelCase : Optional[int] = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def __SCREAMING_SNAKE_CASE ( ): lowerCAmelCase__ : Union[str, Any] = input('''Enter message: ''' ) lowerCAmelCase__ : Optional[int] = input('''Enter key [alphanumeric]: ''' ) lowerCAmelCase__ : Optional[int] = input('''Encrypt/Decrypt [e/d]: ''' ) if mode.lower().startswith('''e''' ): lowerCAmelCase__ : Union[str, Any] = '''encrypt''' lowerCAmelCase__ : Union[str, Any] = encrypt_message(__UpperCamelCase , __UpperCamelCase ) elif mode.lower().startswith('''d''' ): lowerCAmelCase__ : Any = '''decrypt''' lowerCAmelCase__ : str = decrypt_message(__UpperCamelCase , __UpperCamelCase ) print(f'\n{mode.title()}ed message:' ) print(__UpperCamelCase ) def __SCREAMING_SNAKE_CASE ( A_ , A_ ): return translate_message(__UpperCamelCase , __UpperCamelCase , '''encrypt''' ) def __SCREAMING_SNAKE_CASE ( A_ , A_ ): return translate_message(__UpperCamelCase , __UpperCamelCase , '''decrypt''' ) def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ ): lowerCAmelCase__ : Tuple = [] lowerCAmelCase__ : Optional[int] = 0 lowerCAmelCase__ : List[str] = key.upper() for symbol in message: lowerCAmelCase__ : Tuple = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(__UpperCamelCase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(__UpperCamelCase ): lowerCAmelCase__ : int = 0 else: translated.append(__UpperCamelCase ) return "".join(__UpperCamelCase ) if __name__ == "__main__": main()
106
"""simple docstring""" from __future__ import annotations from typing import Any def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not postfix_notation: return 0 __A = {'''+''', '''-''', '''*''', '''/'''} __A = [] for token in postfix_notation: if token in operations: __A , __A = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(__UpperCamelCase ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
266
0
from ..utils import DummyObject, requires_backends class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["speech"] def __init__( self : Dict , *snake_case : Any , **snake_case : Any ) -> Tuple: """simple docstring""" requires_backends(self , ['speech'] ) class _lowercase ( metaclass=_lowerCAmelCase ): lowercase = ["speech"] def __init__( self : List[str] , *snake_case : Any , **snake_case : Any ) -> Tuple: """simple docstring""" requires_backends(self , ['speech'] )
175
"""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 snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple, _lowerCamelCase : List[str]=13, _lowerCamelCase : Optional[Any]=7, _lowerCamelCase : Optional[int]=True, _lowerCamelCase : int=True, _lowerCamelCase : List[str]=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : int=99, _lowerCamelCase : Optional[int]=32, _lowerCamelCase : Tuple=5, _lowerCamelCase : Tuple=4, _lowerCamelCase : str=37, _lowerCamelCase : Union[str, Any]="gelu", _lowerCamelCase : int=0.1, _lowerCamelCase : List[Any]=0.1, _lowerCamelCase : Dict=5_12, _lowerCamelCase : List[Any]=16, _lowerCamelCase : Any=2, _lowerCamelCase : Any=0.02, _lowerCamelCase : Dict=4, ): '''simple docstring''' __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_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_choices def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) __A = None if self.use_attention_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 = 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 _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Dict = True A_ : Tuple = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = FlaxRoFormerModelTester(self ) @slow def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained('''junnyu/roformer_chinese_small''', from_pt=_lowerCamelCase ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase ) @require_flax class snake_case ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = FlaxRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __A = jnp.array([[0, 1, 2, 3, 4, 5]] ) __A = model(_lowerCamelCase )[0] __A = 5_00_00 __A = (1, 6, vocab_size) self.assertEqual(output.shape, _lowerCamelCase ) __A = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3], _lowerCamelCase, atol=1e-4 ) )
266
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase : Dict = { '''configuration_deberta''': ['''DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DebertaConfig''', '''DebertaOnnxConfig'''], '''tokenization_deberta''': ['''DebertaTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] = ['''DebertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[str] = [ '''DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''DebertaForMaskedLM''', '''DebertaForQuestionAnswering''', '''DebertaForSequenceClassification''', '''DebertaForTokenClassification''', '''DebertaModel''', '''DebertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Tuple = [ '''TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFDebertaForMaskedLM''', '''TFDebertaForQuestionAnswering''', '''TFDebertaForSequenceClassification''', '''TFDebertaForTokenClassification''', '''TFDebertaModel''', '''TFDebertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys __lowercase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
318
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def lowerCAmelCase ( __UpperCamelCase = 1_0_0_0_0_0_0 , __UpperCamelCase = 1_0 ): """simple docstring""" __A = defaultdict(__UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: __A = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: __A = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(__UpperCamelCase , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 1_0 ) if __name__ == "__main__": print(F'''{solution() = }''')
266
0
lowercase__ :Tuple = range(2, 20 + 1) lowercase__ :Optional[int] = [10**k for k in range(ks[-1] + 1)] lowercase__ :Any = {} def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = sum(a_i[j] for j in range(__UpperCamelCase , len(__UpperCamelCase ) ) ) lowercase = sum(a_i[j] * base[j] for j in range(min(len(__UpperCamelCase ) , __UpperCamelCase ) ) ) lowercase , lowercase = 0, 0 lowercase = n - i lowercase = memo.get(__UpperCamelCase ) if sub_memo is not None: lowercase = sub_memo.get(__UpperCamelCase ) if jumps is not None and len(__UpperCamelCase ) > 0: # find and make the largest jump without going over lowercase = -1 for _k in range(len(__UpperCamelCase ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: lowercase = _k break if max_jump >= 0: lowercase , lowercase , lowercase = jumps[max_jump] # since the difference between jumps is cached, add c lowercase = diff + c for j in range(min(__UpperCamelCase , len(__UpperCamelCase ) ) ): lowercase , lowercase = divmod(__UpperCamelCase , 10 ) if new_c > 0: add(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) else: lowercase = [] else: lowercase = {c: []} lowercase = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps lowercase , lowercase = next_term(__UpperCamelCase , k - 1 , i + dn , __UpperCamelCase ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead lowercase , lowercase = compute(__UpperCamelCase , __UpperCamelCase , i + dn , __UpperCamelCase ) diff += _diff dn += terms_jumped lowercase = sub_memo[c] # keep jumps sorted by # of terms skipped lowercase = 0 while j < len(__UpperCamelCase ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(__UpperCamelCase , (diff, dn, k) ) return (diff, dn) def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' if i >= n: return 0, i if k > len(__UpperCamelCase ): a_i.extend([0 for _ in range(k - len(__UpperCamelCase ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) lowercase = i lowercase , lowercase , lowercase = 0, 0, 0 for j in range(len(__UpperCamelCase ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 lowercase = ds_c + ds_b diff += addend lowercase = 0 for j in range(__UpperCamelCase ): lowercase = a_i[j] + addend lowercase , lowercase = divmod(__UpperCamelCase , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) return diff, i - start_i def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' for j in range(__UpperCamelCase , len(__UpperCamelCase ) ): lowercase = digits[j] + addend if s >= 10: lowercase , lowercase = divmod(__UpperCamelCase , 10 ) lowercase = addend // 10 + quotient else: lowercase = s lowercase = addend // 10 if addend == 0: break while addend > 0: lowercase , lowercase = divmod(__UpperCamelCase , 10 ) digits.append(__UpperCamelCase ) def UpperCamelCase ( lowerCAmelCase__ = 10**15 ): '''simple docstring''' lowercase = [1] lowercase = 1 lowercase = 0 while True: lowercase , lowercase = next_term(__UpperCamelCase , 20 , i + dn , __UpperCamelCase ) dn += terms_jumped if dn == n - i: break lowercase = 0 for j in range(len(__UpperCamelCase ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(F'{solution() = }')
101
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class snake_case : '''simple docstring''' def __init__( self : Optional[int], _lowerCamelCase : Optional[int]=2, _lowerCamelCase : Optional[int]=3, _lowerCamelCase : int=64, _lowerCamelCase : List[str]=None ): '''simple docstring''' __A = np.random.default_rng(_lowerCamelCase ) __A = length __A = rng.normal(size=(length,) ).astype(np.floataa ) __A = a * self.x + b + rng.normal(scale=0.1, size=(length,) ).astype(np.floataa ) def __len__( self : str ): '''simple docstring''' return self.length def __getitem__( self : Dict, _lowerCamelCase : Optional[int] ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : Optional[Any], _lowerCamelCase : Tuple=0, _lowerCamelCase : Any=0, _lowerCamelCase : Optional[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : Optional[Any]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a[0] + self.b[0] class snake_case ( torch.nn.Module ): '''simple docstring''' def __init__( self : str, _lowerCamelCase : Optional[Any]=0, _lowerCamelCase : Any=0, _lowerCamelCase : List[Any]=False ): '''simple docstring''' super().__init__() __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __A = True def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[str]=None ): '''simple docstring''' if self.first_batch: print(f'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __A = False return x * self.a + self.b def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase = 1_6 ): """simple docstring""" from datasets import load_dataset from transformers import AutoTokenizer __A = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __A = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __A = load_dataset('''csv''' , data_files=__UpperCamelCase ) __A = datasets['''train'''].unique('''label''' ) __A = {v: i for i, v in enumerate(__UpperCamelCase )} def tokenize_function(__UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding='''max_length''' ) if "label" in examples: __A = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __A = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(__UpperCamelCase ): # 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(__UpperCamelCase , padding='''max_length''' , max_length=1_2_8 , return_tensors='''pt''' ) return tokenizer.pad(__UpperCamelCase , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __A = DataLoader(tokenized_datasets['''train'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2 ) __A = DataLoader(tokenized_datasets['''validation'''] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
266
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE_ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ : Dict = { 'google/switch-base-8': 'https://huggingface.co/google/switch-base-8/blob/main/config.json', } class a ( _lowerCAmelCase ): """simple docstring""" UpperCAmelCase = "switch_transformers" UpperCAmelCase = ["past_key_values"] UpperCAmelCase = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self: Tuple , UpperCamelCase: Optional[Any]=3_21_28 , UpperCamelCase: str=7_68 , UpperCamelCase: Optional[int]=64 , UpperCamelCase: Optional[Any]=20_48 , UpperCamelCase: str=64 , UpperCamelCase: Dict=12 , UpperCamelCase: Tuple=3 , UpperCamelCase: Optional[Any]=12 , UpperCamelCase: int=3 , UpperCamelCase: Union[str, Any]=12 , UpperCamelCase: Tuple=8 , UpperCamelCase: int=False , UpperCamelCase: List[Any]=0.01 , UpperCamelCase: Optional[int]="float32" , UpperCamelCase: Dict=False , UpperCamelCase: Dict=32 , UpperCamelCase: Any=1_28 , UpperCamelCase: List[Any]=0.1 , UpperCamelCase: Tuple=1e-6 , UpperCamelCase: Tuple=0.001 , UpperCamelCase: Union[str, Any]=0.001 , UpperCamelCase: Dict=1.0 , UpperCamelCase: Dict="relu" , UpperCamelCase: Any=True , UpperCamelCase: Any=False , UpperCamelCase: Tuple=True , UpperCamelCase: int=0 , UpperCamelCase: Any=1 , **UpperCamelCase: Any , ): """simple docstring""" A__ = vocab_size A__ = d_model A__ = d_kv A__ = d_ff A__ = num_sparse_encoder_layers A__ = num_layers A__ = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry A__ = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: A__ = self.num_layers // self.num_sparse_encoder_layers else: A__ = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: A__ = self.num_decoder_layers // self.num_sparse_decoder_layers else: A__ = self.num_decoder_layers # HACK: this will create 0 sparse layers A__ = num_heads A__ = num_experts A__ = expert_capacity A__ = router_bias A__ = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f"""`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}""" ) A__ = router_dtype A__ = router_ignore_padding_tokens A__ = relative_attention_num_buckets A__ = relative_attention_max_distance A__ = dropout_rate A__ = layer_norm_epsilon A__ = initializer_factor A__ = feed_forward_proj A__ = use_cache A__ = add_router_probs A__ = router_z_loss_coef A__ = router_aux_loss_coef A__ = self.feed_forward_proj.split("""-""" ) A__ = act_info[-1] A__ = act_info[0] == """gated""" if len(_lowerCamelCase ) > 1 and act_info[0] != "gated" or len(_lowerCamelCase ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """\'gated-gelu\' or \'relu\'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": A__ = """gelu_new""" super().__init__( pad_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , **_lowerCamelCase , )
335
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowercase_ = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' lowercase_ = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' lowercase_ = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''', id='''token''' ), id='''sequence''' ), id='''references''' ), } ), ) def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[List[List[str]]], _lowerCamelCase : List[List[str]], _lowerCamelCase : int = 1, _lowerCamelCase : int = 4, ): '''simple docstring''' return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCamelCase, hypotheses=_lowerCamelCase, min_len=_lowerCamelCase, max_len=_lowerCamelCase ) }
266
0
'''simple docstring''' import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() lowercase : List[str] = logging.get_logger(__name__) lowercase : int = { "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", "encoder.layer_norm_for_extract": "layer_norm_for_extract", "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", "label_embs_concat": "label_embeddings_concat", "mask_emb": "masked_spec_embed", "spk_proj": "speaker_proj", } lowercase : Optional[int] = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "label_embeddings_concat", "speaker_proj", "layer_norm_for_extract", ] def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A , __A ) -> str: for attribute in key.split('.' ): _snake_case = getattr(__UpperCamelCase , __UpperCamelCase ) if weight_type is not None: _snake_case = getattr(__UpperCamelCase , __UpperCamelCase ).shape 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 else: _snake_case = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> List[str]: _snake_case = [] _snake_case = fairseq_model.state_dict() _snake_case = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): _snake_case = False if "conv_layers" in name: load_conv_layer( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , hf_model.config.feat_extract_norm == 'group' , ) _snake_case = True else: for key, mapped_key in MAPPING.items(): _snake_case = 'unispeech_sat.' + 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]: if "layer_norm_for_extract" in name and (".".join(name.split('.' )[:-1] ) != key): # special case since naming is very similar continue _snake_case = True if "*" in mapped_key: _snake_case = name.split(__UpperCamelCase )[0].split('.' )[-2] _snake_case = mapped_key.replace('*' , __UpperCamelCase ) 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 set_recursively(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) continue if not is_used: unused_weights.append(__UpperCamelCase ) logger.warning(F'Unused weights: {unused_weights}' ) def SCREAMING_SNAKE_CASE__ ( __A , __A , __A , __A , __A ) -> List[str]: _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[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[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(__UpperCamelCase ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( __A , __A , __A=None , __A=None , __A=True ) -> str: if config_path is not None: _snake_case = UniSpeechSatConfig.from_pretrained(__UpperCamelCase ) else: _snake_case = UniSpeechSatConfig() _snake_case = '' if is_finetuned: _snake_case = UniSpeechSatForCTC(__UpperCamelCase ) else: _snake_case = UniSpeechSatForPreTraining(__UpperCamelCase ) _snake_case , _snake_case , _snake_case = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) _snake_case = model[0].eval() recursively_load_weights(__UpperCamelCase , __UpperCamelCase ) hf_wavavec.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": lowercase : int = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) lowercase : List[Any] = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
42
"""simple docstring""" class snake_case : '''simple docstring''' def __init__( self : List[str], _lowerCamelCase : list[int] ): '''simple docstring''' __A = len(_lowerCamelCase ) __A = [0] * len_array if len_array > 0: __A = array[0] for i in range(1, _lowerCamelCase ): __A = self.prefix_sum[i - 1] + array[i] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : int, _lowerCamelCase : int ): '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : int ): '''simple docstring''' __A = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_lowerCamelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
266
0
"""simple docstring""" import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class __UpperCamelCase : def __init__( self , lowerCAmelCase__=2 , lowerCAmelCase__=3 , lowerCAmelCase__=64 , lowerCAmelCase__=None ) -> Any: a : int = np.random.default_rng(_lowerCamelCase ) a : List[str] = length a : Dict = rng.normal(size=(length,) ).astype(np.floataa ) a : int = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> Any: return self.length def __getitem__( self , lowerCAmelCase__ ) -> Optional[int]: return {"x": self.x[i], "y": self.y[i]} class __UpperCamelCase ( torch.nn.Module ): def __init__( self , lowerCAmelCase__=0 , lowerCAmelCase__=0 , lowerCAmelCase__=False ) -> Any: super().__init__() a : List[str] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) a : List[str] = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) a : Optional[Any] = True def __a ( self , lowerCAmelCase__=None ) -> int: if self.first_batch: print(f"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}""" ) a : Dict = False return x * self.a[0] + self.b[0] class __UpperCamelCase ( torch.nn.Module ): def __init__( self , lowerCAmelCase__=0 , lowerCAmelCase__=0 , lowerCAmelCase__=False ) -> Union[str, Any]: super().__init__() a : Dict = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) a : Union[str, Any] = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) a : Tuple = True def __a ( self , lowerCAmelCase__=None ) -> List[str]: if self.first_batch: print(f"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}""" ) a : Union[str, Any] = False return x * self.a + self.b def _SCREAMING_SNAKE_CASE ( _lowercase : Tuple , _lowercase : List[Any] = 16 ) ->List[str]: '''simple docstring''' from datasets import load_dataset from transformers import AutoTokenizer a : int = AutoTokenizer.from_pretrained("bert-base-cased" ) a : Tuple = {"train": "tests/test_samples/MRPC/train.csv", "validation": "tests/test_samples/MRPC/dev.csv"} a : List[Any] = load_dataset("csv" , data_files=__UpperCamelCase ) a : Optional[int] = datasets["train"].unique("label" ) a : List[Any] = {v: i for i, v in enumerate(__UpperCamelCase )} def tokenize_function(_lowercase : List[Any] ): # max_length=None => use the model max length (it's actually the default) a : str = tokenizer( examples["sentence1"] , examples["sentence2"] , truncation=__UpperCamelCase , max_length=__UpperCamelCase , padding="max_length" ) if "label" in examples: a : Dict = [label_to_id[l] for l in examples["label"]] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset a : int = datasets.map( __UpperCamelCase , batched=__UpperCamelCase , remove_columns=["sentence1", "sentence2", "label"] , ) def collate_fn(_lowercase : 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(__UpperCamelCase , padding="max_length" , max_length=128 , return_tensors="pt" ) return tokenizer.pad(__UpperCamelCase , padding="longest" , return_tensors="pt" ) # Instantiate dataloaders. a : str = DataLoader(tokenized_datasets["train"] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=2 ) a : Optional[Any] = DataLoader(tokenized_datasets["validation"] , shuffle=__UpperCamelCase , collate_fn=__UpperCamelCase , batch_size=1 ) return train_dataloader, eval_dataloader
105
"""simple docstring""" import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ = logging.get_logger(__name__) lowercase_ = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } lowercase_ = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } lowercase_ = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCAmelCase ( ): """simple docstring""" __A = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __A = bs[:] __A = 0 for b in range(2**8 ): if b not in bs: bs.append(__UpperCamelCase ) cs.append(2**8 + n ) n += 1 __A = [chr(__UpperCamelCase ) for n in cs] return dict(zip(__UpperCamelCase , __UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = set() __A = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __A = char return pairs class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : Tuple = VOCAB_FILES_NAMES A_ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP A_ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A_ : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self : Dict, _lowerCamelCase : Optional[Any], _lowerCamelCase : List[str], _lowerCamelCase : Dict="replace", _lowerCamelCase : Any="<s>", _lowerCamelCase : Optional[int]="</s>", _lowerCamelCase : Dict="</s>", _lowerCamelCase : List[Any]="<s>", _lowerCamelCase : List[str]="<unk>", _lowerCamelCase : str="<pad>", _lowerCamelCase : Any="<mask>", _lowerCamelCase : Any=False, **_lowerCamelCase : Tuple, ): '''simple docstring''' __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else bos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else eos_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else sep_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else cls_token __A = AddedToken(_lowerCamelCase, lstrip=_lowerCamelCase, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase, _lowerCamelCase ) else unk_token __A = 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 __A = 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: __A = json.load(_lowerCamelCase ) __A = {v: k for k, v in self.encoder.items()} __A = errors # how to handle errors in decoding __A = bytes_to_unicode() __A = {v: k for k, v in self.byte_encoder.items()} with open(_lowerCamelCase, encoding='''utf-8''' ) as merges_handle: __A = merges_handle.read().split('''\n''' )[1:-1] __A = [tuple(merge.split() ) for merge in bpe_merges] __A = dict(zip(_lowerCamelCase, range(len(_lowerCamelCase ) ) ) ) __A = {} __A = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __A = 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.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' return len(self.encoder ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' return dict(self.encoder, **self.added_tokens_encoder ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : List[Any] ): '''simple docstring''' if token in self.cache: return self.cache[token] __A = tuple(_lowerCamelCase ) __A = get_pairs(_lowerCamelCase ) if not pairs: return token while True: __A = min(_lowerCamelCase, key=lambda _lowerCamelCase : self.bpe_ranks.get(_lowerCamelCase, float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __A , __A = bigram __A = [] __A = 0 while i < len(_lowerCamelCase ): try: __A = word.index(_lowerCamelCase, _lowerCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __A = 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 __A = tuple(_lowerCamelCase ) __A = new_word if len(_lowerCamelCase ) == 1: break else: __A = get_pairs(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = word return word def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Dict ): '''simple docstring''' __A = [] for token in re.findall(self.pat, _lowerCamelCase ): __A = ''''''.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 _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : Dict ): '''simple docstring''' return self.encoder.get(_lowerCamelCase, self.encoder.get(self.unk_token ) ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : Any ): '''simple docstring''' return self.decoder.get(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' __A = ''''''.join(_lowerCamelCase ) __A = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''', errors=self.errors ) return text def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : str, _lowerCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __A = os.path.join( _lowerCamelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __A = 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''' ) __A = 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!''' ) __A = token_index writer.write(''' '''.join(_lowerCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def _SCREAMING_SNAKE_CASE ( self : Optional[int], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None, _lowerCamelCase : bool = 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 _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Union[str, Any], _lowerCamelCase : List[str]=False, **_lowerCamelCase : List[Any] ): '''simple docstring''' __A = 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()): __A = ''' ''' + text return (text, kwargs) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any], _lowerCamelCase : List[int], _lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : List[Any], _lowerCamelCase : "Conversation" ): '''simple docstring''' __A = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(_lowerCamelCase ) __A = ''' '''.join(_lowerCamelCase ) __A = self.encode(_lowerCamelCase ) if len(_lowerCamelCase ) > self.model_max_length: __A = input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
266
0
'''simple docstring''' import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging lowerCamelCase : Dict = logging.get_logger(__name__) logging.set_verbosity_info() def _SCREAMING_SNAKE_CASE (A , A ) -> Dict: """simple docstring""" if "xprophetnet" in prophetnet_checkpoint_path: lowercase__ = XLMProphetNetForConditionalGenerationOld.from_pretrained(__UpperCamelCase ) lowercase__ ,lowercase__ = XLMProphetNetForConditionalGeneration.from_pretrained( __UpperCamelCase , output_loading_info=__UpperCamelCase ) else: lowercase__ = ProphetNetForConditionalGenerationOld.from_pretrained(__UpperCamelCase ) lowercase__ ,lowercase__ = ProphetNetForConditionalGeneration.from_pretrained( __UpperCamelCase , output_loading_info=__UpperCamelCase ) lowercase__ = ['''key_proj''', '''value_proj''', '''query_proj'''] lowercase__ = { '''self_attn''': '''ngram_self_attn''', '''cross_attn''': '''encoder_attn''', '''cross_attn_layer_norm''': '''encoder_attn_layer_norm''', '''feed_forward_layer_norm''': '''final_layer_norm''', '''feed_forward''': '''''', '''intermediate''': '''fc1''', '''output''': '''fc2''', '''key_proj''': '''k_proj''', '''query_proj''': '''q_proj''', '''value_proj''': '''v_proj''', '''word_embeddings''': '''embed_tokens''', '''embeddings_layer_norm''': '''emb_layer_norm''', '''relative_pos_embeddings''': '''relative_linear''', '''ngram_embeddings''': '''ngram_input_embed''', '''position_embeddings''': '''embed_positions''', } for key in loading_info["missing_keys"]: lowercase__ = key.split('''.''' ) if attributes[0] == "lm_head": lowercase__ = prophet lowercase__ = prophet_old else: lowercase__ = prophet.prophetnet lowercase__ = prophet_old.model lowercase__ = False for attribute in attributes: if attribute in mapping: lowercase__ = mapping[attribute] if not hasattr(__UpperCamelCase , __UpperCamelCase ) and len(__UpperCamelCase ) > 0: lowercase__ = attribute elif hasattr(__UpperCamelCase , __UpperCamelCase ): lowercase__ = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" lowercase__ = old_model.weight logger.info(f"{attribute} is initialized." ) lowercase__ = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" lowercase__ = old_model.bias logger.info(f"{attribute} is initialized" ) lowercase__ = True break elif attribute in special_keys and hasattr(__UpperCamelCase , '''in_proj_weight''' ): lowercase__ = old_model.in_proj_weight.shape[0] // 3 lowercase__ = getattr(__UpperCamelCase , __UpperCamelCase ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": lowercase__ = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) lowercase__ = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": lowercase__ = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) lowercase__ = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": lowercase__ = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) lowercase__ = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) lowercase__ = True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 512, "We want 512 position_embeddings." lowercase__ = nn.Parameter(old_model.embed_positions.weight[:512, :] ) lowercase__ = True break if attribute.isdigit(): lowercase__ = model[int(__UpperCamelCase )] lowercase__ = old_model[int(__UpperCamelCase )] else: lowercase__ = getattr(__UpperCamelCase , __UpperCamelCase ) if old_attribute == "": lowercase__ = old_model else: if not hasattr(__UpperCamelCase , __UpperCamelCase ): raise ValueError(f"{old_model} does not have {old_attribute}" ) lowercase__ = getattr(__UpperCamelCase , __UpperCamelCase ) if not is_key_init: raise ValueError(f"{key} was not correctly initialized!" ) print(f"Saving model to {pytorch_dump_folder_path}" ) prophet.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": lowerCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--prophetnet_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.' ) lowerCamelCase : Union[str, Any] = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
2
"""simple docstring""" import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging lowercase_ = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase ( ): """simple docstring""" __A = '''https://pypi.org/pypi/diffusers/json''' __A = json.loads(request.urlopen(__UpperCamelCase ).read() )['''releases'''].keys() return sorted(__UpperCamelCase , key=lambda __UpperCamelCase : version.Version(__UpperCamelCase ) ) def lowerCAmelCase ( ): """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(__UpperCamelCase ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = Path(__UpperCamelCase ) / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" init_hf_modules() __A = Path(__UpperCamelCase ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(__UpperCamelCase , exist_ok=__UpperCamelCase ) __A = dynamic_module_path / '''__init__.py''' if not init_path.exists(): init_path.touch() def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import .xxx` __A = re.findall('''^\s*import\s+\.(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Unique-ify return list(set(__UpperCamelCase ) ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = False __A = [module_file] __A = [] # Let's recurse through all relative imports while not no_change: __A = [] for f in files_to_check: new_imports.extend(get_relative_imports(__UpperCamelCase ) ) __A = Path(__UpperCamelCase ).parent __A = [str(module_path / m ) for m in new_imports] __A = [f for f in new_import_files if f not in all_relative_imports] __A = [f'{f}.py' for f in new_import_files] __A = len(__UpperCamelCase ) == 0 all_relative_imports.extend(__UpperCamelCase ) return all_relative_imports def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" with open(__UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f: __A = f.read() # Imports of the form `import xxx` __A = re.findall('''^\s*import\s+(\S+)\s*$''' , __UpperCamelCase , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall('''^\s*from\s+(\S+)\s+import''' , __UpperCamelCase , flags=re.MULTILINE ) # Only keep the top-level module __A = [imp.split('''.''' )[0] for imp in imports if not imp.startswith('''.''' )] # Unique-ify and test we got them all __A = list(set(__UpperCamelCase ) ) __A = [] for imp in imports: try: importlib.import_module(__UpperCamelCase ) except ImportError: missing_packages.append(__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ImportError( '''This modeling file requires the following packages that were not found in your environment: ''' f'{", ".join(__UpperCamelCase )}. Run `pip install {" ".join(__UpperCamelCase )}`' ) return get_relative_imports(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" __A = module_path.replace(os.path.sep , '''.''' ) __A = importlib.import_module(__UpperCamelCase ) if class_name is None: return find_pipeline_class(__UpperCamelCase ) return getattr(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" from ..pipelines import DiffusionPipeline __A = dict(inspect.getmembers(__UpperCamelCase , inspect.isclass ) ) __A = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , __UpperCamelCase ) and cls.__module__.split('''.''' )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( f'Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:' f' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in' f' {loaded_module}.' ) __A = cls return pipeline_class def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , ): """simple docstring""" __A = str(__UpperCamelCase ) __A = os.path.join(__UpperCamelCase , __UpperCamelCase ) if os.path.isfile(__UpperCamelCase ): __A = module_file_or_url __A = '''local''' elif pretrained_model_name_or_path.count('''/''' ) == 0: __A = get_diffusers_versions() # cut ".dev0" __A = '''v''' + '''.'''.join(__version__.split('''.''' )[:3] ) # retrieve github version that matches if revision is None: __A = latest_version if latest_version[1:] in available_versions else '''main''' logger.info(f'Defaulting to latest_version: {revision}.' ) elif revision in available_versions: __A = f'v{revision}' elif revision == "main": __A = revision else: raise ValueError( f'`custom_revision`: {revision} does not exist. Please make sure to choose one of' f' {", ".join(available_versions + ["main"] )}.' ) # community pipeline on GitHub __A = COMMUNITY_PIPELINES_URL.format(revision=__UpperCamelCase , pipeline=__UpperCamelCase ) try: __A = cached_download( __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = '''git''' __A = pretrained_model_name_or_path + '''.py''' except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise else: try: # Load from URL or cache if already cached __A = hf_hub_download( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , proxies=__UpperCamelCase , resume_download=__UpperCamelCase , local_files_only=__UpperCamelCase , use_auth_token=__UpperCamelCase , ) __A = os.path.join('''local''' , '''--'''.join(pretrained_model_name_or_path.split('''/''' ) ) ) except EnvironmentError: logger.error(f'Could not locate the {module_file} inside {pretrained_model_name_or_path}.' ) raise # Check we have all the requirements in our environment __A = check_imports(__UpperCamelCase ) # Now we move the module inside our cached dynamic modules. __A = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(__UpperCamelCase ) __A = Path(__UpperCamelCase ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(__UpperCamelCase , submodule_path / module_file ) for module_needed in modules_needed: __A = f'{module_needed}.py' shutil.copy(os.path.join(__UpperCamelCase , __UpperCamelCase ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(__UpperCamelCase , __UpperCamelCase ): __A = use_auth_token elif use_auth_token is True: __A = HfFolder.get_token() else: __A = None __A = model_info(__UpperCamelCase , revision=__UpperCamelCase , token=__UpperCamelCase ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. __A = submodule_path / commit_hash __A = full_submodule + os.path.sep + commit_hash create_dynamic_module(__UpperCamelCase ) if not (submodule_path / module_file).exists(): shutil.copy(__UpperCamelCase , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( __UpperCamelCase , f'{module_needed}.py' , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return os.path.join(__UpperCamelCase , __UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , __UpperCamelCase = False , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = False , **__UpperCamelCase , ): """simple docstring""" __A = get_cached_module_file( __UpperCamelCase , __UpperCamelCase , cache_dir=__UpperCamelCase , force_download=__UpperCamelCase , resume_download=__UpperCamelCase , proxies=__UpperCamelCase , use_auth_token=__UpperCamelCase , revision=__UpperCamelCase , local_files_only=__UpperCamelCase , ) return get_class_in_module(__UpperCamelCase , final_module.replace('''.py''' , '''''' ) )
266
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor UpperCAmelCase__ : int = logging.get_logger(__name__) class lowerCAmelCase_ (_lowerCAmelCase ): """simple docstring""" def __init__(self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" warnings.warn( """The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use MobileViTImageProcessor instead.""" , _lowerCamelCase , ) super().__init__(*_lowerCamelCase , **_lowerCamelCase )
25
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class snake_case ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any, _lowerCamelCase : Optional[int] ): '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''], model_result['''ss'''] ): __A = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sgugger/tiny-distilbert-classification''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, only_pretrain_model=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Any ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, torchscript=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == '''cpu''', '''Cant do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, fpaa=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) # set architectures equal to `None` __A = None __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == '''cpu''', '''Can\'t do half precision''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], fpaa=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = '''sshleifer/tinier_bart''' __A = AutoConfig.from_pretrained(_lowerCamelCase ) __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase, configs=[config] ) __A = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, save_to_csv=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], inference_time_csv_file=os.path.join(_lowerCamelCase, '''inf_time.csv''' ), train_memory_csv_file=os.path.join(_lowerCamelCase, '''train_mem.csv''' ), inference_memory_csv_file=os.path.join(_lowerCamelCase, '''inf_mem.csv''' ), train_time_csv_file=os.path.join(_lowerCamelCase, '''train_time.csv''' ), env_info_csv_file=os.path.join(_lowerCamelCase, '''env.csv''' ), multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) benchmark.run() self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''train_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''env.csv''' ) ).exists() ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' __A = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(_lowerCamelCase : List[Any] ): self.assertTrue(hasattr(_lowerCamelCase, '''sequential''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''cumulative''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''current''' ) ) self.assertTrue(hasattr(_lowerCamelCase, '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: __A = PyTorchBenchmarkArguments( models=[MODEL_ID], training=_lowerCamelCase, inference=_lowerCamelCase, sequence_lengths=[8], batch_sizes=[1], log_filename=os.path.join(_lowerCamelCase, '''log.txt''' ), log_print=_lowerCamelCase, trace_memory_line_by_line=_lowerCamelCase, multi_process=_lowerCamelCase, ) __A = PyTorchBenchmark(_lowerCamelCase ) __A = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_lowerCamelCase, '''log.txt''' ) ).exists() )
266
0
import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase_ = logging.get_logger(__name__) def __magic_name__ ( __a : List[Any] , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = [] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f"encoder.deit.blocks.{i}.norm1.weight", f"encoder.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"encoder.deit.blocks.{i}.norm1.bias", f"encoder.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.attn.proj.weight", f"encoder.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append( (f"encoder.deit.blocks.{i}.attn.proj.bias", f"encoder.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.norm2.weight", f"encoder.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"encoder.deit.blocks.{i}.norm2.bias", f"encoder.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.mlp.fc1.weight", f"encoder.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append( (f"encoder.deit.blocks.{i}.mlp.fc1.bias", f"encoder.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.mlp.fc2.weight", f"encoder.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"encoder.deit.blocks.{i}.mlp.fc2.bias", f"encoder.encoder.layer.{i}.output.dense.bias") ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ("""encoder.deit.cls_token""", """encoder.embeddings.cls_token"""), ("""encoder.deit.pos_embed""", """encoder.embeddings.position_embeddings"""), ("""encoder.deit.patch_embed.proj.weight""", """encoder.embeddings.patch_embeddings.projection.weight"""), ("""encoder.deit.patch_embed.proj.bias""", """encoder.embeddings.patch_embeddings.projection.bias"""), ("""encoder.deit.norm.weight""", """encoder.layernorm.weight"""), ("""encoder.deit.norm.bias""", """encoder.layernorm.bias"""), ] ) return rename_keys def __magic_name__ ( __a : int , __a : List[str] ): '''simple docstring''' for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) UpperCamelCase__ = state_dict.pop(f"encoder.deit.blocks.{i}.attn.qkv.weight" ) UpperCamelCase__ = in_proj_weight[ : encoder_config.hidden_size, : ] UpperCamelCase__ = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] UpperCamelCase__ = in_proj_weight[ -encoder_config.hidden_size :, : ] def __magic_name__ ( __a : List[str] , __a : int , __a : Any ): '''simple docstring''' UpperCamelCase__ = dct.pop(__UpperCamelCase ) UpperCamelCase__ = val def __magic_name__ ( __a : List[Any] ): '''simple docstring''' if "handwritten" in checkpoint_url: UpperCamelCase__ = """https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg""" # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: UpperCamelCase__ = """https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg""" UpperCamelCase__ = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw ).convert("""RGB""" ) return im @torch.no_grad() def __magic_name__ ( __a : int , __a : str ): '''simple docstring''' UpperCamelCase__ = ViTConfig(image_size=384 , qkv_bias=__UpperCamelCase ) UpperCamelCase__ = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: UpperCamelCase__ = 768 elif "large" in checkpoint_url: # use ViT-large encoder UpperCamelCase__ = 1_024 UpperCamelCase__ = 4_096 UpperCamelCase__ = 24 UpperCamelCase__ = 16 UpperCamelCase__ = 1_024 else: raise ValueError("""Should either find \'base\' or \'large\' in checkpoint URL""" ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: UpperCamelCase__ = False UpperCamelCase__ = """relu""" UpperCamelCase__ = 1_024 UpperCamelCase__ = True UpperCamelCase__ = False UpperCamelCase__ = False # load HuggingFace model UpperCamelCase__ = ViTModel(__UpperCamelCase , add_pooling_layer=__UpperCamelCase ) UpperCamelCase__ = TrOCRForCausalLM(__UpperCamelCase ) UpperCamelCase__ = VisionEncoderDecoderModel(encoder=__UpperCamelCase , decoder=__UpperCamelCase ) model.eval() # load state_dict of original model, rename some keys UpperCamelCase__ = torch.hub.load_state_dict_from_url(__UpperCamelCase , map_location="""cpu""" , check_hash=__UpperCamelCase )["""model"""] UpperCamelCase__ = create_rename_keys(__UpperCamelCase , __UpperCamelCase ) for src, dest in rename_keys: rename_key(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) read_in_q_k_v(__UpperCamelCase , __UpperCamelCase ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): UpperCamelCase__ = state_dict.pop(__UpperCamelCase ) if key.startswith("""decoder""" ) and "output_projection" not in key: UpperCamelCase__ = val else: UpperCamelCase__ = val # load state dict model.load_state_dict(__UpperCamelCase ) # Check outputs on an image UpperCamelCase__ = ViTImageProcessor(size=encoder_config.image_size ) UpperCamelCase__ = RobertaTokenizer.from_pretrained("""roberta-large""" ) UpperCamelCase__ = TrOCRProcessor(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase__ = processor(images=prepare_img(__UpperCamelCase ) , return_tensors="""pt""" ).pixel_values # verify logits UpperCamelCase__ = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) UpperCamelCase__ = model(pixel_values=__UpperCamelCase , decoder_input_ids=__UpperCamelCase ) UpperCamelCase__ = outputs.logits UpperCamelCase__ = torch.Size([1, 1, 50_265] ) if "trocr-base-handwritten" in checkpoint_url: UpperCamelCase__ = torch.tensor( [-1.4_502, -4.6_683, -0.5_347, -2.9_291, 9.1_435, -3.0_571, 8.9_764, 1.7_560, 8.7_358, -1.5_311] ) elif "trocr-large-handwritten" in checkpoint_url: UpperCamelCase__ = torch.tensor( [-2.6_437, -1.3_129, -2.2_596, -5.3_455, 6.3_539, 1.7_604, 5.4_991, 1.4_702, 5.6_113, 2.0_170] ) elif "trocr-base-printed" in checkpoint_url: UpperCamelCase__ = torch.tensor( [-5.6_816, -5.8_388, 1.1_398, -6.9_034, 6.8_505, -2.4_393, 1.2_284, -1.0_232, -1.9_661, -3.9_210] ) elif "trocr-large-printed" in checkpoint_url: UpperCamelCase__ = torch.tensor( [-6.0_162, -7.0_959, 4.4_155, -5.1_063, 7.0_468, -3.1_631, 2.6_466, -0.3_081, -0.8_106, -1.7_535] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10] , __UpperCamelCase , atol=1E-3 ), "First elements of logits not as expected" Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) print(f"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(__UpperCamelCase ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_url''', default='''https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt''', type=str, help='''URL to the original PyTorch checkpoint (.pth file).''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) lowerCamelCase_ = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
244
"""simple docstring""" import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast 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 lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : Optional[Any] = PegasusTokenizer A_ : int = PegasusTokenizerFast A_ : Optional[Any] = True A_ : Union[str, Any] = True def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def _SCREAMING_SNAKE_CASE ( self : int, **_lowerCamelCase : List[Any] ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any], _lowerCamelCase : Dict ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = '''</s>''' __A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ), _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ), _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' __A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], '''<pad>''' ) self.assertEqual(vocab_keys[1], '''</s>''' ) self.assertEqual(vocab_keys[-1], '''v''' ) self.assertEqual(len(_lowerCamelCase ), 11_03 ) def _SCREAMING_SNAKE_CASE ( self : int ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size, 11_03 ) def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __A = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' __A = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ): '''simple docstring''' __A = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 __A = '''To ensure a smooth flow of bank resolutions.''' __A = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str], return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _SCREAMING_SNAKE_CASE ( self : Dict ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 1_50, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' # fmt: off __A = {'''input_ids''': [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 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], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 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]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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='''google/bigbird-pegasus-large-arxiv''', revision='''ba85d0851d708441f91440d509690f1ab6353415''', ) @require_sentencepiece @require_tokenizers class snake_case ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' A_ : str = PegasusTokenizer A_ : Union[str, Any] = PegasusTokenizerFast A_ : Any = True A_ : str = True def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(_lowerCamelCase, offset=0, mask_token_sent=_lowerCamelCase, mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _SCREAMING_SNAKE_CASE ( self : str ): '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def _SCREAMING_SNAKE_CASE ( self : Optional[int], **_lowerCamelCase : Dict ): '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname, **_lowerCamelCase ) def _SCREAMING_SNAKE_CASE ( self : List[str], _lowerCamelCase : List[str] ): '''simple docstring''' return ("This is a test", "This is a test") def _SCREAMING_SNAKE_CASE ( self : List[Any] ): '''simple docstring''' __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) __A = rust_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] __A = py_tokenizer([raw_input_str], return_tensors=_lowerCamelCase, add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase, _lowerCamelCase ) @require_torch def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ['''This is going to be way too long.''' * 10_00, '''short example'''] __A = ['''not super long but more than 5 tokens''', '''tiny'''] __A = self._large_tokenizer(_lowerCamelCase, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) __A = self._large_tokenizer( text_target=_lowerCamelCase, max_length=5, padding=_lowerCamelCase, truncation=_lowerCamelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def _SCREAMING_SNAKE_CASE ( self : Tuple ): '''simple docstring''' __A = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) __A = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase, [1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1], )
266
0
'''simple docstring''' from __future__ import annotations from typing import Generic, TypeVar _lowerCamelCase : List[str] = TypeVar("T") class SCREAMING_SNAKE_CASE ( Generic[T] ): """simple docstring""" def __init__( self : Optional[int] , UpperCamelCase__ : T ): """simple docstring""" UpperCamelCase = data UpperCamelCase = self UpperCamelCase = 0 class SCREAMING_SNAKE_CASE ( Generic[T] ): """simple docstring""" def __init__( self : Dict ): """simple docstring""" UpperCamelCase = {} def A ( self : Dict , UpperCamelCase__ : T ): """simple docstring""" UpperCamelCase = DisjointSetTreeNode(_lowerCamelCase ) def A ( self : Optional[int] , UpperCamelCase__ : T ): """simple docstring""" UpperCamelCase = self.map[data] if elem_ref != elem_ref.parent: UpperCamelCase = self.find_set(elem_ref.parent.data ) return elem_ref.parent def A ( self : Any , UpperCamelCase__ : DisjointSetTreeNode[T] , UpperCamelCase__ : DisjointSetTreeNode[T] ): """simple docstring""" if nodea.rank > nodea.rank: UpperCamelCase = nodea else: UpperCamelCase = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def A ( self : Optional[int] , UpperCamelCase__ : T , UpperCamelCase__ : T ): """simple docstring""" self.link(self.find_set(_lowerCamelCase ) , self.find_set(_lowerCamelCase ) ) class SCREAMING_SNAKE_CASE ( Generic[T] ): """simple docstring""" def __init__( self : Dict ): """simple docstring""" UpperCamelCase = {} def A ( self : str , UpperCamelCase__ : T ): """simple docstring""" if node not in self.connections: UpperCamelCase = {} def A ( self : int , UpperCamelCase__ : T , UpperCamelCase__ : T , UpperCamelCase__ : int ): """simple docstring""" self.add_node(_lowerCamelCase ) self.add_node(_lowerCamelCase ) UpperCamelCase = weight UpperCamelCase = weight def A ( self : Any ): """simple docstring""" UpperCamelCase = [] UpperCamelCase = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda UpperCamelCase__ : x[2] ) # creating the disjoint set UpperCamelCase = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(_lowerCamelCase ) # MST generation UpperCamelCase = 0 UpperCamelCase = 0 UpperCamelCase = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: UpperCamelCase , UpperCamelCase , UpperCamelCase = edges[index] index += 1 UpperCamelCase = disjoint_set.find_set(_lowerCamelCase ) UpperCamelCase = disjoint_set.find_set(_lowerCamelCase ) if parent_u != parent_v: num_edges += 1 graph.add_edge(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) disjoint_set.union(_lowerCamelCase , _lowerCamelCase ) return graph
28
"""simple docstring""" import re def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return [char.split() for char in re.split(r'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" try: __A = split_input(__UpperCamelCase ) if upper: __A = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __A = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return to_simple_case(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" try: __A = to_simple_case(__UpperCamelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''_''' ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
266
0
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets __UpperCamelCase : str = '''\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n''' __UpperCamelCase : Optional[Any] = '''\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n''' __UpperCamelCase : Dict = '''\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): """simple docstring""" def __lowerCAmelCase ( self : Any ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='''https://github.com/krishnap25/mauve''' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { '''predictions''': datasets.Value('''string''' ,id='''sequence''' ), '''references''': datasets.Value('''string''' ,id='''sequence''' ), } ) ,codebase_urls=['''https://github.com/krishnap25/mauve'''] ,reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] ,) def __lowerCAmelCase ( self : int ,lowercase_ : str ,lowercase_ : Optional[Any] ,lowercase_ : Any=None ,lowercase_ : Tuple=None ,lowercase_ : Optional[Any]=None ,lowercase_ : Union[str, Any]=None ,lowercase_ : str="auto" ,lowercase_ : Union[str, Any]=-1 ,lowercase_ : List[str]=0.9 ,lowercase_ : int=5 ,lowercase_ : Tuple=5_0_0 ,lowercase_ : Union[str, Any]="gpt2-large" ,lowercase_ : int=-1 ,lowercase_ : Union[str, Any]=1_0_2_4 ,lowercase_ : Union[str, Any]=2_5 ,lowercase_ : str=5 ,lowercase_ : Any=True ,lowercase_ : Union[str, Any]=2_5 ,): lowerCAmelCase__ : List[str] = compute_mauve( p_text=_lowerCamelCase ,q_text=_lowerCamelCase ,p_features=_lowerCamelCase ,q_features=_lowerCamelCase ,p_tokens=_lowerCamelCase ,q_tokens=_lowerCamelCase ,num_buckets=_lowerCamelCase ,pca_max_data=_lowerCamelCase ,kmeans_explained_var=_lowerCamelCase ,kmeans_num_redo=_lowerCamelCase ,kmeans_max_iter=_lowerCamelCase ,featurize_model_name=_lowerCamelCase ,device_id=_lowerCamelCase ,max_text_length=_lowerCamelCase ,divergence_curve_discretization_size=_lowerCamelCase ,mauve_scaling_factor=_lowerCamelCase ,verbose=_lowerCamelCase ,seed=_lowerCamelCase ,) return out
106
"""simple docstring""" from __future__ import annotations class snake_case : '''simple docstring''' def __init__( self : int, _lowerCamelCase : List[Any]=None ): '''simple docstring''' __A = data __A = None def __repr__( self : Union[str, Any] ): '''simple docstring''' __A = [] __A = self while temp: string_rep.append(f'{temp.data}' ) __A = temp.next return "->".join(_lowerCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if not elements_list: raise Exception('''The Elements List is empty''' ) __A = __A = Node(elements_list[0] ) for i in range(1 , len(__UpperCamelCase ) ): __A = Node(elements_list[i] ) __A = current.next return head def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" if head_node is not None and isinstance(__UpperCamelCase , __UpperCamelCase ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase ( ): """simple docstring""" from doctest import testmod testmod() __A = make_linked_list([1_4, 5_2, 1_4, 1_2, 4_3] ) print('''Linked List:''' ) print(__UpperCamelCase ) print('''Elements in Reverse:''' ) print_reverse(__UpperCamelCase ) if __name__ == "__main__": main()
266
0
from __future__ import annotations import os from collections.abc import Mapping a_ = tuple[int, int] class _lowercase : def __init__( self : Optional[Any] , snake_case : set[int] , snake_case : Mapping[EdgeT, int] ) -> int: """simple docstring""" UpperCamelCase_ : List[Any] = vertices UpperCamelCase_ : Union[str, Any] = { (min(_lowerCamelCase ), max(_lowerCamelCase )): weight for edge, weight in edges.items() } def SCREAMING_SNAKE_CASE__ ( self : List[str] , snake_case : EdgeT , snake_case : int ) -> Union[str, Any]: """simple docstring""" self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) UpperCamelCase_ : List[str] = weight def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ : Optional[int] = Graph({min(self.vertices )} , {} ) UpperCamelCase_ : int = 4_2 UpperCamelCase_ : Any = 4_2 UpperCamelCase_ : Tuple = 4_2 UpperCamelCase_ : Optional[int] = 4_2 while len(subgraph.vertices ) < len(self.vertices ): UpperCamelCase_ : List[str] = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: UpperCamelCase_ : List[str] = edge UpperCamelCase_ : Tuple = weight subgraph.add_edge(_lowerCamelCase , _lowerCamelCase ) return subgraph def __lowercase ( lowerCamelCase : Union[str, Any] = "p107_network.txt" ): UpperCamelCase_ : Optional[int] = os.path.abspath(os.path.dirname(__UpperCamelCase ) ) UpperCamelCase_ : Optional[Any] = os.path.join(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase_ : str = {} UpperCamelCase_ : Tuple = 42 UpperCamelCase_ : Optional[Any] = 42 UpperCamelCase_ : Tuple = 42 with open(__UpperCamelCase ) as f: UpperCamelCase_ : str = f.read().strip().split('\n' ) UpperCamelCase_ : List[str] = [line.split(',' ) for line in data] for edgea in range(1 , len(__UpperCamelCase ) ): for edgea in range(__UpperCamelCase ): if adjaceny_matrix[edgea][edgea] != "-": UpperCamelCase_ : List[Any] = int(adjaceny_matrix[edgea][edgea] ) UpperCamelCase_ : int = Graph(set(range(len(__UpperCamelCase ) ) ) , __UpperCamelCase ) UpperCamelCase_ : Union[str, Any] = graph.prims_algorithm() UpperCamelCase_ : List[str] = sum(graph.edges.values() ) UpperCamelCase_ : Optional[Any] = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F"""{solution() = }""")
175
"""simple docstring""" from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging lowercase_ = logging.get_logger(__name__) class snake_case ( _lowerCAmelCase ): '''simple docstring''' A_ : int = ["input_features", "attention_mask"] def __init__( self : Optional[Any], _lowerCamelCase : Union[str, Any]=80, _lowerCamelCase : int=1_60_00, _lowerCamelCase : Any=80, _lowerCamelCase : List[str]=0.0, _lowerCamelCase : int=True, _lowerCamelCase : Optional[Any]=True, _lowerCamelCase : Optional[int]=True, **_lowerCamelCase : List[str], ): '''simple docstring''' super().__init__(feature_size=_lowerCamelCase, sampling_rate=_lowerCamelCase, padding_value=_lowerCamelCase, **_lowerCamelCase ) __A = num_mel_bins __A = do_ceptral_normalize __A = normalize_means __A = normalize_vars __A = True def _SCREAMING_SNAKE_CASE ( self : Dict, _lowerCamelCase : np.ndarray, ): '''simple docstring''' __A = waveform * (2**15) # Kaldi compliance: 16-bit signed integers __A = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ) __A = ta_kaldi.fbank(_lowerCamelCase, num_mel_bins=self.num_mel_bins, sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : np.ndarray, _lowerCamelCase : int, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : Optional[bool] = True, _lowerCamelCase : float = 0.0, ): '''simple docstring''' # make sure we normalize float32 arrays if normalize_means: __A = x[:input_length].mean(axis=0 ) __A = np.subtract(_lowerCamelCase, _lowerCamelCase ) if normalize_vars: __A = x[:input_length].std(axis=0 ) __A = np.divide(_lowerCamelCase, _lowerCamelCase ) if input_length < x.shape[0]: __A = padding_value # make sure array is in float32 __A = x.astype(np.floataa ) return x def _SCREAMING_SNAKE_CASE ( self : str, _lowerCamelCase : List[np.ndarray], _lowerCamelCase : Optional[np.ndarray] = None ): '''simple docstring''' __A = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(_lowerCamelCase, _lowerCamelCase, self.normalize_means, self.normalize_vars, self.padding_value ) for x, n in zip(_lowerCamelCase, _lowerCamelCase ) ] def __call__( self : Optional[Any], _lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], _lowerCamelCase : Union[bool, str, PaddingStrategy] = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : bool = False, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[Union[str, TensorType]] = None, _lowerCamelCase : Optional[int] = None, _lowerCamelCase : Optional[bool] = None, **_lowerCamelCase : Optional[Any], ): '''simple docstring''' if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the `sampling_rate` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) __A = isinstance(_lowerCamelCase, np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) __A = is_batched_numpy or ( isinstance(_lowerCamelCase, (list, tuple) ) and (isinstance(raw_speech[0], (np.ndarray, tuple, list) )) ) if is_batched: __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(_lowerCamelCase, np.ndarray ): __A = np.asarray(_lowerCamelCase, dtype=np.floataa ) elif isinstance(_lowerCamelCase, np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __A = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __A = [raw_speech] # extract fbank features __A = [self._extract_fbank_features(_lowerCamelCase ) for waveform in raw_speech] # convert into correct format for padding __A = BatchFeature({'''input_features''': features} ) __A = self.pad( _lowerCamelCase, padding=_lowerCamelCase, max_length=_lowerCamelCase, truncation=_lowerCamelCase, pad_to_multiple_of=_lowerCamelCase, return_attention_mask=_lowerCamelCase, **_lowerCamelCase, ) # make sure list is in array format __A = padded_inputs.get('''input_features''' ) if isinstance(input_features[0], _lowerCamelCase ): __A = [np.asarray(_lowerCamelCase, dtype=np.floataa ) for feature in input_features] __A = padded_inputs.get('''attention_mask''' ) if attention_mask is not None: __A = [np.asarray(_lowerCamelCase, dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: __A = ( np.array(_lowerCamelCase, dtype=np.intaa ) if self._get_padding_strategies(_lowerCamelCase, max_length=_lowerCamelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) __A = self.normalize( padded_inputs['''input_features'''], attention_mask=_lowerCamelCase ) if return_tensors is not None: __A = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs
266
0