code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' def a_ ( lowerCamelCase : str ): return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
4
"""simple docstring""" import re def UpperCamelCase_ ( lowerCAmelCase__ : str ) -> list: """simple docstring""" return [char.split() for char in re.split(R'[^ a-z A-Z 0-9 \s]' , str_ )] def UpperCamelCase_ ( lowerCAmelCase__ : str ) -> str: """simple docstring""" lowerCAmelCase_ : str = split_input(str_ ) return "".join( [''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def UpperCamelCase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : bool , lowerCAmelCase__ : str ) -> str: """simple docstring""" try: lowerCAmelCase_ : int = split_input(lowerCAmelCase__ ) if upper: lowerCAmelCase_ : Optional[int] = ''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: lowerCAmelCase_ : Any = ''.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 UpperCamelCase_ ( lowerCAmelCase__ : str ) -> str: """simple docstring""" return to_simple_case(lowerCAmelCase__ ) def UpperCamelCase_ ( lowerCAmelCase__ : str ) -> str: """simple docstring""" try: lowerCAmelCase_ : Dict = to_simple_case(lowerCAmelCase__ ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def UpperCamelCase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : bool ) -> str: """simple docstring""" return to_complex_case(lowerCAmelCase__ , lowerCAmelCase__ , '_' ) def UpperCamelCase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : bool ) -> str: """simple docstring""" return to_complex_case(lowerCAmelCase__ , lowerCAmelCase__ , '-' ) if __name__ == "__main__": __import__("""doctest""").testmod()
224
0
'''simple docstring''' import warnings from .generation import TFGenerationMixin class SCREAMING_SNAKE_CASE (a__ ): # warning at import time warnings.warn( '''Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will ''' '''be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead.''' , a__ , )
190
'''simple docstring''' from __future__ import annotations from math import gcd def _lowerCAmelCase ( __snake_case : int , __snake_case : int = 2 , __snake_case : int = 1 , __snake_case : int = 3 , ) -> int | None: # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError('The input value cannot be less than 2' ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(__snake_case : int , __snake_case : int , __snake_case : int ) -> int: return (pow(__snake_case , 2 ) + step) % modulus for _ in range(__snake_case ): # These track the position within the cycle detection logic. __A : int = seed __A : Union[str, Any] = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. __A : List[Any] = rand_fn(__snake_case , __snake_case , __snake_case ) __A : Optional[Any] = rand_fn(__snake_case , __snake_case , __snake_case ) __A : Any = rand_fn(__snake_case , __snake_case , __snake_case ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. __A : Optional[int] = gcd(hare - tortoise , __snake_case ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. __A : Union[str, Any] = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse lowercase__ : str = argparse.ArgumentParser() parser.add_argument( '''num''', type=int, help='''The value to find a divisor of''', ) parser.add_argument( '''--attempts''', type=int, default=3, help='''The number of attempts before giving up''', ) lowercase__ : Optional[int] = parser.parse_args() lowercase__ : int = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f"""{args.num} is probably prime""") else: lowercase__ : List[str] = args.num // divisor print(f"""{args.num} = {divisor} * {quotient}""")
190
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/config.json", "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/config.json" # See all FNet models at https://huggingface.co/models?filter=fnet } class A ( _UpperCAmelCase ): """simple docstring""" lowerCamelCase = 'fnet' def __init__( self : Dict,lowercase_ : Optional[Any]=3_2_0_0_0,lowercase_ : Optional[Any]=7_6_8,lowercase_ : Dict=1_2,lowercase_ : int=3_0_7_2,lowercase_ : Any="gelu_new",lowercase_ : Optional[int]=0.1,lowercase_ : Optional[Any]=5_1_2,lowercase_ : Dict=4,lowercase_ : Union[str, Any]=0.02,lowercase_ : List[Any]=1E-12,lowercase_ : str=False,lowercase_ : List[str]=5_1_2,lowercase_ : Optional[int]=3,lowercase_ : Optional[int]=1,lowercase_ : List[Any]=2,**lowercase_ : int,)-> List[Any]: '''simple docstring''' super().__init__(pad_token_id=lowercase_,bos_token_id=lowercase_,eos_token_id=lowercase_,**lowercase_ ) A__ = vocab_size A__ = max_position_embeddings A__ = hidden_size A__ = num_hidden_layers A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = initializer_range A__ = type_vocab_size A__ = layer_norm_eps A__ = use_tpu_fourier_optimizations A__ = tpu_short_seq_length
7
import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir("fixtures/spiece.model") @require_sentencepiece @require_tokenizers class A ( _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = AlbertTokenizer lowerCamelCase = AlbertTokenizerFast lowerCamelCase = True lowerCamelCase = True lowerCamelCase = True def snake_case__ ( self : Dict )-> Any: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing A__ = AlbertTokenizer(lowercase_ ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case__ ( self : List[str],lowercase_ : str )-> Any: '''simple docstring''' A__ = 'this is a test' A__ = 'this is a test' return input_text, output_text def snake_case__ ( self : List[Any] )-> Optional[int]: '''simple docstring''' A__ = '<pad>' A__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_ ),lowercase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_ ),lowercase_ ) def snake_case__ ( self : List[str] )-> str: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0],'<pad>' ) self.assertEqual(vocab_keys[1],'<unk>' ) self.assertEqual(vocab_keys[-1],'▁eloquent' ) self.assertEqual(len(lowercase_ ),3_0_0_0_0 ) def snake_case__ ( self : int )-> List[Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size,3_0_0_0_0 ) def snake_case__ ( self : Union[str, Any] )-> List[Any]: '''simple docstring''' if not self.test_rust_tokenizer: return A__ = self.get_tokenizer() A__ = self.get_rust_tokenizer() A__ = 'I was born in 92000, and this is falsé.' A__ = tokenizer.tokenize(lowercase_ ) A__ = rust_tokenizer.tokenize(lowercase_ ) self.assertListEqual(lowercase_,lowercase_ ) A__ = tokenizer.encode(lowercase_,add_special_tokens=lowercase_ ) A__ = rust_tokenizer.encode(lowercase_,add_special_tokens=lowercase_ ) self.assertListEqual(lowercase_,lowercase_ ) A__ = self.get_rust_tokenizer() A__ = tokenizer.encode(lowercase_ ) A__ = rust_tokenizer.encode(lowercase_ ) self.assertListEqual(lowercase_,lowercase_ ) def snake_case__ ( self : int )-> int: '''simple docstring''' A__ = AlbertTokenizer(lowercase_,keep_accents=lowercase_ ) A__ = tokenizer.tokenize('This is a test' ) self.assertListEqual(lowercase_,['▁this', '▁is', '▁a', '▁test'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase_ ),[4_8, 2_5, 2_1, 1_2_8_9] ) A__ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowercase_,['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.'] ) A__ = tokenizer.convert_tokens_to_ids(lowercase_ ) self.assertListEqual(lowercase_,[3_1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] ) A__ = tokenizer.convert_ids_to_tokens(lowercase_ ) self.assertListEqual( lowercase_,['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.'],) def snake_case__ ( self : Union[str, Any] )-> str: '''simple docstring''' A__ = AlbertTokenizer(lowercase_ ) A__ = tokenizer.encode('sequence builders' ) A__ = tokenizer.encode('multi-sequence build' ) A__ = tokenizer.build_inputs_with_special_tokens(lowercase_ ) A__ = tokenizer.build_inputs_with_special_tokens(lowercase_,lowercase_ ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ] @slow def snake_case__ ( self : Any )-> Tuple: '''simple docstring''' A__ = {'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'input_ids': [[2, 2_1_9_7_0, 1_3, 5, 6_0_9_2, 1_6_7, 2_8, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 7_0_2_8, 1_2_0_5_1, 1_8, 1_7, 7_1_0_3, 2_1_5_3, 6_7_3, 8, 3_5_1_5, 1_8_6_8_4, 8, 4_4_6_1, 6, 1_9_2_7, 2_9_7, 8, 1_2_0_6_0, 2_6_0_7, 1_8, 1_3, 5, 4_4_6_1, 1_5, 1_0_5_3_8, 3_8, 8, 1_3_5, 1_5, 8_2_2, 5_8, 1_5, 9_9_3, 1_0_3_6_3, 1_5, 1_4_6_0, 8_0_0_5, 4_4_6_1, 1_5, 9_9_3, 2_5_5, 2_3_2_8, 9, 9, 9, 6, 2_6, 1_1_1_2, 8_1_6, 3_2_6_0, 1_3, 5, 1_0_3, 2_3_7_7, 6, 1_7, 1_1_1_2, 8_1_6, 2_7_8_2, 1_3, 5, 1_0_3, 1_0_6_4_1, 6, 2_9, 8_4, 2_5_1_2, 2_4_3_0, 7_8_2, 1_8_6_8_4, 2_7_6_1, 1_9, 8_0_8, 2_4_3_0, 2_5_5_6, 1_7, 8_5_5, 1_4_8_0, 9_4_7_7, 4_0_9_1, 1_2_8, 1_1_7_1_2, 1_5, 7_1_0_3, 2_1_5_3, 6_7_3, 1_7, 2_4_8_8_3, 9_9_9_0, 9, 3], [2, 1_1_5_0_2, 2_5, 1_0_0_6, 2_0, 7_8_2, 8, 1_1_8_0_9, 8_5_5, 1_7_3_2, 1_9_3_9_3, 1_8_6_6_7, 3_7, 3_6_7, 2_1_0_1_8, 6_9, 1_8_5_4, 3_4, 1_1_8_6_0, 1_9_1_2_4, 2_7, 1_5_6, 2_2_5, 1_7, 1_9_3, 4_1_4_1, 1_9, 6_5, 9_1_2_4, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 1_4, 2_2_3_1, 8_8_6, 2_3_8_5, 1_7_6_5_9, 8_4, 1_4, 1_6_7_9_2, 1_9_5_2, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase_,model_name='albert-base-v2',revision='6b6560eaf5ff2e250b00c50f380c5389a9c2d82e',)
7
1
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint SCREAMING_SNAKE_CASE_:List[str] = { """169M""": 12, """430M""": 24, """1B5""": 24, """3B""": 32, """7B""": 32, """14B""": 40, } SCREAMING_SNAKE_CASE_:str = { """169M""": 768, """430M""": 1_024, """1B5""": 2_048, """3B""": 2_560, """7B""": 4_096, """14B""": 5_120, } def __UpperCamelCase ( _lowerCAmelCase ) -> Union[str, Any]: """simple docstring""" A : str = list(state_dict.keys() ) for name in state_dict_keys: A : Optional[Any] = state_dict.pop(_lowerCAmelCase ) # emb -> embedding if name.startswith("""emb.""" ): A : Tuple = name.replace("""emb.""" , """embeddings.""" ) # ln_0 -> pre_ln (only present at block 0) if name.startswith("""blocks.0.ln0""" ): A : Dict = name.replace("""blocks.0.ln0""" , """blocks.0.pre_ln""" ) # att -> attention A : Union[str, Any] = re.sub(R"""blocks\.(\d+)\.att""" , R"""blocks.\1.attention""" , _lowerCAmelCase ) # ffn -> feed_forward A : Optional[int] = re.sub(R"""blocks\.(\d+)\.ffn""" , R"""blocks.\1.feed_forward""" , _lowerCAmelCase ) # time_mix_k -> time_mix_key and reshape if name.endswith(""".time_mix_k""" ): A : Tuple = name.replace(""".time_mix_k""" , """.time_mix_key""" ) # time_mix_v -> time_mix_value and reshape if name.endswith(""".time_mix_v""" ): A : Tuple = name.replace(""".time_mix_v""" , """.time_mix_value""" ) # time_mix_r -> time_mix_key and reshape if name.endswith(""".time_mix_r""" ): A : Optional[Any] = name.replace(""".time_mix_r""" , """.time_mix_receptance""" ) if name != "head.weight": A : List[Any] = """rwkv.""" + name A : Optional[int] = weight return state_dict def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=False , _lowerCAmelCase=None ) -> Dict: """simple docstring""" if tokenizer_file is None: print("""No `--tokenizer_file` provided, we will use the default tokenizer.""" ) A : Optional[int] = 5_0277 A : Dict = AutoTokenizer.from_pretrained("""EleutherAI/gpt-neox-20b""" ) else: A : List[Any] = PreTrainedTokenizerFast(tokenizer_file=_lowerCAmelCase ) A : Tuple = len(_lowerCAmelCase ) tokenizer.save_pretrained(_lowerCAmelCase ) # 2. Build the config A : List[str] = list(NUM_HIDDEN_LAYERS_MAPPING.keys() ) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: A : Tuple = candidate break if size is None: raise ValueError("""Could not infer the size, please provide it with the `--size` argument.""" ) if size not in possible_sizes: raise ValueError(f'''`size` should be one of {possible_sizes}, got {size}.''' ) A : int = RwkvConfig( vocab_size=_lowerCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_lowerCAmelCase ) # 3. Download model file then convert state_dict A : Dict = hf_hub_download(_lowerCAmelCase , _lowerCAmelCase ) A : Any = torch.load(_lowerCAmelCase , map_location="""cpu""" ) A : str = convert_state_dict(_lowerCAmelCase ) # 4. Split in shards and save A , A : Any = shard_checkpoint(_lowerCAmelCase ) for shard_file, shard in shards.items(): torch.save(_lowerCAmelCase , os.path.join(_lowerCAmelCase , _lowerCAmelCase ) ) if index is not None: A : Tuple = os.path.join(_lowerCAmelCase , _lowerCAmelCase ) # Save the index as well with open(_lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: A : int = json.dumps(_lowerCAmelCase , indent=2 , sort_keys=_lowerCAmelCase ) + """\n""" f.write(_lowerCAmelCase ) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( """Cleaning up shards. This may error with an OOM error, it this is the case don't worry you still have converted the model.""" ) A : str = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: A : Any = torch.load(os.path.join(_lowerCAmelCase , _lowerCAmelCase ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_lowerCAmelCase , _lowerCAmelCase ) ) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError("""Please provide a `model_name` to push the model to the Hub.""" ) A : Any = AutoModelForCausalLM.from_pretrained(_lowerCAmelCase ) model.push_to_hub(_lowerCAmelCase , max_shard_size="""2GB""" ) tokenizer.push_to_hub(_lowerCAmelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_:Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--repo_id""", default=None, type=str, required=True, help="""Repo ID from which to pull the checkpoint.""" ) parser.add_argument( """--checkpoint_file""", default=None, type=str, required=True, help="""Name of the checkpoint file in the repo.""" ) parser.add_argument( """--output_dir""", default=None, type=str, required=True, help="""Where to save the converted model.""" ) parser.add_argument( """--tokenizer_file""", default=None, type=str, help="""Path to the tokenizer file to use (if not provided, only the model is converted).""", ) parser.add_argument( """--size""", default=None, type=str, help="""Size of the model. Will be inferred from the `checkpoint_file` if not passed.""", ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Push to the Hub the converted model.""", ) parser.add_argument( """--model_name""", default=None, type=str, help="""Name of the pushed model on the Hub, including the username / organization.""", ) SCREAMING_SNAKE_CASE_:int = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
115
import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py SCREAMING_SNAKE_CASE_:Any = """src/diffusers""" # Matches is_xxx_available() SCREAMING_SNAKE_CASE_:Optional[Any] = re.compile(R"""is\_([a-z_]*)_available\(\)""") # Matches from xxx import bla SCREAMING_SNAKE_CASE_:Union[str, Any] = re.compile(R"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") SCREAMING_SNAKE_CASE_:List[Any] = """ {0} = None """ SCREAMING_SNAKE_CASE_:Optional[Any] = """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) """ SCREAMING_SNAKE_CASE_:int = """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ def __UpperCamelCase ( _lowerCAmelCase ) -> Tuple: """simple docstring""" A : Union[str, Any] = _re_backend.findall(_lowerCAmelCase ) if len(_lowerCAmelCase ) == 0: return None return "_and_".join(_lowerCAmelCase ) def __UpperCamelCase ( ) -> str: """simple docstring""" with open(os.path.join(_lowerCAmelCase , """__init__.py""" ) , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: A : Dict = f.readlines() # Get to the point we do the actual imports for type checking A : Dict = 0 A : List[Any] = {} # Go through the end of the file while line_index < len(_lowerCAmelCase ): # If the line contains is_backend_available, we grab all objects associated with the `else` block A : Optional[int] = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith("""else:""" ): line_index += 1 line_index += 1 A : str = [] # Until we unindent, add backend objects to the list while line_index < len(_lowerCAmelCase ) and len(lines[line_index] ) > 1: A : Tuple = lines[line_index] A : List[str] = _re_single_line_import.search(_lowerCAmelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(_lowerCAmelCase ) > 0: A : List[str] = objects else: line_index += 1 return backend_specific_objects def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase ) -> str: """simple docstring""" if name.isupper(): return DUMMY_CONSTANT.format(_lowerCAmelCase ) elif name.islower(): return DUMMY_FUNCTION.format(_lowerCAmelCase , _lowerCAmelCase ) else: return DUMMY_CLASS.format(_lowerCAmelCase , _lowerCAmelCase ) def __UpperCamelCase ( _lowerCAmelCase=None ) -> Tuple: """simple docstring""" if backend_specific_objects is None: A : Union[str, Any] = read_init() # For special correspondence backend to module name as used in the function requires_modulename A : Any = {} for backend, objects in backend_specific_objects.items(): A : str = """[""" + """, """.join(f'''"{b}"''' for b in backend.split("""_and_""" ) ) + """]""" A : Any = """# This file is autogenerated by the command `make fix-copies`, do not edit.\n""" dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(_lowerCAmelCase , _lowerCAmelCase ) for o in objects] ) A : Optional[Any] = dummy_file return dummy_files def __UpperCamelCase ( _lowerCAmelCase=False ) -> str: """simple docstring""" A : str = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py A : List[str] = {"""torch""": """pt"""} # Locate actual dummy modules and read their content. A : Union[str, Any] = os.path.join(_lowerCAmelCase , """utils""" ) A : Any = { backend: os.path.join(_lowerCAmelCase , f'''dummy_{short_names.get(_lowerCAmelCase , _lowerCAmelCase )}_objects.py''' ) for backend in dummy_files.keys() } A : List[Any] = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(_lowerCAmelCase ): with open(_lowerCAmelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: A : Dict = f.read() else: A : str = """""" for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( f'''Updating diffusers.utils.dummy_{short_names.get(_lowerCAmelCase , _lowerCAmelCase )}_objects.py as the main ''' """__init__ has new objects.""" ) with open(dummy_file_paths[backend] , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(dummy_files[backend] ) else: raise ValueError( """The main __init__ has objects that are not present in """ f'''diffusers.utils.dummy_{short_names.get(_lowerCAmelCase , _lowerCAmelCase )}_objects.py. Run `make fix-copies` ''' """to fix this.""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_:List[Any] = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") SCREAMING_SNAKE_CASE_:Any = parser.parse_args() check_dummies(args.fix_and_overwrite)
115
1
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @property def _a ( self ) -> List[str]: torch.manual_seed(0 ) __UpperCamelCase =UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model def _a ( self ) -> Optional[int]: __UpperCamelCase =self.dummy_uncond_unet __UpperCamelCase =KarrasVeScheduler() __UpperCamelCase =KarrasVePipeline(unet=A_ , scheduler=A_ ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =torch.manual_seed(0 ) __UpperCamelCase =pipe(num_inference_steps=2 , generator=A_ , output_type='numpy' ).images __UpperCamelCase =torch.manual_seed(0 ) __UpperCamelCase =pipe(num_inference_steps=2 , generator=A_ , output_type='numpy' , return_dict=A_ )[0] __UpperCamelCase =image[0, -3:, -3:, -1] __UpperCamelCase =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCamelCase =np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Union[str, Any]: __UpperCamelCase ='google/ncsnpp-celebahq-256' __UpperCamelCase =UNetaDModel.from_pretrained(A_ ) __UpperCamelCase =KarrasVeScheduler() __UpperCamelCase =KarrasVePipeline(unet=A_ , scheduler=A_ ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =torch.manual_seed(0 ) __UpperCamelCase =pipe(num_inference_steps=20 , generator=A_ , output_type='numpy' ).images __UpperCamelCase =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __UpperCamelCase =np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
62
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
1
"""simple docstring""" from __future__ import annotations from collections.abc import Generator def __lowercase ( ) ->Generator[int, None, None]: '''simple docstring''' __A : dict[int, int] = {} __A : Dict = 2 while True: __A : List[str] = factor_map.pop(snake_case_ ,snake_case_ ) if factor: __A : List[str] = factor + prime while x in factor_map: x += factor __A : List[Any] = factor else: __A : Dict = prime yield prime prime += 1 def __lowercase ( snake_case_ : float = 1e10 ) ->int: '''simple docstring''' __A : Tuple = sieve() __A : int = 1 while True: __A : Optional[Any] = next(snake_case_ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(snake_case_ ) n += 2 if __name__ == "__main__": print(solution())
291
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def __lowercase ( snake_case_ : int ) ->str: '''simple docstring''' if not isinstance(snake_case_ ,snake_case_ ): raise TypeError('''Undefined for non-integers''' ) elif precision < 1: raise ValueError('''Undefined for non-natural numbers''' ) __A : int = precision __A : Tuple = ceil(precision / 14 ) __A : Dict = 426880 * Decimal(10005 ).sqrt() __A : Optional[Any] = 1 __A : int = 13591409 __A : Optional[int] = Decimal(snake_case_ ) for k in range(1 ,snake_case_ ): __A : int = factorial(6 * k ) // (factorial(3 * k ) * factorial(snake_case_ ) ** 3) linear_term += 545140134 exponential_term *= -262537412640768000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": a_ = 50 print(f'''The first {n} digits of pi is: {pi(n)}''')
291
1
"""simple docstring""" import unittest from typing import Dict, List, Optional, Union 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 BridgeTowerImageProcessor class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , __a , __a = True , __a = None , __a = 32 , __a = True , __a = 1 / 2_55 , __a = True , __a = True , __a = [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , __a = [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , __a = True , __a=7 , __a=30 , __a=4_00 , __a=3 , ): __lowerCAmelCase = parent __lowerCAmelCase = do_resize __lowerCAmelCase = size if size is not None else {"shortest_edge": 2_88} __lowerCAmelCase = size_divisor __lowerCAmelCase = do_rescale __lowerCAmelCase = rescale_factor __lowerCAmelCase = do_normalize __lowerCAmelCase = do_center_crop __lowerCAmelCase = image_mean __lowerCAmelCase = image_std __lowerCAmelCase = do_pad __lowerCAmelCase = batch_size __lowerCAmelCase = num_channels __lowerCAmelCase = min_resolution __lowerCAmelCase = max_resolution def snake_case ( self ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def snake_case ( self , __a , __a=False ): if not batched: __lowerCAmelCase = self.size["shortest_edge"] __lowerCAmelCase = image_inputs[0] if isinstance(__a , Image.Image ): __lowerCAmelCase , __lowerCAmelCase = image.size else: __lowerCAmelCase , __lowerCAmelCase = image.shape[1], image.shape[2] __lowerCAmelCase = size / min(__a , __a ) if h < w: __lowerCAmelCase , __lowerCAmelCase = size, scale * w else: __lowerCAmelCase , __lowerCAmelCase = scale * h, size __lowerCAmelCase = int((13_33 / 8_00) * size ) if max(__a , __a ) > max_size: __lowerCAmelCase = max_size / max(__a , __a ) __lowerCAmelCase = newh * scale __lowerCAmelCase = neww * scale __lowerCAmelCase , __lowerCAmelCase = int(newh + 0.5 ), int(neww + 0.5 ) __lowerCAmelCase , __lowerCAmelCase = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: __lowerCAmelCase = [] for image in image_inputs: __lowerCAmelCase , __lowerCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCAmelCase = max(__a , key=lambda __a : item[0] )[0] __lowerCAmelCase = max(__a , key=lambda __a : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _UpperCamelCase ( lowerCAmelCase__ ,unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : List[str] =BridgeTowerImageProcessor if is_vision_available() else None def snake_case ( self ): __lowerCAmelCase = BridgeTowerImageProcessingTester(self ) @property def snake_case ( self ): return self.image_processor_tester.prepare_image_processor_dict() def snake_case ( self ): __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , "image_mean" ) ) self.assertTrue(hasattr(__a , "image_std" ) ) self.assertTrue(hasattr(__a , "do_normalize" ) ) self.assertTrue(hasattr(__a , "do_resize" ) ) self.assertTrue(hasattr(__a , "size" ) ) self.assertTrue(hasattr(__a , "size_divisor" ) ) def snake_case ( self ): pass def snake_case ( self ): # Initialize image processor __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(__a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase = image_processing(__a , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(__a , batched=__a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def snake_case ( self ): # Initialize image processor __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a ) for image in image_inputs: self.assertIsInstance(__a , np.ndarray ) # Test not batched input __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(__a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase = image_processing(__a , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(__a , batched=__a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def snake_case ( self ): # Initialize image processor __lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a ) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor ) # Test not batched input __lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(__a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase = image_processing(__a , return_tensors="pt" ).pixel_values __lowerCAmelCase , __lowerCAmelCase = self.image_processor_tester.get_expected_values(__a , batched=__a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
57
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __A = logging.get_logger(__name__) if is_vision_available(): import PIL class lowerCamelCase__ ( lowerCamelCase_ ): a__ : Union[str, Any] = ["""pixel_values"""] def __init__( self , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = 1 / 255 , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = True , **SCREAMING_SNAKE_CASE , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) snake_case : int = size if size is not None else {"shortest_edge": 224} snake_case : int = get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) snake_case : List[str] = crop_size if crop_size is not None else {"height": 224, "width": 224} snake_case : Tuple = get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE , param_name="crop_size" ) snake_case : Dict = do_resize snake_case : Optional[int] = size snake_case : int = resample snake_case : Union[str, Any] = do_center_crop snake_case : Dict = crop_size snake_case : Dict = do_rescale snake_case : Any = rescale_factor snake_case : Tuple = do_normalize snake_case : int = image_mean if image_mean is not None else OPENAI_CLIP_MEAN snake_case : Tuple = image_std if image_std is not None else OPENAI_CLIP_STD snake_case : Tuple = do_convert_rgb def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ): """simple docstring""" snake_case : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size: raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) snake_case : Dict = get_resize_output_image_size(SCREAMING_SNAKE_CASE , size=size["shortest_edge"] , default_to_square=SCREAMING_SNAKE_CASE ) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ): """simple docstring""" snake_case : Tuple = get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(SCREAMING_SNAKE_CASE , size=(size["height"], size["width"]) , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ): """simple docstring""" return rescale(SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ): """simple docstring""" return normalize(SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE , ): """simple docstring""" snake_case : int = do_resize if do_resize is not None else self.do_resize snake_case : List[str] = size if size is not None else self.size snake_case : Dict = get_size_dict(SCREAMING_SNAKE_CASE , param_name="size" , default_to_square=SCREAMING_SNAKE_CASE ) snake_case : Optional[Any] = resample if resample is not None else self.resample snake_case : List[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case : Optional[int] = crop_size if crop_size is not None else self.crop_size snake_case : Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE , param_name="crop_size" , default_to_square=SCREAMING_SNAKE_CASE ) snake_case : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale snake_case : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize snake_case : List[str] = image_mean if image_mean is not None else self.image_mean snake_case : Optional[int] = image_std if image_std is not None else self.image_std snake_case : Optional[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb snake_case : List[Any] = make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: snake_case : Optional[int] = [convert_to_rgb(SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. snake_case : List[str] = [to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if do_resize: snake_case : Optional[Any] = [self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: snake_case : int = [self.center_crop(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: snake_case : str = [self.rescale(image=SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: snake_case : Optional[int] = [self.normalize(image=SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE ) for image in images] snake_case : Optional[int] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] snake_case : Tuple = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE , tensor_type=SCREAMING_SNAKE_CASE )
148
0
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class snake_case__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" lowerCamelCase = 42 @flax_register_to_config class snake_case__ ( nn.Module , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowerCamelCase = 32 lowerCamelCase = 4 lowerCamelCase = 4 lowerCamelCase = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) lowerCamelCase = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") lowerCamelCase = False lowerCamelCase = (320, 640, 1280, 1280) lowerCamelCase = 2 lowerCamelCase = 8 lowerCamelCase = None lowerCamelCase = 1280 lowerCamelCase = 0.0 lowerCamelCase = False lowerCamelCase = jnp.floataa lowerCamelCase = True lowerCamelCase = 0 lowerCamelCase = False def lowerCAmelCase ( self : Union[str, Any] , UpperCamelCase__ : jax.random.KeyArray ) -> FrozenDict: """simple docstring""" snake_case : List[Any] = (1, self.in_channels, self.sample_size, self.sample_size) snake_case : Optional[Any] = jnp.zeros(UpperCamelCase__ , dtype=jnp.floataa ) snake_case : Tuple = jnp.ones((1,) , dtype=jnp.intaa ) snake_case : Dict = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) snake_case ,snake_case : List[str] = jax.random.split(UpperCamelCase__ ) snake_case : Tuple = {'''params''': params_rng, '''dropout''': dropout_rng} return self.init(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )["params"] def lowerCAmelCase ( self : int ) -> Optional[Any]: """simple docstring""" snake_case : Dict = self.block_out_channels snake_case : List[Any] = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( '''At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.''' ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. snake_case : List[Any] = self.num_attention_heads or self.attention_head_dim # input snake_case : Union[str, Any] = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time snake_case : List[Any] = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) snake_case : Dict = FlaxTimestepEmbedding(UpperCamelCase__ , dtype=self.dtype ) snake_case : int = self.only_cross_attention if isinstance(UpperCamelCase__ , UpperCamelCase__ ): snake_case : Dict = (only_cross_attention,) * len(self.down_block_types ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ): snake_case : Dict = (num_attention_heads,) * len(self.down_block_types ) # down snake_case : Optional[Any] = [] snake_case : Any = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): snake_case : Optional[Any] = output_channel snake_case : int = block_out_channels[i] snake_case : List[Any] = i == len(UpperCamelCase__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": snake_case : Union[str, Any] = FlaxCrossAttnDownBlockaD( in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: snake_case : Union[str, Any] = FlaxDownBlockaD( in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(UpperCamelCase__ ) snake_case : Dict = down_blocks # mid snake_case : Any = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up snake_case : Optional[int] = [] snake_case : int = list(reversed(UpperCamelCase__ ) ) snake_case : Tuple = list(reversed(UpperCamelCase__ ) ) snake_case : str = list(reversed(UpperCamelCase__ ) ) snake_case : int = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): snake_case : Optional[Any] = output_channel snake_case : Any = reversed_block_out_channels[i] snake_case : Union[str, Any] = reversed_block_out_channels[min(i + 1 , len(UpperCamelCase__ ) - 1 )] snake_case : List[Any] = i == len(UpperCamelCase__ ) - 1 if up_block_type == "CrossAttnUpBlock2D": snake_case : List[Any] = FlaxCrossAttnUpBlockaD( in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , prev_output_channel=UpperCamelCase__ , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: snake_case : int = FlaxUpBlockaD( in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , prev_output_channel=UpperCamelCase__ , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(UpperCamelCase__ ) snake_case : Tuple = output_channel snake_case : Any = up_blocks # out snake_case : Optional[Any] = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) snake_case : List[str] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : int=None , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : bool = True , UpperCamelCase__ : bool = False , ) -> Union[FlaxUNetaDConditionOutput, Tuple]: """simple docstring""" if not isinstance(UpperCamelCase__ , jnp.ndarray ): snake_case : Dict = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(UpperCamelCase__ , jnp.ndarray ) and len(timesteps.shape ) == 0: snake_case : Dict = timesteps.astype(dtype=jnp.floataa ) snake_case : Optional[Any] = jnp.expand_dims(UpperCamelCase__ , 0 ) snake_case : Optional[Any] = self.time_proj(UpperCamelCase__ ) snake_case : Any = self.time_embedding(UpperCamelCase__ ) # 2. pre-process snake_case : Dict = jnp.transpose(UpperCamelCase__ , (0, 2, 3, 1) ) snake_case : int = self.conv_in(UpperCamelCase__ ) # 3. down snake_case : int = (sample,) for down_block in self.down_blocks: if isinstance(UpperCamelCase__ , UpperCamelCase__ ): snake_case ,snake_case : Tuple = down_block(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , deterministic=not train ) else: snake_case ,snake_case : Dict = down_block(UpperCamelCase__ , UpperCamelCase__ , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: snake_case : Dict = () for down_block_res_sample, down_block_additional_residual in zip( UpperCamelCase__ , UpperCamelCase__ ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) snake_case : Optional[int] = new_down_block_res_samples # 4. mid snake_case : Optional[Any] = self.mid_block(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: snake_case : Dict = down_block_res_samples[-(self.layers_per_block + 1) :] snake_case : int = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(UpperCamelCase__ , UpperCamelCase__ ): snake_case : Tuple = up_block( UpperCamelCase__ , temb=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , res_hidden_states_tuple=UpperCamelCase__ , deterministic=not train , ) else: snake_case : List[str] = up_block(UpperCamelCase__ , temb=UpperCamelCase__ , res_hidden_states_tuple=UpperCamelCase__ , deterministic=not train ) # 6. post-process snake_case : Any = self.conv_norm_out(UpperCamelCase__ ) snake_case : int = nn.silu(UpperCamelCase__ ) snake_case : List[str] = self.conv_out(UpperCamelCase__ ) snake_case : Tuple = jnp.transpose(UpperCamelCase__ , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=UpperCamelCase__ )
83
'''simple docstring''' import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> str: '''simple docstring''' with open(SCREAMING_SNAKE_CASE__ ) as metadata_file: snake_case : int = json.load(SCREAMING_SNAKE_CASE__ ) snake_case : Any = LukeConfig(use_entity_aware_attention=SCREAMING_SNAKE_CASE__ , **metadata['''model_config'''] ) # Load in the weights from the checkpoint_path snake_case : Any = torch.load(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' )['''module'''] # Load the entity vocab file snake_case : Dict = load_original_entity_vocab(SCREAMING_SNAKE_CASE__ ) # add an entry for [MASK2] snake_case : List[str] = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 snake_case : int = XLMRobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] ) # Add special tokens to the token vocabulary for downstream tasks snake_case : Union[str, Any] = AddedToken('''<ent>''' , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) snake_case : Optional[int] = AddedToken('''<ent2>''' , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'Saving tokenizer to {pytorch_dump_folder_path}' ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , '''tokenizer_config.json''' ) , '''r''' ) as f: snake_case : Tuple = json.load(SCREAMING_SNAKE_CASE__ ) snake_case : List[str] = '''MLukeTokenizer''' with open(os.path.join(SCREAMING_SNAKE_CASE__ , '''tokenizer_config.json''' ) , '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , MLukeTokenizer.vocab_files_names['''entity_vocab_file'''] ) , '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case : List[Any] = MLukeTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Initialize the embeddings of the special tokens snake_case : List[str] = tokenizer.convert_tokens_to_ids(['''@'''] )[0] snake_case : List[str] = tokenizer.convert_tokens_to_ids(['''#'''] )[0] snake_case : List[str] = state_dict['''embeddings.word_embeddings.weight'''] snake_case : int = word_emb[ent_init_index].unsqueeze(0 ) snake_case : Union[str, Any] = word_emb[enta_init_index].unsqueeze(0 ) snake_case : Dict = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: snake_case : Dict = state_dict[bias_name] snake_case : Any = decoder_bias[ent_init_index].unsqueeze(0 ) snake_case : str = decoder_bias[enta_init_index].unsqueeze(0 ) snake_case : Any = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: snake_case : Optional[Any] = F'encoder.layer.{layer_index}.attention.self.' snake_case : int = state_dict[prefix + matrix_name] snake_case : Union[str, Any] = state_dict[prefix + matrix_name] snake_case : int = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks snake_case : List[Any] = state_dict['''entity_embeddings.entity_embeddings.weight'''] snake_case : Dict = entity_emb[entity_vocab['''[MASK]''']].unsqueeze(0 ) snake_case : List[Any] = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' snake_case : Optional[Any] = state_dict['''entity_predictions.bias'''] snake_case : Optional[int] = entity_prediction_bias[entity_vocab['''[MASK]''']].unsqueeze(0 ) snake_case : List[Any] = torch.cat([entity_prediction_bias, entity_mask_bias] ) snake_case : str = LukeForMaskedLM(config=SCREAMING_SNAKE_CASE__ ).eval() state_dict.pop('''entity_predictions.decoder.weight''' ) state_dict.pop('''lm_head.decoder.weight''' ) state_dict.pop('''lm_head.decoder.bias''' ) snake_case : Optional[Any] = OrderedDict() for key, value in state_dict.items(): if not (key.startswith('''lm_head''' ) or key.startswith('''entity_predictions''' )): snake_case : int = state_dict[key] else: snake_case : List[str] = state_dict[key] snake_case ,snake_case : int = model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ ) if set(SCREAMING_SNAKE_CASE__ ) != {"luke.embeddings.position_ids"}: raise ValueError(F'Unexpected unexpected_keys: {unexpected_keys}' ) if set(SCREAMING_SNAKE_CASE__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'Unexpected missing_keys: {missing_keys}' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs snake_case : Optional[int] = MLukeTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , task='''entity_classification''' ) snake_case : Tuple = '''ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).''' snake_case : int = (0, 9) snake_case : str = tokenizer(SCREAMING_SNAKE_CASE__ , entity_spans=[span] , return_tensors='''pt''' ) snake_case : Union[str, Any] = model(**SCREAMING_SNAKE_CASE__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base snake_case : Dict = torch.Size((1, 33, 768) ) snake_case : int = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base snake_case : str = torch.Size((1, 1, 768) ) snake_case : Tuple = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is' F' {expected_shape}' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction snake_case : str = MLukeTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case : List[Any] = '''Tokyo is the capital of <mask>.''' snake_case : Union[str, Any] = (24, 30) snake_case : Tuple = tokenizer(SCREAMING_SNAKE_CASE__ , entity_spans=[span] , return_tensors='''pt''' ) snake_case : int = model(**SCREAMING_SNAKE_CASE__ ) snake_case : List[str] = encoding['''input_ids'''][0].tolist() snake_case : Union[str, Any] = input_ids.index(tokenizer.convert_tokens_to_ids('''<mask>''' ) ) snake_case : Dict = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(SCREAMING_SNAKE_CASE__ ) snake_case : List[Any] = outputs.entity_logits[0][0].argmax().item() snake_case : Dict = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('''en:''' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('''Saving PyTorch model to {}'''.format(SCREAMING_SNAKE_CASE__ ) ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ ) -> List[str]: '''simple docstring''' snake_case : Dict = ['''[MASK]''', '''[PAD]''', '''[UNK]'''] snake_case : List[Any] = [json.loads(SCREAMING_SNAKE_CASE__ ) for line in open(SCREAMING_SNAKE_CASE__ )] snake_case : Optional[int] = {} for entry in data: snake_case : Optional[Any] = entry['''id'''] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: snake_case : List[str] = entity_id break snake_case : Any = F'{language}:{entity_name}' snake_case : List[str] = entity_id return new_mapping if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() # Required parameters parser.add_argument("--checkpoint_path", type=str, help="Path to a pytorch_model.bin file.") parser.add_argument( "--metadata_path", default=None, type=str, help="Path to a metadata.json file, defining the configuration." ) parser.add_argument( "--entity_vocab_path", default=None, type=str, help="Path to an entity_vocab.tsv file, containing the entity vocabulary.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to where to dump the output PyTorch model." ) parser.add_argument( "--model_size", default="base", type=str, choices=["base", "large"], help="Size of the model to be converted." ) lowercase__ = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
83
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a : str = logging.get_logger(__name__) a : str = { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json', 'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json', 'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class a ( _lowerCamelCase ): snake_case_ = "big_bird" def __init__( self : Union[str, Any] , lowercase_ : List[Any]=5_0358 , lowercase_ : Tuple=768 , lowercase_ : Dict=12 , lowercase_ : str=12 , lowercase_ : Tuple=3072 , lowercase_ : Any="gelu_new" , lowercase_ : Optional[Any]=0.1 , lowercase_ : List[Any]=0.1 , lowercase_ : List[Any]=4096 , lowercase_ : List[Any]=2 , lowercase_ : List[str]=0.02 , lowercase_ : Optional[int]=1e-12 , lowercase_ : Tuple=True , lowercase_ : Tuple=0 , lowercase_ : str=1 , lowercase_ : Union[str, Any]=2 , lowercase_ : Optional[Any]=66 , lowercase_ : Optional[int]="block_sparse" , lowercase_ : Any=True , lowercase_ : List[str]=False , lowercase_ : Any=64 , lowercase_ : Tuple=3 , lowercase_ : Tuple=None , **lowercase_ : Tuple , ): super().__init__( pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , sep_token_id=lowercase_ , **lowercase_ , ) snake_case_ = vocab_size snake_case_ = max_position_embeddings snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = type_vocab_size snake_case_ = layer_norm_eps snake_case_ = use_cache snake_case_ = rescale_embeddings snake_case_ = attention_type snake_case_ = use_bias snake_case_ = block_size snake_case_ = num_random_blocks snake_case_ = classifier_dropout class a ( _lowerCamelCase ): @property def A_ ( self : str ): if self.task == "multiple-choice": snake_case_ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: snake_case_ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
56
"""simple docstring""" import math def _snake_case ( ): lowerCAmelCase : Union[str, Any] = input('''Enter message: ''' ) lowerCAmelCase : Optional[int] = int(input(f'''Enter key [2-{len(_snake_case ) - 1}]: ''' ) ) lowerCAmelCase : str = input('''Encryption/Decryption [e/d]: ''' ) if mode.lower().startswith('''e''' ): lowerCAmelCase : Any = encrypt_message(_snake_case , _snake_case ) elif mode.lower().startswith('''d''' ): lowerCAmelCase : Union[str, Any] = decrypt_message(_snake_case , _snake_case ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f'''Output:\n{text + "|"}''' ) def _snake_case ( _snake_case : int , _snake_case : str ): lowerCAmelCase : Optional[Any] = [''''''] * key for col in range(_snake_case ): lowerCAmelCase : Optional[Any] = col while pointer < len(_snake_case ): cipher_text[col] += message[pointer] pointer += key return "".join(_snake_case ) def _snake_case ( _snake_case : int , _snake_case : str ): lowerCAmelCase : Union[str, Any] = math.ceil(len(_snake_case ) / key ) lowerCAmelCase : str = key lowerCAmelCase : Any = (num_cols * num_rows) - len(_snake_case ) lowerCAmelCase : Dict = [''''''] * num_cols lowerCAmelCase : int = 0 lowerCAmelCase : int = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): lowerCAmelCase : int = 0 row += 1 return "".join(_snake_case ) if __name__ == "__main__": import doctest doctest.testmod() main()
60
0
'''simple docstring''' from ...processing_utils import ProcessorMixin class a__ ( lowerCamelCase_ ): _SCREAMING_SNAKE_CASE : str = 'SpeechT5FeatureExtractor' _SCREAMING_SNAKE_CASE : Any = 'SpeechT5Tokenizer' def __init__( self , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" super().__init__(_UpperCamelCase , _UpperCamelCase ) def __call__( self , *_UpperCamelCase , **_UpperCamelCase ): """simple docstring""" _lowercase : Optional[int] = kwargs.pop("audio" , _UpperCamelCase ) _lowercase : Optional[int] = kwargs.pop("text" , _UpperCamelCase ) _lowercase : List[Any] = kwargs.pop("text_target" , _UpperCamelCase ) _lowercase : str = kwargs.pop("audio_target" , _UpperCamelCase ) _lowercase : str = kwargs.pop("sampling_rate" , _UpperCamelCase ) if audio is not None and text is not None: raise ValueError( "Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?" ) if audio_target is not None and text_target is not None: raise ValueError( "Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?" ) if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( "You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process." ) if audio is not None: _lowercase : Optional[Any] = self.feature_extractor(_UpperCamelCase , *_UpperCamelCase , sampling_rate=_UpperCamelCase , **_UpperCamelCase ) elif text is not None: _lowercase : Optional[Any] = self.tokenizer(_UpperCamelCase , **_UpperCamelCase ) else: _lowercase : Dict = None if audio_target is not None: _lowercase : Any = self.feature_extractor(audio_target=_UpperCamelCase , *_UpperCamelCase , sampling_rate=_UpperCamelCase , **_UpperCamelCase ) _lowercase : Tuple = targets["input_values"] elif text_target is not None: _lowercase : str = self.tokenizer(_UpperCamelCase , **_UpperCamelCase ) _lowercase : Any = targets["input_ids"] else: _lowercase : Optional[int] = None if inputs is None: return targets if targets is not None: _lowercase : Any = labels _lowercase : Tuple = targets.get("attention_mask" ) if decoder_attention_mask is not None: _lowercase : Any = decoder_attention_mask return inputs def _lowerCamelCase ( self , *_UpperCamelCase , **_UpperCamelCase ): """simple docstring""" _lowercase : List[str] = kwargs.pop("input_values" , _UpperCamelCase ) _lowercase : List[Any] = kwargs.pop("input_ids" , _UpperCamelCase ) _lowercase : int = kwargs.pop("labels" , _UpperCamelCase ) if input_values is not None and input_ids is not None: raise ValueError("Cannot process both `input_values` and `input_ids` inputs." ) if input_values is None and input_ids is None and labels is None: raise ValueError( "You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded." ) if input_values is not None: _lowercase : List[Any] = self.feature_extractor.pad(_UpperCamelCase , *_UpperCamelCase , **_UpperCamelCase ) elif input_ids is not None: _lowercase : List[Any] = self.tokenizer.pad(_UpperCamelCase , **_UpperCamelCase ) else: _lowercase : List[Any] = None if labels is not None: if "input_ids" in labels or (isinstance(_UpperCamelCase , _UpperCamelCase ) and "input_ids" in labels[0]): _lowercase : List[Any] = self.tokenizer.pad(_UpperCamelCase , **_UpperCamelCase ) _lowercase : Dict = targets["input_ids"] else: _lowercase : Optional[int] = self.feature_extractor.feature_size _lowercase : str = self.feature_extractor.num_mel_bins _lowercase : Union[str, Any] = self.feature_extractor.pad(_UpperCamelCase , *_UpperCamelCase , **_UpperCamelCase ) _lowercase : Tuple = feature_size_hack _lowercase : List[str] = targets["input_values"] else: _lowercase : str = None if inputs is None: return targets if targets is not None: _lowercase : str = labels _lowercase : List[Any] = targets.get("attention_mask" ) if decoder_attention_mask is not None: _lowercase : Union[str, Any] = decoder_attention_mask return inputs def _lowerCamelCase ( self , *_UpperCamelCase , **_UpperCamelCase ): """simple docstring""" return self.tokenizer.batch_decode(*_UpperCamelCase , **_UpperCamelCase ) def _lowerCamelCase ( self , *_UpperCamelCase , **_UpperCamelCase ): """simple docstring""" return self.tokenizer.decode(*_UpperCamelCase , **_UpperCamelCase )
350
'''simple docstring''' import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = {'vocab_file': 'spiece.model'} _snake_case = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } _snake_case = { 'google/bigbird-roberta-base': 4_096, 'google/bigbird-roberta-large': 4_096, 'google/bigbird-base-trivia-itc': 4_096, } class a__ ( lowerCamelCase_ ): _SCREAMING_SNAKE_CASE : List[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : Optional[int] = ['input_ids', 'attention_mask'] _SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self , _UpperCamelCase , _UpperCamelCase="<unk>" , _UpperCamelCase="<s>" , _UpperCamelCase="</s>" , _UpperCamelCase="<pad>" , _UpperCamelCase="[SEP]" , _UpperCamelCase="[MASK]" , _UpperCamelCase="[CLS]" , _UpperCamelCase = None , **_UpperCamelCase , ): """simple docstring""" _lowercase : Optional[int] = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else bos_token _lowercase : Optional[int] = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else eos_token _lowercase : Optional[Any] = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else unk_token _lowercase : Union[str, Any] = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else pad_token _lowercase : Any = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else cls_token _lowercase : str = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else sep_token # Mask token behave like a normal word, i.e. include the space before it _lowercase : Any = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else mask_token _lowercase : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_UpperCamelCase , eos_token=_UpperCamelCase , unk_token=_UpperCamelCase , pad_token=_UpperCamelCase , sep_token=_UpperCamelCase , mask_token=_UpperCamelCase , cls_token=_UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_UpperCamelCase , ) _lowercase : str = vocab_file _lowercase : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_UpperCamelCase ) @property def _lowerCamelCase ( self ): """simple docstring""" return self.sp_model.get_piece_size() def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Dict = {self.convert_ids_to_tokens(_UpperCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" _lowercase : str = self.__dict__.copy() _lowercase : Union[str, Any] = None return state def __setstate__( self , _UpperCamelCase ): """simple docstring""" _lowercase : Dict = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _lowercase : Optional[Any] = {} _lowercase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" return self.sp_model.encode(_UpperCamelCase , out_type=_UpperCamelCase ) def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" return self.sp_model.piece_to_id(_UpperCamelCase ) def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" _lowercase : List[Any] = self.sp_model.IdToPiece(_UpperCamelCase ) return token def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" _lowercase : Optional[int] = [] _lowercase : int = "" _lowercase : Tuple = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_UpperCamelCase ) + token _lowercase : Union[str, Any] = True _lowercase : Optional[int] = [] else: current_sub_tokens.append(_UpperCamelCase ) _lowercase : str = False out_string += self.sp_model.decode(_UpperCamelCase ) return out_string.strip() def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = False , _UpperCamelCase = None , _UpperCamelCase = True , **_UpperCamelCase , ): """simple docstring""" _lowercase : Any = kwargs.pop("use_source_tokenizer" , _UpperCamelCase ) _lowercase : Dict = self.convert_ids_to_tokens(_UpperCamelCase , skip_special_tokens=_UpperCamelCase ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 _lowercase : Dict = [] _lowercase : Any = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_UpperCamelCase ) ) _lowercase : Optional[Any] = [] sub_texts.append(_UpperCamelCase ) else: current_sub_text.append(_UpperCamelCase ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_UpperCamelCase ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: _lowercase : List[str] = re.sub(R" (\[(MASK|SEP)\])" , R"\1" , " ".join(_UpperCamelCase ) ) else: _lowercase : List[Any] = "".join(_UpperCamelCase ) _lowercase : Optional[int] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: _lowercase : Tuple = self.clean_up_tokenization(_UpperCamelCase ) return clean_text else: return text def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = None ): """simple docstring""" if not os.path.isdir(_UpperCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return _lowercase : Optional[Any] = os.path.join( _UpperCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _UpperCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCamelCase , "wb" ) as fi: _lowercase : List[str] = self.sp_model.serialized_model_proto() fi.write(_UpperCamelCase ) return (out_vocab_file,) def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _lowercase : str = [self.cls_token_id] _lowercase : List[str] = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = None , _UpperCamelCase = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCamelCase , token_ids_a=_UpperCamelCase , already_has_special_tokens=_UpperCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCamelCase )) + [1] return [1] + ([0] * len(_UpperCamelCase )) + [1] + ([0] * len(_UpperCamelCase )) + [1] def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = None ): """simple docstring""" _lowercase : str = [self.sep_token_id] _lowercase : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
199
0
from __future__ import annotations from math import pow, sqrt def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if resistance == 0: return {"resistance": sqrt(pow(lowerCAmelCase_, 2 ) - pow(lowerCAmelCase_, 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(lowerCAmelCase_, 2 ) - pow(lowerCAmelCase_, 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(lowerCAmelCase_, 2 ) + pow(lowerCAmelCase_, 2 ) )} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : Any ,snake_case : Any ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : int ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Tuple ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def __call__( self : int ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ): raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ResNetForImageClassification(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) assert torch.allclose(from_model(lowerCAmelCase_ ), our_model(lowerCAmelCase_ ).logits ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels 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 =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() __lowercase = logging.get_logger() @dataclass class lowerCamelCase_ : '''simple docstring''' a__ : nn.Module a__ : List[nn.Module] = field(default_factory=UpperCAmelCase_ ) a__ : list = field(default_factory=UpperCAmelCase_ ) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> int: __UpperCamelCase :Tuple = len(list(m.modules())) == 1 or isinstance(__lowercase , nn.Convad) or isinstance(__lowercase , nn.BatchNormad) if has_not_submodules: self.traced.append(__lowercase) def __call__( self , __lowercase) -> str: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook)) self.module(__lowercase) [x.remove() for x in self.handles] return self @property def UpperCamelCase__ ( self) -> Tuple: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda __lowercase: len(list(x.state_dict().keys())) > 0 , self.traced)) @dataclass class lowerCamelCase_ : '''simple docstring''' a__ : nn.Module a__ : nn.Module a__ : int = 0 a__ : List = field(default_factory=UpperCAmelCase_ ) a__ : List = field(default_factory=UpperCAmelCase_ ) def __call__( self , __lowercase) -> Any: __UpperCamelCase :List[Any] = Tracker(self.dest)(__lowercase).parametrized __UpperCamelCase :Optional[int] = Tracker(self.src)(__lowercase).parametrized __UpperCamelCase :str = list(filter(lambda __lowercase: type(__lowercase) not in self.src_skip , __lowercase)) __UpperCamelCase :Optional[int] = list(filter(lambda __lowercase: type(__lowercase) not in self.dest_skip , __lowercase)) if len(__lowercase) != len(__lowercase): raise Exception( f"""Numbers of operations are different. Source module has {len(__lowercase)} operations while""" f""" destination module has {len(__lowercase)}.""") for dest_m, src_m in zip(__lowercase , __lowercase): dest_m.load_state_dict(src_m.state_dict()) if self.verbose == 1: print(f"""Transfered from={src_m} to={dest_m}""") def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = True ): '''simple docstring''' print(f"""Converting {name}...""" ) with torch.no_grad(): __UpperCamelCase :Any = timm.create_model(SCREAMING_SNAKE_CASE , pretrained=SCREAMING_SNAKE_CASE ).eval() __UpperCamelCase :Optional[Any] = ResNetForImageClassification(SCREAMING_SNAKE_CASE ).eval() __UpperCamelCase :int = ModuleTransfer(src=SCREAMING_SNAKE_CASE , dest=SCREAMING_SNAKE_CASE ) __UpperCamelCase :Dict = torch.randn((1, 3, 224, 224) ) module_transfer(SCREAMING_SNAKE_CASE ) assert torch.allclose(from_model(SCREAMING_SNAKE_CASE ) , our_model(SCREAMING_SNAKE_CASE ).logits ), "The model logits don't match the original one." __UpperCamelCase :Tuple = f"""resnet{'-'.join(name.split('resnet' ) )}""" print(SCREAMING_SNAKE_CASE ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add model''' , use_temp_dir=SCREAMING_SNAKE_CASE , ) # we can use the convnext one __UpperCamelCase :Union[str, Any] = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add image processor''' , use_temp_dir=SCREAMING_SNAKE_CASE , ) print(f"""Pushed {checkpoint_name}""" ) def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = True ): '''simple docstring''' __UpperCamelCase :str = '''imagenet-1k-id2label.json''' __UpperCamelCase :int = 1_000 __UpperCamelCase :Optional[Any] = (1, num_labels) __UpperCamelCase :Tuple = '''huggingface/label-files''' __UpperCamelCase :Optional[int] = num_labels __UpperCamelCase :Tuple = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , repo_type='''dataset''' ) , '''r''' ) ) __UpperCamelCase :Dict = {int(SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} __UpperCamelCase :str = idalabel __UpperCamelCase :List[Any] = {v: k for k, v in idalabel.items()} __UpperCamelCase :List[str] = partial(SCREAMING_SNAKE_CASE , num_labels=SCREAMING_SNAKE_CASE , idalabel=SCREAMING_SNAKE_CASE , labelaid=SCREAMING_SNAKE_CASE ) __UpperCamelCase :List[str] = { '''resnet18''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type='''basic''' ), '''resnet26''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1_024, 2_048] , layer_type='''bottleneck''' ), '''resnet34''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type='''basic''' ), '''resnet50''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1_024, 2_048] , layer_type='''bottleneck''' ), '''resnet101''': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1_024, 2_048] , layer_type='''bottleneck''' ), '''resnet152''': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1_024, 2_048] , layer_type='''bottleneck''' ), } if model_name: convert_weight_and_push(SCREAMING_SNAKE_CASE , names_to_config[model_name] , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return config, expected_shape if __name__ == "__main__": __lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported resnet* architecture,''' ''' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) __lowercase = parser.parse_args() __lowercase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
105
from __future__ import annotations from math import pi def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError('''One and only one argument must be 0''' ) if inductance < 0: raise ValueError('''Inductance cannot be negative''' ) if frequency < 0: raise ValueError('''Frequency cannot be negative''' ) if reactance < 0: raise ValueError('''Inductive reactance cannot be negative''' ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
105
1
"""simple docstring""" from argparse import ArgumentParser from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand lowercase__ = logging.get_logger(__name__) # pylint: disable=invalid-name def _snake_case ( lowercase__ ): if not path: return "pipe" for ext in PipelineDataFormat.SUPPORTED_FORMATS: if path.endswith(lowercase__ ): return ext raise Exception( f'''Unable to determine file format from file extension {path}. ''' f'''Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}''' ) def _snake_case ( lowercase__ ): _lowerCamelCase : Optional[int] = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) _lowerCamelCase : Optional[int] = try_infer_format_from_ext(args.input ) if args.format == 'infer' else args.format _lowerCamelCase : List[Any] = PipelineDataFormat.from_str( format=lowercase__ , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , ) return RunCommand(lowercase__ , lowercase__ ) class lowerCAmelCase__ ( lowercase ): '''simple docstring''' def __init__( self , lowercase , lowercase ): _lowerCamelCase : List[Any] = nlp _lowerCamelCase : Optional[Any] = reader @staticmethod def A_ ( lowercase ): _lowerCamelCase : Optional[int] = parser.add_parser('run' , help='Run a pipeline through the CLI' ) run_parser.add_argument('--task' , choices=get_supported_tasks() , help='Task to run' ) run_parser.add_argument('--input' , type=lowercase , help='Path to the file to use for inference' ) run_parser.add_argument('--output' , type=lowercase , help='Path to the file that will be used post to write results.' ) run_parser.add_argument('--model' , type=lowercase , help='Name or path to the model to instantiate.' ) run_parser.add_argument('--config' , type=lowercase , help='Name or path to the model\'s config to instantiate.' ) run_parser.add_argument( '--tokenizer' , type=lowercase , help='Name of the tokenizer to use. (default: same as the model name)' ) run_parser.add_argument( '--column' , type=lowercase , help='Name of the column to use as input. (For multi columns input as QA use column1,columns2)' , ) run_parser.add_argument( '--format' , type=lowercase , default='infer' , choices=PipelineDataFormat.SUPPORTED_FORMATS , help='Input format to read from' , ) run_parser.add_argument( '--device' , type=lowercase , default=-1 , help='Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)' , ) run_parser.add_argument('--overwrite' , action='store_true' , help='Allow overwriting the output file.' ) run_parser.set_defaults(func=lowercase ) def A_ ( self ): _lowerCamelCase, _lowerCamelCase : Tuple = self._nlp, [] for entry in self._reader: _lowerCamelCase : Any = nlp(**lowercase ) if self._reader.is_multi_columns else nlp(lowercase ) if isinstance(lowercase , lowercase ): outputs.append(lowercase ) else: outputs += output # Saving data if self._nlp.binary_output: _lowerCamelCase : Optional[Any] = self._reader.save_binary(lowercase ) logger.warning(F'''Current pipeline requires output to be in binary format, saving at {binary_path}''' ) else: self._reader.save(lowercase )
96
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler lowercase__ = 16 lowercase__ = 32 def _snake_case ( lowercase__ , lowercase__ = 16 , lowercase__ = "bert-base-cased" ): _lowerCamelCase : List[Any] = AutoTokenizer.from_pretrained(lowercase__ ) _lowerCamelCase : Tuple = load_dataset('glue' , 'mrpc' ) def tokenize_function(lowercase__ ): # max_length=None => use the model max length (it's actually the default) _lowerCamelCase : Union[str, Any] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=lowercase__ , max_length=lowercase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset _lowerCamelCase : int = datasets.map( lowercase__ , batched=lowercase__ , remove_columns=['idx', 'sentence1', 'sentence2'] , load_from_cache_file=lowercase__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _lowerCamelCase : Optional[int] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(lowercase__ ): # 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(lowercase__ , padding='max_length' , max_length=128 , return_tensors='pt' ) return tokenizer.pad(lowercase__ , padding='longest' , return_tensors='pt' ) # Instantiate dataloaders. _lowerCamelCase : List[str] = DataLoader( tokenized_datasets['train'] , shuffle=lowercase__ , collate_fn=lowercase__ , batch_size=lowercase__ ) _lowerCamelCase : int = DataLoader( tokenized_datasets['validation'] , shuffle=lowercase__ , collate_fn=lowercase__ , batch_size=lowercase__ ) return train_dataloader, eval_dataloader def _snake_case ( lowercase__ , lowercase__ ): # Initialize accelerator _lowerCamelCase : Optional[int] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _lowerCamelCase : Optional[int] = config['lr'] _lowerCamelCase : Optional[int] = int(config['num_epochs'] ) _lowerCamelCase : Union[str, Any] = int(config['seed'] ) _lowerCamelCase : Optional[int] = int(config['batch_size'] ) _lowerCamelCase : Dict = args.model_name_or_path set_seed(lowercase__ ) _lowerCamelCase, _lowerCamelCase : Optional[int] = get_dataloaders(lowercase__ , lowercase__ , lowercase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _lowerCamelCase : int = AutoModelForSequenceClassification.from_pretrained(lowercase__ , return_dict=lowercase__ ) # Instantiate optimizer _lowerCamelCase : Optional[int] = ( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) _lowerCamelCase : Union[str, Any] = optimizer_cls(params=model.parameters() , lr=lowercase__ ) if accelerator.state.deepspeed_plugin is not None: _lowerCamelCase : str = accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: _lowerCamelCase : Tuple = 1 _lowerCamelCase : List[Any] = (len(lowercase__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): _lowerCamelCase : Tuple = get_linear_schedule_with_warmup( optimizer=lowercase__ , num_warmup_steps=0 , num_training_steps=lowercase__ , ) else: _lowerCamelCase : Any = DummyScheduler(lowercase__ , total_num_steps=lowercase__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase, _lowerCamelCase : Union[str, Any] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) # We need to keep track of how many total steps we have iterated over _lowerCamelCase : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly _lowerCamelCase : Dict = 0 # Now we train the model _lowerCamelCase : Dict = evaluate.load('glue' , 'mrpc' ) _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : str = {} for epoch in range(lowercase__ , lowercase__ ): model.train() for step, batch in enumerate(lowercase__ ): _lowerCamelCase : List[Any] = model(**lowercase__ ) _lowerCamelCase : int = outputs.loss _lowerCamelCase : Dict = loss / gradient_accumulation_steps accelerator.backward(lowercase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() _lowerCamelCase : Union[str, Any] = 0 for step, batch in enumerate(lowercase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _lowerCamelCase : Optional[int] = model(**lowercase__ ) _lowerCamelCase : Dict = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times _lowerCamelCase, _lowerCamelCase : List[str] = accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase__ ) - 1: _lowerCamelCase : Optional[Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen] _lowerCamelCase : Dict = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase__ , references=lowercase__ , ) _lowerCamelCase : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , lowercase__ ) _lowerCamelCase : Tuple = eval_metric['accuracy'] if best_performance < eval_metric["accuracy"]: _lowerCamelCase : str = eval_metric['accuracy'] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f'''Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}''' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , 'all_results.json' ) , 'w' ) as f: json.dump(lowercase__ , lowercase__ ) def _snake_case ( ): _lowerCamelCase : Any = argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path' , type=lowercase__ , default='bert-base-cased' , help='Path to pretrained model or model identifier from huggingface.co/models.' , required=lowercase__ , ) parser.add_argument( '--output_dir' , type=lowercase__ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--performance_lower_bound' , type=lowercase__ , default=lowercase__ , help='Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.' , ) parser.add_argument( '--num_epochs' , type=lowercase__ , default=3 , help='Number of train epochs.' , ) _lowerCamelCase : Optional[Any] = parser.parse_args() _lowerCamelCase : str = {'lr': 2E-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase__ , lowercase__ ) if __name__ == "__main__": main()
96
1
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : str , _lowerCamelCase : bool = False) -> str: '''simple docstring''' if not isinstance(_lowercase , _lowercase): __UpperCamelCase : List[Any] = F'Expected string as input, found {type(_lowercase)}' raise ValueError(_lowercase) if not isinstance(_lowercase , _lowercase): __UpperCamelCase : int = F'Expected boolean as use_pascal parameter, found {type(_lowercase)}' raise ValueError(_lowercase) __UpperCamelCase : Optional[Any] = input_str.split("_") __UpperCamelCase : List[str] = 0 if use_pascal else 1 __UpperCamelCase : List[str] = words[start_index:] __UpperCamelCase : Optional[Any] = [word[0].upper() + word[1:] for word in words_to_capitalize] __UpperCamelCase : Tuple = "" if use_pascal else words[0] return "".join([initial_word, *capitalized_words]) if __name__ == "__main__": from doctest import testmod testmod()
363
import random def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int , _lowerCamelCase : float , _lowerCamelCase : bool = False) -> dict: '''simple docstring''' __UpperCamelCase : dict = {i: [] for i in range(_lowerCamelCase)} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(_lowerCamelCase) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(_lowerCamelCase): for j in range(i + 1 , _lowerCamelCase): if random.random() < probability: graph[i].append(_lowerCamelCase) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(_lowerCamelCase) return graph def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : int) -> dict: '''simple docstring''' return { i: [j for j in range(_lowerCamelCase) if i != j] for i in range(_lowerCamelCase) } if __name__ == "__main__": import doctest doctest.testmod()
151
0
from functools import reduce a__ = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def lowercase ( SCREAMING_SNAKE_CASE__ : str = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str(int(SCREAMING_SNAKE_CASE__ ) * int(SCREAMING_SNAKE_CASE__ ) ) , n[i : i + 13] ) ) for i in range(len(SCREAMING_SNAKE_CASE__ ) - 12 ) ) if __name__ == "__main__": print(F'''{solution() = }''')
317
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowercase ( SCREAMING_SNAKE_CASE__ : Optional[int] ) -> int: return getitem, k def lowercase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: return setitem, k, v def lowercase ( SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: return delitem, k def lowercase ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str , *SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: try: return fun(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ), None except Exception as e: return None, e a__ = ( _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), ) a__ = [ _set("""key_a""", """val_a"""), _set("""key_a""", """val_b"""), ] a__ = [ _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), _del("""key_a"""), _del("""key_b"""), _set("""key_a""", """val_a"""), _del("""key_a"""), ] a__ = [ _get("""key_a"""), _del("""key_a"""), _set("""key_a""", """val_a"""), _del("""key_a"""), _del("""key_a"""), _get("""key_a"""), ] a__ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] a__ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("""key_a""", """val_b"""), ] @pytest.mark.parametrize( """operations""" , ( pytest.param(_add_items , id="""add items""" ), pytest.param(_overwrite_items , id="""overwrite items""" ), pytest.param(_delete_items , id="""delete items""" ), pytest.param(_access_absent_items , id="""access absent items""" ), pytest.param(_add_with_resize_up , id="""add with resize up""" ), pytest.param(_add_with_resize_down , id="""add with resize down""" ), ) , ) def lowercase ( SCREAMING_SNAKE_CASE__ : str ) -> Tuple: _snake_case : List[Any] = HashMap(initial_block_size=4 ) _snake_case : int = {} for _, (fun, *args) in enumerate(SCREAMING_SNAKE_CASE__ ): _snake_case , _snake_case : Tuple = _run_operation(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) _snake_case , _snake_case : int = _run_operation(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) assert my_res == py_res assert str(SCREAMING_SNAKE_CASE__ ) == str(SCREAMING_SNAKE_CASE__ ) assert set(SCREAMING_SNAKE_CASE__ ) == set(SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) assert set(my.items() ) == set(py.items() ) def lowercase ( ) -> Optional[int]: def is_public(SCREAMING_SNAKE_CASE__ : str ) -> bool: return not name.startswith("""_""" ) _snake_case : Tuple = {name for name in dir({} ) if is_public(SCREAMING_SNAKE_CASE__ )} _snake_case : Optional[Any] = {name for name in dir(HashMap() ) if is_public(SCREAMING_SNAKE_CASE__ )} assert dict_public_names > hash_public_names
317
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ = {'''configuration_plbart''': ['''PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PLBartConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''PLBartTokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''PLBART_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PLBartForCausalLM''', '''PLBartForConditionalGeneration''', '''PLBartForSequenceClassification''', '''PLBartModel''', '''PLBartPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
367
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = {'''vocab_file''': '''spiece.model'''} lowerCamelCase_ = { '''vocab_file''': { '''bert_for_seq_generation''': ( '''https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model''' ), } } lowerCamelCase_ = {'''bert_for_seq_generation''': 512} class UpperCamelCase_ (__A ): __magic_name__ = VOCAB_FILES_NAMES __magic_name__ = PRETRAINED_VOCAB_FILES_MAP __magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ = [] __magic_name__ = ['''input_ids''', '''attention_mask'''] def __init__( self : int , lowerCAmelCase_ : Any , lowerCAmelCase_ : List[Any]="<s>" , lowerCAmelCase_ : Optional[Any]="</s>" , lowerCAmelCase_ : int="<unk>" , lowerCAmelCase_ : Tuple="<pad>" , lowerCAmelCase_ : Tuple="<::::>" , lowerCAmelCase_ : Optional[Dict[str, Any]] = None , **lowerCAmelCase_ : Union[str, Any] , ) -> None: UpperCAmelCase_ : int = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , sep_token=lowerCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase_ , ) UpperCAmelCase_ : List[str] = vocab_file UpperCAmelCase_ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowerCAmelCase_ ) @property def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: return self.sp_model.get_piece_size() def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: UpperCAmelCase_ : List[str] = {self.convert_ids_to_tokens(lowerCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Tuple: UpperCAmelCase_ : List[str] = self.__dict__.copy() UpperCAmelCase_ : List[Any] = None return state def __setstate__( self : Dict , lowerCAmelCase_ : Tuple ) -> Union[str, Any]: UpperCAmelCase_ : Any = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCAmelCase_ : Any = {} UpperCAmelCase_ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : str ) -> List[str]: return self.sp_model.encode(lowerCAmelCase_ , out_type=lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase_ : Optional[int] ) -> Dict: return self.sp_model.piece_to_id(lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase_ : int ) -> Optional[int]: UpperCAmelCase_ : Optional[Any] = self.sp_model.IdToPiece(lowerCAmelCase_ ) return token def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase_ : List[Any] ) -> List[Any]: UpperCAmelCase_ : Union[str, Any] = [] UpperCAmelCase_ : Tuple = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(lowerCAmelCase_ ) + token UpperCAmelCase_ : Tuple = [] else: current_sub_tokens.append(lowerCAmelCase_ ) out_string += self.sp_model.decode(lowerCAmelCase_ ) return out_string.strip() def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(lowerCAmelCase_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase_ : Tuple = 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: UpperCAmelCase_ : List[str] = self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase_ ) return (out_vocab_file,)
253
0
import argparse import json import subprocess def lowercase_ ( _lowerCamelCase : int , _lowerCamelCase : List[Any]): lowercase__ : List[Any] = [] lowercase__ : Dict = ( f'''curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"''' " https://api.github.com/repos/huggingface/transformers/actions/runners" ) lowercase__ : int = subprocess.run(_lowerCamelCase , shell=_lowerCamelCase , stdout=subprocess.PIPE) lowercase__ : Tuple = output.stdout.decode("utf-8") lowercase__ : List[Any] = json.loads(_lowerCamelCase) lowercase__ : str = status["runners"] for runner in runners: if runner["name"] in target_runners: if runner["status"] == "offline": offline_runners.append(_lowerCamelCase) # save the result so we can report them on Slack with open("offline_runners.txt" , "w") as fp: fp.write(json.dumps(_lowerCamelCase)) if len(_lowerCamelCase) > 0: lowercase__ : int = "\n".join([x["name"] for x in offline_runners]) raise ValueError(f'''The following runners are offline:\n{failed}''') if __name__ == "__main__": def lowercase_ ( _lowerCamelCase : Union[str, Any]): return values.split(",") UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--target_runners''', default=None, type=list_str, required=True, help='''Comma-separated list of runners to check status.''', ) parser.add_argument( '''--token''', default=None, type=str, required=True, help='''A token that has actions:read permission.''' ) UpperCamelCase = parser.parse_args() get_runner_status(args.target_runners, args.token)
87
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCamelCase__ ( _A , _A , _A ): if isinstance(_A , torch.Tensor ): return image elif isinstance(_A , PIL.Image.Image ): a : Any = [image] if isinstance(image[0] , PIL.Image.Image ): a : List[str] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image] a : int = np.concatenate(_A , axis=0 ) a : int = np.array(_A ).astype(np.floataa ) / 255.0 a : str = image.transpose(0 , 3 , 1 , 2 ) a : str = 2.0 * image - 1.0 a : Optional[int] = torch.from_numpy(_A ) elif isinstance(image[0] , torch.Tensor ): a : Optional[Any] = torch.cat(_A , dim=0 ) return image def lowerCamelCase__ ( _A , _A , _A , _A=0.9995 ): if not isinstance(_A , np.ndarray ): a : Dict = True a : Optional[Any] = va.device a : Optional[int] = va.cpu().numpy() a : Union[str, Any] = va.cpu().numpy() a : Any = np.sum(va * va / (np.linalg.norm(_A ) * np.linalg.norm(_A )) ) if np.abs(_A ) > DOT_THRESHOLD: a : Any = (1 - t) * va + t * va else: a : Any = np.arccos(_A ) a : Tuple = np.sin(_A ) a : Optional[Any] = theta_a * t a : List[Any] = np.sin(_A ) a : Dict = np.sin(theta_a - theta_t ) / sin_theta_a a : int = sin_theta_t / sin_theta_a a : Any = sa * va + sa * va if inputs_are_torch: a : Dict = torch.from_numpy(_A ).to(_A ) return va def lowerCamelCase__ ( _A , _A ): a : Optional[int] = F.normalize(_A , dim=-1 ) a : str = F.normalize(_A , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowerCamelCase__ ( _A , _A ): for param in model.parameters(): a : int = value class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : AutoencoderKL , __snake_case : CLIPTextModel , __snake_case : CLIPModel , __snake_case : CLIPTokenizer , __snake_case : UNetaDConditionModel , __snake_case : Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler] , __snake_case : CLIPFeatureExtractor , __snake_case : List[str]=None , __snake_case : List[str]=None , __snake_case : List[Any]=None , ): super().__init__() self.register_modules( vae=__snake_case , text_encoder=__snake_case , clip_model=__snake_case , tokenizer=__snake_case , unet=__snake_case , scheduler=__snake_case , feature_extractor=__snake_case , coca_model=__snake_case , coca_tokenizer=__snake_case , coca_transform=__snake_case , ) a : Optional[Any] = ( feature_extractor.size if isinstance(feature_extractor.size , __snake_case ) else feature_extractor.size['shortest_edge'] ) a : Optional[int] = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , __snake_case ) set_requires_grad(self.clip_model , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory a : Union[str, Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__snake_case ) def lowercase_ ( self : Union[str, Any] ): self.enable_attention_slicing(__snake_case ) def lowercase_ ( self : Optional[Any] ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : Tuple ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : int ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : Union[str, Any] ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : int , __snake_case : Dict , __snake_case : str , __snake_case : Optional[int] ): # get the original timestep using init_timestep a : Optional[Any] = min(int(num_inference_steps * strength ) , __snake_case ) a : Union[str, Any] = max(num_inference_steps - init_timestep , 0 ) a : List[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase_ ( self : Dict , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : Any , __snake_case : Optional[Any]=None ): if not isinstance(__snake_case , torch.Tensor ): raise ValueError(F"""`image` has to be of type `torch.Tensor` but is {type(__snake_case )}""" ) a : Optional[Any] = image.to(device=__snake_case , dtype=__snake_case ) if isinstance(__snake_case , __snake_case ): a : Optional[int] = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(__snake_case ) ] a : Optional[Any] = torch.cat(__snake_case , dim=0 ) else: a : Union[str, Any] = self.vae.encode(__snake_case ).latent_dist.sample(__snake_case ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : List[str] = 0.18215 * init_latents a : str = init_latents.repeat_interleave(__snake_case , dim=0 ) a : Dict = randn_tensor(init_latents.shape , generator=__snake_case , device=__snake_case , dtype=__snake_case ) # get latents a : Dict = self.scheduler.add_noise(__snake_case , __snake_case , __snake_case ) a : int = init_latents return latents def lowercase_ ( self : List[str] , __snake_case : Dict ): a : List[Any] = self.coca_transform(__snake_case ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): a : Optional[Any] = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) a : Union[str, Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('<end_of_text>' )[0].replace('<start_of_text>' , '' ).rstrip(' .,' ) def lowercase_ ( self : Tuple , __snake_case : Any , __snake_case : Optional[Any] ): a : List[Any] = self.feature_extractor.preprocess(__snake_case ) a : Optional[Any] = torch.from_numpy(clip_image_input['pixel_values'][0] ).unsqueeze(0 ).to(self.device ).half() a : int = self.clip_model.get_image_features(__snake_case ) a : str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : Tuple = image_embeddings_clip.repeat_interleave(__snake_case , dim=0 ) return image_embeddings_clip @torch.enable_grad() def lowercase_ ( self : Tuple , __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : List[Any] , ): a : Optional[Any] = latents.detach().requires_grad_() a : List[Any] = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : Any = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): a : int = self.scheduler.alphas_cumprod[timestep] a : Any = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf a : List[str] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 a : Tuple = torch.sqrt(__snake_case ) a : str = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , __snake_case ): a : List[Any] = self.scheduler.sigmas[index] a : Optional[int] = latents - sigma * noise_pred else: raise ValueError(F"""scheduler type {type(self.scheduler )} not supported""" ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Union[str, Any] = 1 / 0.18215 * sample a : str = self.vae.decode(__snake_case ).sample a : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) a : Tuple = transforms.Resize(self.feature_extractor_size )(__snake_case ) a : List[str] = self.normalize(__snake_case ).to(latents.dtype ) a : List[str] = self.clip_model.get_image_features(__snake_case ) a : Tuple = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : int = spherical_dist_loss(__snake_case , __snake_case ).mean() * clip_guidance_scale a : List[str] = -torch.autograd.grad(__snake_case , __snake_case )[0] if isinstance(self.scheduler , __snake_case ): a : List[Any] = latents.detach() + grads * (sigma**2) a : Optional[int] = noise_pred_original else: a : List[Any] = noise_pred_original - torch.sqrt(__snake_case ) * grads return noise_pred, latents @torch.no_grad() def __call__( self : Optional[int] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Optional[str] = None , __snake_case : Optional[str] = None , __snake_case : Optional[int] = 5_12 , __snake_case : Optional[int] = 5_12 , __snake_case : float = 0.6 , __snake_case : Optional[int] = 50 , __snake_case : Optional[float] = 7.5 , __snake_case : Optional[int] = 1 , __snake_case : float = 0.0 , __snake_case : Optional[float] = 1_00 , __snake_case : Optional[torch.Generator] = None , __snake_case : Optional[str] = "pil" , __snake_case : bool = True , __snake_case : float = 0.8 , __snake_case : float = 0.1 , __snake_case : float = 0.1 , ): if isinstance(__snake_case , __snake_case ) and len(__snake_case ) != batch_size: raise ValueError(F"""You have passed {batch_size} batch_size, but only {len(__snake_case )} generators.""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if isinstance(__snake_case , torch.Generator ) and batch_size > 1: a : Dict = [generator] + [None] * (batch_size - 1) a : Any = [ ('model', self.coca_model is None), ('tokenizer', self.coca_tokenizer is None), ('transform', self.coca_transform is None), ] a : List[str] = [x[0] for x in coca_is_none if x[1]] a : List[str] = ', '.join(__snake_case ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(__snake_case ): raise ValueError( F"""Content prompt is None and CoCa [{coca_is_none_str}] is None.""" F"""Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : int = self.get_image_description(__snake_case ) if style_prompt is None: if len(__snake_case ): raise ValueError( F"""Style prompt is None and CoCa [{coca_is_none_str}] is None.""" F""" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : Union[str, Any] = self.get_image_description(__snake_case ) # get prompt text embeddings for content and style a : Optional[Any] = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] a : Dict = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] a : Any = slerp(__snake_case , __snake_case , __snake_case ) # duplicate text embeddings for each generation per prompt a : Optional[Any] = text_embeddings.repeat_interleave(__snake_case , dim=0 ) # set timesteps a : int = 'offset' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) a : Any = {} if accepts_offset: a : Optional[Any] = 1 self.scheduler.set_timesteps(__snake_case , **__snake_case ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) a , a : Tuple = self.get_timesteps(__snake_case , __snake_case , self.device ) a : Optional[int] = timesteps[:1].repeat(__snake_case ) # Preprocess image a : Optional[Any] = preprocess(__snake_case , __snake_case , __snake_case ) a : List[Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : str = preprocess(__snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : Union[str, Any] = slerp(__snake_case , __snake_case , __snake_case ) if clip_guidance_scale > 0: a : Dict = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : int = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : List[str] = slerp( __snake_case , __snake_case , __snake_case ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. a : int = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: a : Any = content_text_input.input_ids.shape[-1] a : List[Any] = self.tokenizer([''] , padding='max_length' , max_length=__snake_case , return_tensors='pt' ) a : List[str] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt a : Dict = uncond_embeddings.repeat_interleave(__snake_case , dim=0 ) # 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 a : Any = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. a : List[str] = (batch_size, self.unet.config.in_channels, height // 8, width // 8) a : List[str] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps a : int = torch.randn(__snake_case , generator=__snake_case , device='cpu' , dtype=__snake_case ).to( self.device ) else: a : Optional[int] = torch.randn(__snake_case , generator=__snake_case , device=self.device , dtype=__snake_case ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) a : List[str] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler a : Any = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a : Optional[Any] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a : Union[str, Any] = {} if accepts_eta: a : List[str] = eta # check if the scheduler accepts generator a : List[Any] = 'generator' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: a : Any = generator with self.progress_bar(total=__snake_case ): for i, t in enumerate(__snake_case ): # expand the latents if we are doing classifier free guidance a : Tuple = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a : Dict = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : List[Any] = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample # perform classifier free guidance if do_classifier_free_guidance: a , a : List[str] = noise_pred.chunk(2 ) a : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: a : Optional[Any] = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) a , a : Union[str, Any] = self.cond_fn( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ) # compute the previous noisy sample x_t -> x_t-1 a : Any = self.scheduler.step(__snake_case , __snake_case , __snake_case , **__snake_case ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Tuple = 1 / 0.18215 * latents a : Optional[int] = self.vae.decode(__snake_case ).sample a : List[str] = (image / 2 + 0.5).clamp(0 , 1 ) a : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a : str = self.numpy_to_pil(__snake_case ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=__snake_case , nsfw_content_detected=__snake_case )
297
0
from __future__ import annotations import math def SCREAMING_SNAKE_CASE_ ( __magic_name__ : float , __magic_name__ : int ) -> float: """simple docstring""" UpperCamelCase :Tuple = u for i in range(1 , __magic_name__ ): UpperCamelCase :Any = temp * (u - i) return temp def SCREAMING_SNAKE_CASE_ ( ) -> None: """simple docstring""" UpperCamelCase :Union[str, Any] = int(input("""enter the numbers of values: """ ) ) UpperCamelCase :list[list[float]] = [] for _ in range(__magic_name__ ): y.append([] ) for i in range(__magic_name__ ): for j in range(__magic_name__ ): y[i].append(__magic_name__ ) UpperCamelCase :Tuple = 0 print("""enter the values of parameters in a list: """ ) UpperCamelCase :Union[str, Any] = list(map(__magic_name__ , input().split() ) ) print("""enter the values of corresponding parameters: """ ) for i in range(__magic_name__ ): UpperCamelCase :List[Any] = float(input() ) UpperCamelCase :List[str] = int(input("""enter the value to interpolate: """ ) ) UpperCamelCase :Optional[int] = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , __magic_name__ ): for j in range(n - i ): UpperCamelCase :Dict = y[j + 1][i - 1] - y[j][i - 1] UpperCamelCase :Dict = y[0][0] for i in range(1 , __magic_name__ ): summ += (ucal(__magic_name__ , __magic_name__ ) * y[0][i]) / math.factorial(__magic_name__ ) print(f"""the value at {value} is {summ}""" ) if __name__ == "__main__": main()
62
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Tuple , __magic_name__ : Any , __magic_name__ : str ) -> Optional[int]: """simple docstring""" return params[f"""{prefix}/{prefix}/relpos_bias/rel_embedding"""][:, i, :] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : str , __magic_name__ : List[str] , __magic_name__ : Tuple="attention" ) -> Optional[int]: """simple docstring""" UpperCamelCase :Any = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/key/kernel"""][:, i, :, :] ) UpperCamelCase :Any = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) UpperCamelCase :Optional[Any] = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/out/kernel"""][:, i, :, :] ) UpperCamelCase :Tuple = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) UpperCamelCase :Any = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/query/kernel"""][:, i, :, :] ) UpperCamelCase :List[str] = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) UpperCamelCase :int = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/value/kernel"""][:, i, :, :] ) UpperCamelCase :Optional[int] = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Union[str, Any] , __magic_name__ : int , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[int]=False ) -> Optional[int]: """simple docstring""" if split_mlp_wi: UpperCamelCase :Tuple = params[f"""{prefix}/{prefix}/mlp/wi_0/kernel"""][:, i, :] UpperCamelCase :Optional[int] = params[f"""{prefix}/{prefix}/mlp/wi_1/kernel"""][:, i, :] UpperCamelCase :Union[str, Any] = (wi_a, wi_a) else: UpperCamelCase :Union[str, Any] = params[f"""{prefix}/{prefix}/mlp/wi/kernel"""][:, i, :] UpperCamelCase :List[str] = params[f"""{prefix}/{prefix}/mlp/wo/kernel"""][:, i, :] return wi, wo def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : str ) -> List[Any]: """simple docstring""" return params[f"""{prefix}/{prefix}/{layer_name}/scale"""][:, i] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : dict , *, __magic_name__ : int , __magic_name__ : bool , __magic_name__ : bool = False ) -> List[str]: """simple docstring""" UpperCamelCase :str = traverse_util.flatten_dict(variables["""target"""] ) UpperCamelCase :int = {"""/""".join(__magic_name__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCamelCase :Union[str, Any] = """encoder/encoder/mlp/wi_0/kernel""" in old print("""Split MLP:""" , __magic_name__ ) UpperCamelCase :Tuple = collections.OrderedDict() # Shared embeddings. UpperCamelCase :Optional[int] = old["""token_embedder/embedding"""] # Encoder. for i in range(__magic_name__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :List[Any] = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """encoder""" , """pre_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Union[str, Any] = tax_attention_lookup(__magic_name__ , __magic_name__ , """encoder""" , """attention""" ) UpperCamelCase :Dict = layer_norm UpperCamelCase :str = k.T UpperCamelCase :int = o.T UpperCamelCase :Optional[int] = q.T UpperCamelCase :List[str] = v.T # Block i, layer 1 (MLP). UpperCamelCase :Union[str, Any] = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """encoder""" , """pre_mlp_layer_norm""" ) UpperCamelCase , UpperCamelCase :List[Any] = tax_mlp_lookup(__magic_name__ , __magic_name__ , """encoder""" , __magic_name__ ) UpperCamelCase :Dict = layer_norm if split_mlp_wi: UpperCamelCase :Union[str, Any] = wi[0].T UpperCamelCase :List[str] = wi[1].T else: UpperCamelCase :str = wi.T UpperCamelCase :Dict = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase :List[Any] = tax_relpos_bias_lookup( __magic_name__ , __magic_name__ , """encoder""" ).T UpperCamelCase :Dict = old["""encoder/encoder_norm/scale"""] if not scalable_attention: UpperCamelCase :Optional[Any] = tax_relpos_bias_lookup( __magic_name__ , 0 , """encoder""" ).T UpperCamelCase :str = tax_relpos_bias_lookup( __magic_name__ , 0 , """decoder""" ).T if not is_encoder_only: # Decoder. for i in range(__magic_name__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :Tuple = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_self_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = tax_attention_lookup(__magic_name__ , __magic_name__ , """decoder""" , """self_attention""" ) UpperCamelCase :Any = layer_norm UpperCamelCase :Tuple = k.T UpperCamelCase :Optional[Any] = o.T UpperCamelCase :List[Any] = q.T UpperCamelCase :Optional[Any] = v.T # Block i, layer 1 (Cross Attention). UpperCamelCase :List[str] = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_cross_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :int = tax_attention_lookup(__magic_name__ , __magic_name__ , """decoder""" , """encoder_decoder_attention""" ) UpperCamelCase :Union[str, Any] = layer_norm UpperCamelCase :int = k.T UpperCamelCase :Union[str, Any] = o.T UpperCamelCase :Optional[Any] = q.T UpperCamelCase :List[str] = v.T # Block i, layer 2 (MLP). UpperCamelCase :Tuple = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_mlp_layer_norm""" ) UpperCamelCase , UpperCamelCase :Optional[int] = tax_mlp_lookup(__magic_name__ , __magic_name__ , """decoder""" , __magic_name__ ) UpperCamelCase :Optional[int] = layer_norm if split_mlp_wi: UpperCamelCase :List[Any] = wi[0].T UpperCamelCase :Tuple = wi[1].T else: UpperCamelCase :Any = wi.T UpperCamelCase :List[Any] = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase :Optional[int] = tax_relpos_bias_lookup(__magic_name__ , __magic_name__ , """decoder""" ).T UpperCamelCase :int = old["""decoder/decoder_norm/scale"""] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCamelCase :Dict = old["""decoder/logits_dense/kernel"""].T return new def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Union[str, Any] , __magic_name__ : bool ) -> Union[str, Any]: """simple docstring""" UpperCamelCase :Tuple = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: UpperCamelCase :str = state_dict["""shared.weight"""] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCamelCase :Union[str, Any] = state_dict["""shared.weight"""] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("""Using shared word embeddings as lm_head.""" ) UpperCamelCase :Dict = state_dict["""shared.weight"""] return state_dict def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : Any , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , __magic_name__ : int ) -> List[str]: """simple docstring""" UpperCamelCase :Union[str, Any] = checkpoints.load_tax_checkpoint(__magic_name__ ) UpperCamelCase :Optional[Any] = convert_tax_to_pytorch( __magic_name__ , num_layers=config.num_layers , is_encoder_only=__magic_name__ , scalable_attention=__magic_name__ ) UpperCamelCase :Optional[int] = make_state_dict(__magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ , strict=__magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[Any] , __magic_name__ : Tuple , __magic_name__ : int , __magic_name__ : bool = False , __magic_name__ : bool = False , ) -> List[str]: """simple docstring""" UpperCamelCase :Tuple = MTaConfig.from_json_file(__magic_name__ ) print(f"""Building PyTorch model from configuration: {config}""" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: UpperCamelCase :Optional[Any] = UMTaEncoderModel(__magic_name__ ) else: UpperCamelCase :Tuple = UMTaForConditionalGeneration(__magic_name__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__magic_name__ ) # Verify that we can load the checkpoint. model.from_pretrained(__magic_name__ ) print("""Done""" ) if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) parser.add_argument( '''--scalable_attention''', action='''store_true''', help='''Whether the model uses scaled attention (umt5 model)''', default=False, ) UpperCAmelCase_ : str = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
62
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_camembert import CamembertTokenizer else: __A = None __A = logging.get_logger(__name__) __A = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} __A = { """vocab_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model""", }, """tokenizer_file""": { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/tokenizer.json""", }, } __A = { """camembert-base""": 512, } __A = """▁""" class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Optional[Any] = VOCAB_FILES_NAMES __magic_name__ :Optional[int] = PRETRAINED_VOCAB_FILES_MAP __magic_name__ :Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ :Tuple = ["""input_ids""", """attention_mask"""] __magic_name__ :int = CamembertTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase="<s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="</s>" , __UpperCAmelCase="<s>" , __UpperCAmelCase="<unk>" , __UpperCAmelCase="<pad>" , __UpperCAmelCase="<mask>" , __UpperCAmelCase=["<s>NOTUSED", "</s>NOTUSED"] , **__UpperCAmelCase , ): '''simple docstring''' lowerCAmelCase__ :Any = AddedToken(__UpperCAmelCase , lstrip=__UpperCAmelCase , rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ) else mask_token super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , additional_special_tokens=__UpperCAmelCase , **__UpperCAmelCase , ) lowerCAmelCase__ :Optional[int] = vocab_file lowerCAmelCase__ :List[Any] = False if not self.vocab_file else True def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ :Optional[Any] = [self.cls_token_id] lowerCAmelCase__ :Optional[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''simple docstring''' lowerCAmelCase__ :List[Any] = [self.sep_token_id] lowerCAmelCase__ :Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase = None ): '''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 lowerCAmelCase__ :Dict = 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,)
293
"""simple docstring""" import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask __A = logging.getLogger(__name__) class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self , __UpperCAmelCase=-1 ): '''simple docstring''' lowerCAmelCase__ :Dict = label_idx def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Optional[Any] = mode.value lowerCAmelCase__ :List[str] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :List[str] = 1 lowerCAmelCase__ :Union[str, Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: lowerCAmelCase__ :str = [] lowerCAmelCase__ :Dict = [] for line in f: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 lowerCAmelCase__ :Tuple = [] lowerCAmelCase__ :List[str] = [] else: lowerCAmelCase__ :List[str] = line.split(' ' ) words.append(splits[0] ) if len(__UpperCAmelCase ) > 1: labels.append(splits[self.label_idx].replace('\n' , '' ) ) else: # Examples could have no label for mode = "test" labels.append('O' ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = 0 for line in test_input_reader: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": writer.write(__UpperCAmelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ :Optional[Any] = line.split()[0] + ' ' + preds_list[example_id].pop(0 ) + '\n' writer.write(__UpperCAmelCase ) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' , line.split()[0] ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :Any = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Union[str, Any] = ['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class _lowerCAmelCase ( a ): """simple docstring""" def __init__( self ): '''simple docstring''' super().__init__(label_idx=-2 ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: lowerCAmelCase__ :str = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ :Optional[Any] = ['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class _lowerCAmelCase ( a ): """simple docstring""" def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if isinstance(__UpperCAmelCase , __UpperCAmelCase ): lowerCAmelCase__ :Union[str, Any] = mode.value lowerCAmelCase__ :Union[str, Any] = os.path.join(__UpperCAmelCase , F"{mode}.txt" ) lowerCAmelCase__ :Any = 1 lowerCAmelCase__ :Optional[Any] = [] with open(__UpperCAmelCase , encoding='utf-8' ) as f: for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Dict = [] lowerCAmelCase__ :Dict = [] for token in sentence: words.append(token['form'] ) labels.append(token['upos'] ) assert len(__UpperCAmelCase ) == len(__UpperCAmelCase ) if words: examples.append(InputExample(guid=F"{mode}-{guid_index}" , words=__UpperCAmelCase , labels=__UpperCAmelCase ) ) guid_index += 1 return examples def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = 0 for sentence in parse_incr(__UpperCAmelCase ): lowerCAmelCase__ :Optional[int] = preds_list[example_id] lowerCAmelCase__ :Tuple = '' for token in sentence: out += F"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(__UpperCAmelCase ) example_id += 1 def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' if path: with open(__UpperCAmelCase , 'r' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
293
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : List[str] = logging.get_logger(__name__) _lowerCamelCase : Optional[int] = { "uw-madison/mra-base-512-4": "https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json", } class __snake_case (_a ): lowerCAmelCase__ = "mra" def __init__( self : Optional[int] , _UpperCAmelCase : Union[str, Any]=5_0265 , _UpperCAmelCase : List[Any]=768 , _UpperCAmelCase : Optional[int]=12 , _UpperCAmelCase : List[Any]=12 , _UpperCAmelCase : Optional[Any]=3072 , _UpperCAmelCase : str="gelu" , _UpperCAmelCase : Optional[Any]=0.1 , _UpperCAmelCase : Optional[Any]=0.1 , _UpperCAmelCase : int=512 , _UpperCAmelCase : List[str]=1 , _UpperCAmelCase : int=0.02 , _UpperCAmelCase : Dict=1E-5 , _UpperCAmelCase : List[str]="absolute" , _UpperCAmelCase : Union[str, Any]=4 , _UpperCAmelCase : str="full" , _UpperCAmelCase : Any=0 , _UpperCAmelCase : Dict=0 , _UpperCAmelCase : Union[str, Any]=1 , _UpperCAmelCase : List[Any]=0 , _UpperCAmelCase : Tuple=2 , **_UpperCAmelCase : Union[str, Any] , ) -> List[Any]: '''simple docstring''' super().__init__(pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , **_UpperCAmelCase ) _lowerCAmelCase : Dict = vocab_size _lowerCAmelCase : Union[str, Any] = max_position_embeddings _lowerCAmelCase : Tuple = hidden_size _lowerCAmelCase : Tuple = num_hidden_layers _lowerCAmelCase : Any = num_attention_heads _lowerCAmelCase : Any = intermediate_size _lowerCAmelCase : str = hidden_act _lowerCAmelCase : int = hidden_dropout_prob _lowerCAmelCase : Optional[int] = attention_probs_dropout_prob _lowerCAmelCase : int = initializer_range _lowerCAmelCase : Optional[int] = type_vocab_size _lowerCAmelCase : Optional[Any] = layer_norm_eps _lowerCAmelCase : Optional[Any] = position_embedding_type _lowerCAmelCase : Union[str, Any] = block_per_row _lowerCAmelCase : List[Any] = approx_mode _lowerCAmelCase : str = initial_prior_first_n_blocks _lowerCAmelCase : Any = initial_prior_diagonal_n_blocks
159
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin _lowerCamelCase : str = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n" class __snake_case (unittest.TestCase , _a ): def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: '''simple docstring''' _lowerCAmelCase : List[Any] = load_tool("""text-question-answering""" ) self.tool.setup() _lowerCAmelCase : Optional[Any] = load_tool("""text-question-answering""" , remote=_UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: '''simple docstring''' _lowerCAmelCase : Union[str, Any] = self.tool(_UpperCAmelCase , """What did Hugging Face do in April 2021?""" ) self.assertEqual(_UpperCAmelCase , """launched the BigScience Research Workshop""" ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: '''simple docstring''' _lowerCAmelCase : List[Any] = self.remote_tool(_UpperCAmelCase , """What did Hugging Face do in April 2021?""" ) self.assertEqual(_UpperCAmelCase , """launched the BigScience Research Workshop""" ) def SCREAMING_SNAKE_CASE ( self : Dict ) -> str: '''simple docstring''' _lowerCAmelCase : List[Any] = self.tool(text=_UpperCAmelCase , question="""What did Hugging Face do in April 2021?""" ) self.assertEqual(_UpperCAmelCase , """launched the BigScience Research Workshop""" ) def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: '''simple docstring''' _lowerCAmelCase : List[Any] = self.remote_tool(text=_UpperCAmelCase , question="""What did Hugging Face do in April 2021?""" ) self.assertEqual(_UpperCAmelCase , """launched the BigScience Research Workshop""" )
159
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class lowerCamelCase__ ( lowerCamelCase_ ): a__ : str = """Salesforce/blip-image-captioning-base""" a__ : Dict = ( """This is a tool that generates a description of an image. It takes an input named `image` which should be the """ """image to caption, and returns a text that contains the description in English.""" ) a__ : Optional[int] = """image_captioner""" a__ : int = AutoModelForVisionaSeq a__ : Optional[Any] = ["""image"""] a__ : Optional[int] = ["""text"""] def __init__( self , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ): """simple docstring""" requires_backends(self , ["vision"] ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE ): """simple docstring""" return self.pre_processor(images=SCREAMING_SNAKE_CASE , return_tensors="pt" ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE ): """simple docstring""" return self.model.generate(**SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE ): """simple docstring""" return self.pre_processor.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE )[0].strip()
148
"""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 lowerCamelCase__ ( unittest.TestCase ): 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=512 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=4 , ): """simple docstring""" snake_case : int = parent snake_case : List[Any] = batch_size snake_case : str = seq_length snake_case : Optional[int] = is_training snake_case : Optional[int] = use_attention_mask snake_case : str = use_token_type_ids snake_case : int = use_labels snake_case : Any = vocab_size snake_case : Any = hidden_size snake_case : Any = num_hidden_layers snake_case : int = num_attention_heads snake_case : Optional[Any] = intermediate_size snake_case : List[str] = hidden_act snake_case : Any = hidden_dropout_prob snake_case : Tuple = attention_probs_dropout_prob snake_case : int = max_position_embeddings snake_case : Any = type_vocab_size snake_case : int = type_sequence_label_size snake_case : Union[str, Any] = initializer_range snake_case : Optional[Any] = num_choices def lowerCamelCase_ ( self ): """simple docstring""" snake_case : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case : Tuple = None if self.use_attention_mask: snake_case : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case : str = None if self.use_token_type_ids: snake_case : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case : str = 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=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase_ ( self ): """simple docstring""" snake_case : Optional[int] = self.prepare_config_and_inputs() snake_case , snake_case , snake_case , snake_case : str = config_and_inputs snake_case : int = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class lowerCamelCase__ ( lowerCamelCase_ , unittest.TestCase ): a__ : Optional[Any] = True a__ : List[str] = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase_ ( self ): """simple docstring""" snake_case : str = FlaxRoFormerModelTester(self ) @slow def lowerCamelCase_ ( self ): """simple docstring""" for model_class_name in self.all_model_classes: snake_case : List[Any] = model_class_name.from_pretrained("junnyu/roformer_chinese_small" , from_pt=SCREAMING_SNAKE_CASE ) snake_case : str = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_flax class lowerCamelCase__ ( unittest.TestCase ): @slow def lowerCamelCase_ ( self ): """simple docstring""" snake_case : List[str] = FlaxRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base" ) snake_case : Union[str, Any] = jnp.array([[0, 1, 2, 3, 4, 5]] ) snake_case : List[Any] = model(SCREAMING_SNAKE_CASE )[0] snake_case : List[Any] = 50_000 snake_case : List[str] = (1, 6, vocab_size) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) snake_case : Optional[int] = 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] , SCREAMING_SNAKE_CASE , atol=1E-4 ) )
148
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { 'facebook/deit-base-distilled-patch16-224': ( 'https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class lowerCAmelCase__ ( UpperCAmelCase__ ): lowerCAmelCase : List[str] = "deit" def __init__( self : Union[str, Any] , lowerCamelCase__ : int=7_68 , lowerCamelCase__ : List[Any]=12 , lowerCamelCase__ : List[Any]=12 , lowerCamelCase__ : Optional[Any]=30_72 , lowerCamelCase__ : int="gelu" , lowerCamelCase__ : Union[str, Any]=0.0 , lowerCamelCase__ : List[Any]=0.0 , lowerCamelCase__ : Dict=0.0_2 , lowerCamelCase__ : List[str]=1E-12 , lowerCamelCase__ : Optional[Any]=2_24 , lowerCamelCase__ : Dict=16 , lowerCamelCase__ : Dict=3 , lowerCamelCase__ : List[str]=True , lowerCamelCase__ : Any=16 , **lowerCamelCase__ : Union[str, Any] , ) ->str: '''simple docstring''' super().__init__(**lowerCamelCase__ ) _UpperCAmelCase : Union[str, Any] = hidden_size _UpperCAmelCase : Any = num_hidden_layers _UpperCAmelCase : Union[str, Any] = num_attention_heads _UpperCAmelCase : Union[str, Any] = intermediate_size _UpperCAmelCase : Optional[Any] = hidden_act _UpperCAmelCase : Any = hidden_dropout_prob _UpperCAmelCase : Any = attention_probs_dropout_prob _UpperCAmelCase : str = initializer_range _UpperCAmelCase : Dict = layer_norm_eps _UpperCAmelCase : str = image_size _UpperCAmelCase : int = patch_size _UpperCAmelCase : Union[str, Any] = num_channels _UpperCAmelCase : Dict = qkv_bias _UpperCAmelCase : Tuple = encoder_stride class lowerCAmelCase__ ( UpperCAmelCase__ ): lowerCAmelCase : Optional[int] = version.parse("1.11" ) @property def lowerCAmelCase__ ( self : Optional[int] ) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def lowerCAmelCase__ ( self : Union[str, Any] ) ->float: '''simple docstring''' return 1E-4
322
'''simple docstring''' from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor lowerCamelCase__ = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def __lowerCAmelCase (__lowerCAmelCase ): if isinstance(__lowerCAmelCase , torch.Tensor ): return image elif isinstance(__lowerCAmelCase , PIL.Image.Image ): _UpperCAmelCase : int = [image] _UpperCAmelCase : str = [trans(img.convert("RGB" ) ) for img in image] _UpperCAmelCase : Optional[Any] = torch.stack(__lowerCAmelCase ) return image class lowerCAmelCase__ ( UpperCAmelCase__ ): def __init__( self : Tuple , lowerCamelCase__ : int , lowerCamelCase__ : int ) ->int: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM _UpperCAmelCase : Tuple = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=lowerCamelCase__ , scheduler=lowerCamelCase__ ) def lowerCAmelCase__ ( self : Dict , lowerCamelCase__ : str ) ->Union[str, Any]: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""" ) def lowerCAmelCase__ ( self : Dict , lowerCamelCase__ : Dict , lowerCamelCase__ : List[str] , lowerCamelCase__ : int ) ->Union[str, Any]: '''simple docstring''' _UpperCAmelCase : str = min(int(num_inference_steps * strength ) , lowerCamelCase__ ) _UpperCAmelCase : str = max(num_inference_steps - init_timestep , 0 ) _UpperCAmelCase : List[str] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowerCAmelCase__ ( self : List[Any] , lowerCamelCase__ : List[str] , lowerCamelCase__ : Any , lowerCamelCase__ : str , lowerCamelCase__ : str , lowerCamelCase__ : Dict , lowerCamelCase__ : Optional[Any]=None ) ->str: '''simple docstring''' if not isinstance(lowerCamelCase__ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowerCamelCase__ )}""" ) _UpperCAmelCase : Union[str, Any] = image.to(device=lowerCamelCase__ , dtype=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and len(lowerCamelCase__ ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(lowerCamelCase__ )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) _UpperCAmelCase : List[str] = init_latents.shape _UpperCAmelCase : Optional[int] = randn_tensor(lowerCamelCase__ , generator=lowerCamelCase__ , device=lowerCamelCase__ , dtype=lowerCamelCase__ ) # get latents print("add noise to latents at timestep" , lowerCamelCase__ ) _UpperCAmelCase : List[Any] = self.scheduler.add_noise(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) _UpperCAmelCase : List[Any] = init_latents return latents @torch.no_grad() def __call__( self : Any , lowerCamelCase__ : Union[torch.FloatTensor, PIL.Image.Image] = None , lowerCamelCase__ : float = 0.8 , lowerCamelCase__ : int = 1 , lowerCamelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase__ : float = 0.0 , lowerCamelCase__ : int = 50 , lowerCamelCase__ : Optional[bool] = None , lowerCamelCase__ : Optional[str] = "pil" , lowerCamelCase__ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(lowerCamelCase__ ) # 2. Preprocess image _UpperCAmelCase : Dict = preprocess(lowerCamelCase__ ) # 3. set timesteps self.scheduler.set_timesteps(lowerCamelCase__ , device=self.device ) _UpperCAmelCase , _UpperCAmelCase : Any = self.get_timesteps(lowerCamelCase__ , lowerCamelCase__ , self.device ) _UpperCAmelCase : List[Any] = timesteps[:1].repeat(lowerCamelCase__ ) # 4. Prepare latent variables _UpperCAmelCase : Optional[int] = self.prepare_latents(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , self.unet.dtype , self.device , lowerCamelCase__ ) _UpperCAmelCase : Any = latents # 5. Denoising loop for t in self.progress_bar(lowerCamelCase__ ): # 1. predict noise model_output _UpperCAmelCase : Union[str, Any] = self.unet(lowerCamelCase__ , lowerCamelCase__ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 _UpperCAmelCase : int = self.scheduler.step( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , eta=lowerCamelCase__ , use_clipped_model_output=lowerCamelCase__ , generator=lowerCamelCase__ , ).prev_sample _UpperCAmelCase : Dict = (image / 2 + 0.5).clamp(0 , 1 ) _UpperCAmelCase : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _UpperCAmelCase : str = self.numpy_to_pil(lowerCamelCase__ ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=lowerCamelCase__ )
322
1
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[str] , A : int , A : Union[str, Any]=7 , A : Any=3 , A : List[Any]=18 , A : Tuple=30 , A : Dict=400 , A : Optional[int]=True , A : Any=None , A : List[str]=True , ): __snake_case: int = size if size is not None else {"""height""": 18, """width""": 18} __snake_case: Any = parent __snake_case: Tuple = batch_size __snake_case: List[str] = num_channels __snake_case: List[Any] = image_size __snake_case: Dict = min_resolution __snake_case: Optional[int] = max_resolution __snake_case: Dict = do_resize __snake_case: List[str] = size __snake_case: Optional[Any] = apply_ocr def UpperCAmelCase__ ( self : List[str] ): 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''' lowerCAmelCase__ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def UpperCAmelCase__ ( self : Optional[int] ): __snake_case: Any = LayoutLMvaImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Dict ): __snake_case: str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A , """do_resize""" ) ) self.assertTrue(hasattr(A , """size""" ) ) self.assertTrue(hasattr(A , """apply_ocr""" ) ) def UpperCAmelCase__ ( self : Tuple ): __snake_case: int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) __snake_case: Any = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def UpperCAmelCase__ ( self : str ): pass def UpperCAmelCase__ ( self : Tuple ): # Initialize image_processing __snake_case: int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case: Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A , Image.Image ) # Test not batched input __snake_case: str = 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 , A ) self.assertIsInstance(encoding.boxes , A ) # Test batched __snake_case: int = image_processing(A , 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 UpperCAmelCase__ ( self : Optional[Any] ): # Initialize image_processing __snake_case: int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case: Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , numpify=A ) for image in image_inputs: self.assertIsInstance(A , np.ndarray ) # Test not batched input __snake_case: Optional[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.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched __snake_case: Optional[Any] = image_processing(A , 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 UpperCAmelCase__ ( self : Tuple ): # Initialize image_processing __snake_case: Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case: str = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , torchify=A ) for image in image_inputs: self.assertIsInstance(A , torch.Tensor ) # Test not batched input __snake_case: str = 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 __snake_case: str = image_processing(A , 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 UpperCAmelCase__ ( self : Optional[Any] ): # with apply_OCR = True __snake_case: List[str] = LayoutLMvaImageProcessor() from datasets import load_dataset __snake_case: Optional[int] = load_dataset("""hf-internal-testing/fixtures_docvqa""" , split="""test""" ) __snake_case: List[str] = Image.open(ds[0]["""file"""] ).convert("""RGB""" ) __snake_case: int = image_processing(A , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __snake_case: Optional[Any] = [["""11:14""", """to""", """11:39""", """a.m""", """11:39""", """to""", """11:44""", """a.m.""", """11:44""", """a.m.""", """to""", """12:25""", """p.m.""", """12:25""", """to""", """12:58""", """p.m.""", """12:58""", """to""", """4:00""", """p.m.""", """2:00""", """to""", """5:00""", """p.m.""", """Coffee""", """Break""", """Coffee""", """will""", """be""", """served""", """for""", """men""", """and""", """women""", """in""", """the""", """lobby""", """adjacent""", """to""", """exhibit""", """area.""", """Please""", """move""", """into""", """exhibit""", """area.""", """(Exhibits""", """Open)""", """TRRF""", """GENERAL""", """SESSION""", """(PART""", """|)""", """Presiding:""", """Lee""", """A.""", """Waller""", """TRRF""", """Vice""", """President""", """“Introductory""", """Remarks”""", """Lee""", """A.""", """Waller,""", """TRRF""", """Vice""", """Presi-""", """dent""", """Individual""", """Interviews""", """with""", """TRRF""", """Public""", """Board""", """Members""", """and""", """Sci-""", """entific""", """Advisory""", """Council""", """Mem-""", """bers""", """Conducted""", """by""", """TRRF""", """Treasurer""", """Philip""", """G.""", """Kuehn""", """to""", """get""", """answers""", """which""", """the""", """public""", """refrigerated""", """warehousing""", """industry""", """is""", """looking""", """for.""", """Plus""", """questions""", """from""", """the""", """floor.""", """Dr.""", """Emil""", """M.""", """Mrak,""", """University""", """of""", """Cal-""", """ifornia,""", """Chairman,""", """TRRF""", """Board;""", """Sam""", """R.""", """Cecil,""", """University""", """of""", """Georgia""", """College""", """of""", """Agriculture;""", """Dr.""", """Stanley""", """Charm,""", """Tufts""", """University""", """School""", """of""", """Medicine;""", """Dr.""", """Robert""", """H.""", """Cotton,""", """ITT""", """Continental""", """Baking""", """Company;""", """Dr.""", """Owen""", """Fennema,""", """University""", """of""", """Wis-""", """consin;""", """Dr.""", """Robert""", """E.""", """Hardenburg,""", """USDA.""", """Questions""", """and""", """Answers""", """Exhibits""", """Open""", """Capt.""", """Jack""", """Stoney""", """Room""", """TRRF""", """Scientific""", """Advisory""", """Council""", """Meeting""", """Ballroom""", """Foyer"""]] # noqa: E231 __snake_case: Any = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , A ) self.assertListEqual(encoding.boxes , A ) # with apply_OCR = False __snake_case: List[Any] = LayoutLMvaImageProcessor(apply_ocr=A ) __snake_case: Dict = image_processing(A , return_tensors="""pt""" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
111
def A__ ( SCREAMING_SNAKE_CASE__ = 200) -> int: __snake_case: Optional[int] = [1, 2, 5, 10, 20, 50, 100, 200] __snake_case: List[Any] = [0] * (pence + 1) __snake_case: int = 1 # base case: 1 way to make 0 pence for coin in coins: for i in range(SCREAMING_SNAKE_CASE__ , pence + 1 , 1): number_of_ways[i] += number_of_ways[i - coin] return number_of_ways[pence] if __name__ == "__main__": assert solution(200) == 73_682
111
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase = { 'configuration_groupvit': [ 'GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GroupViTConfig', 'GroupViTOnnxConfig', 'GroupViTTextConfig', 'GroupViTVisionConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ 'GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'GroupViTModel', 'GroupViTPreTrainedModel', 'GroupViTTextModel', 'GroupViTVisionModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ 'TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFGroupViTModel', 'TFGroupViTPreTrainedModel', 'TFGroupViTTextModel', 'TFGroupViTVisionModel', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys lowerCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
93
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase = { 'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'], 'tokenization_luke': ['LukeTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ 'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST', 'LukeForEntityClassification', 'LukeForEntityPairClassification', 'LukeForEntitySpanClassification', 'LukeForMultipleChoice', 'LukeForQuestionAnswering', 'LukeForSequenceClassification', 'LukeForTokenClassification', 'LukeForMaskedLM', 'LukeModel', 'LukePreTrainedModel', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys lowerCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
93
1
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 650, '''eval_accuracy''': 0.6, '''eval_loss''': 0.9}, }, { '''framework''': '''tensorflow''', '''script''': '''run_tf.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 600, '''eval_accuracy''': 0.3, '''eval_loss''': 0.9}, }, ] ) class lowercase_ ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase_ ( self : Union[str, Any] ): if self.framework == "pytorch": subprocess.run( F'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='utf-8' , check=lowerCamelCase_ , ) assert hasattr(self , 'env' ) def lowerCAmelCase_ ( self : int , _UpperCAmelCase : Dict=1 ): return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F'''{self.env.base_job_name}-single''' , instance_count=lowerCamelCase_ , instance_type=self.instance_type , debugger_hook_config=lowerCamelCase_ , hyperparameters={**self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version='py36' , ) def lowerCAmelCase_ ( self : List[str] , _UpperCAmelCase : str ): TrainingJobAnalytics(lowerCamelCase_ ).export_csv(F'''{self.env.test_path}/{job_name}_metrics.csv''' ) def lowerCAmelCase_ ( self : Optional[Any] ): _A = self.create_estimator() # run training estimator.fit() # result dataframe _A = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis _A = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value'] ) _A = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value'] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping _A = ( Session().describe_training_job(estimator.latest_training_job.name ).get('TrainingTimeInSeconds' , 999_999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy ) assert all(t <= self.results['eval_loss'] for t in eval_loss ) # dump tests result into json file to share in PR with open(F'''{estimator.latest_training_job.name}.json''' , 'w' ) as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} , lowerCamelCase_ )
315
from __future__ import annotations def lowercase( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> list: '''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 lowercase( UpperCamelCase_ ) -> list: '''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__": _SCREAMING_SNAKE_CASE = input("""Enter numbers separated by a comma:\n""").strip() if user_input == "": _SCREAMING_SNAKE_CASE = [] else: _SCREAMING_SNAKE_CASE = [int(item.strip()) for item in user_input.split(""",""")] print(iter_merge_sort(unsorted))
343
0
"""simple docstring""" from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
362
"""simple docstring""" from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def _lowerCAmelCase ( ): __SCREAMING_SNAKE_CASE = HfArgumentParser(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses()[0] __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(args=UpperCamelCase_ ) try: __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses()[0] except ValueError as e: __SCREAMING_SNAKE_CASE = """Arg --no_{0} is no longer used, please use --no-{0} instead.""" __SCREAMING_SNAKE_CASE = """ """.join(str(UpperCamelCase_ ).split(""" """ )[:-1] ) __SCREAMING_SNAKE_CASE = """""" __SCREAMING_SNAKE_CASE = eval(str(UpperCamelCase_ ).split(""" """ )[-1] ) __SCREAMING_SNAKE_CASE = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(UpperCamelCase_ ) if len(UpperCamelCase_ ) > 0: __SCREAMING_SNAKE_CASE = full_error_msg + begin_error_msg + str(UpperCamelCase_ ) raise ValueError(UpperCamelCase_ ) benchmark.run() if __name__ == "__main__": main()
255
0
"""simple docstring""" import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline lowerCAmelCase__ = { '''n_samples''': 64, '''horizon''': 32, '''num_inference_steps''': 20, '''n_guide_steps''': 2, # can set to 0 for faster sampling, does not use value network '''scale_grad_by_std''': True, '''scale''': 0.1, '''eta''': 0.0, '''t_grad_cutoff''': 2, '''device''': '''cpu''', } if __name__ == "__main__": lowerCAmelCase__ = '''hopper-medium-v2''' lowerCAmelCase__ = gym.make(env_name) lowerCAmelCase__ = ValueGuidedRLPipeline.from_pretrained( '''bglick13/hopper-medium-v2-value-function-hor32''', env=env, ) env.seed(0) lowerCAmelCase__ = env.reset() lowerCAmelCase__ = 0 lowerCAmelCase__ = 0 lowerCAmelCase__ = 1000 lowerCAmelCase__ = [obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy lowerCAmelCase__ = pipeline(obs, planning_horizon=32) # execute action in environment lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = env.step(denorm_actions) lowerCAmelCase__ = env.get_normalized_score(total_reward) # update return total_reward += reward total_score += score print( F"""Step: {t}, Reward: {reward}, Total Reward: {total_reward}, Score: {score}, Total Score:""" F""" {total_score}""" ) # save observations for rendering rollout.append(next_observation.copy()) lowerCAmelCase__ = next_observation except KeyboardInterrupt: pass print(F"""Total reward: {total_reward}""")
72
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase = '▁' lowerCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class A ( UpperCamelCase_ , unittest.TestCase ): UpperCamelCase__ : Tuple =BigBirdTokenizer UpperCamelCase__ : Union[str, Any] =BigBirdTokenizerFast UpperCamelCase__ : Any =True UpperCamelCase__ : Optional[Any] =True def lowerCamelCase ( self : List[Any] ) -> Dict: """simple docstring""" super().setUp() _lowerCamelCase : List[Any] =self.tokenizer_class(lowercase_ , keep_accents=lowercase_ ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase ( self : Union[str, Any] ) -> int: """simple docstring""" _lowerCamelCase : List[Any] ='<s>' _lowerCamelCase : Optional[Any] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_ ) , lowercase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_ ) , lowercase_ ) def lowerCamelCase ( self : int ) -> Union[str, Any]: """simple docstring""" _lowerCamelCase : Optional[int] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '[MASK]' ) self.assertEqual(len(lowercase_ ) , 1004 ) def lowerCamelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def lowerCamelCase ( self : Any ) -> Dict: """simple docstring""" if not self.test_rust_tokenizer: return _lowerCamelCase : Union[str, Any] =self.get_tokenizer() _lowerCamelCase : int =self.get_rust_tokenizer() _lowerCamelCase : int ='I was born in 92000, and this is falsé.' _lowerCamelCase : int =tokenizer.tokenize(lowercase_ ) _lowerCamelCase : List[Any] =rust_tokenizer.tokenize(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) _lowerCamelCase : Any =tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ ) _lowerCamelCase : str =rust_tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) _lowerCamelCase : str =self.get_rust_tokenizer() _lowerCamelCase : Union[str, Any] =tokenizer.encode(lowercase_ ) _lowerCamelCase : List[Any] =rust_tokenizer.encode(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) def lowerCamelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" _lowerCamelCase : str =BigBirdTokenizer(lowercase_ , keep_accents=lowercase_ ) _lowerCamelCase : int =tokenizer.tokenize('This is a test' ) self.assertListEqual(lowercase_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase_ ) , [285, 46, 10, 170, 382] , ) _lowerCamelCase : Optional[Any] =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) _lowerCamelCase : Any =tokenizer.convert_tokens_to_ids(lowercase_ ) self.assertListEqual( lowercase_ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) _lowerCamelCase : Optional[int] =tokenizer.convert_ids_to_tokens(lowercase_ ) self.assertListEqual( lowercase_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def lowerCamelCase ( self : Union[str, Any] ) -> str: """simple docstring""" return BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base' ) @slow def lowerCamelCase ( self : Any ) -> Dict: """simple docstring""" _lowerCamelCase : List[str] ='Hello World!' _lowerCamelCase : Tuple =[65, 1_8536, 2260, 101, 66] self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_ ) ) @slow def lowerCamelCase ( self : str ) -> Optional[Any]: """simple docstring""" _lowerCamelCase : int =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) # fmt: off _lowerCamelCase : Tuple =[65, 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 3_4324, 497, 391, 408, 1_1342, 1244, 385, 100, 938, 985, 456, 574, 362, 1_2597, 3200, 3129, 1172, 66] # noqa: E231 # fmt: on self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_ ) ) @require_torch @slow def lowerCamelCase ( self : Any ) -> Any: """simple docstring""" import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence _lowerCamelCase : Union[str, Any] =list(self.big_tokenizer.get_vocab().keys() )[:10] _lowerCamelCase : List[Any] =' '.join(lowercase_ ) _lowerCamelCase : List[str] =self.big_tokenizer.encode_plus(lowercase_ , return_tensors='pt' , return_token_type_ids=lowercase_ ) _lowerCamelCase : Optional[int] =self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=lowercase_ ) _lowerCamelCase : List[str] =BigBirdConfig(attention_type='original_full' ) _lowerCamelCase : Optional[Any] =BigBirdModel(lowercase_ ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**lowercase_ ) model(**lowercase_ ) @slow def lowerCamelCase ( self : Dict ) -> Optional[int]: """simple docstring""" _lowerCamelCase : Dict =BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base' ) _lowerCamelCase : int =tokenizer.decode(tokenizer('Paris is the [MASK].' ).input_ids ) self.assertTrue(decoded_text == '[CLS] Paris is the[MASK].[SEP]' ) @slow def lowerCamelCase ( self : Optional[int] ) -> List[Any]: """simple docstring""" _lowerCamelCase : Union[str, Any] ={'input_ids': [[65, 3_9286, 458, 3_6335, 2001, 456, 1_3073, 1_3266, 455, 113, 7746, 1741, 1_1157, 391, 1_3073, 1_3266, 455, 113, 3967, 3_5412, 113, 4936, 109, 3870, 2377, 113, 3_0084, 4_5720, 458, 134, 1_7496, 112, 503, 1_1672, 113, 118, 112, 5665, 1_3347, 3_8687, 112, 1496, 3_1389, 112, 3268, 4_7264, 134, 962, 112, 1_6377, 8035, 2_3130, 430, 1_2169, 1_5518, 2_8592, 458, 146, 4_1697, 109, 391, 1_2169, 1_5518, 1_6689, 458, 146, 4_1358, 109, 452, 726, 4034, 111, 763, 3_5412, 5082, 388, 1903, 111, 9051, 391, 2870, 4_8918, 1900, 1123, 550, 998, 112, 9586, 1_5985, 455, 391, 410, 2_2955, 3_7636, 114, 66], [65, 448, 1_7496, 419, 3663, 385, 763, 113, 2_7533, 2870, 3283, 1_3043, 1639, 2_4713, 523, 656, 2_4013, 1_8550, 2521, 517, 2_7014, 2_1244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 1_1786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2169, 7687, 2_1932, 1_8146, 726, 363, 1_7032, 3391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase_ , model_name='google/bigbird-roberta-base' , revision='215c99f1600e06f83acce68422f2035b2b5c3510' , )
199
0
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class __magic_name__ : """simple docstring""" def __init__( self :List[Any] , snake_case :int , snake_case :Any=13 , snake_case :List[str]=7 , snake_case :str=True , snake_case :Union[str, Any]=True , snake_case :Any=True , snake_case :List[Any]=True , snake_case :Tuple=99 , snake_case :Tuple=32 , snake_case :Union[str, Any]=2 , snake_case :Dict=4 , snake_case :int=37 , snake_case :Any="gelu" , snake_case :Optional[Any]=0.1 , snake_case :str=0.1 , snake_case :Tuple=512 , snake_case :Optional[Any]=16 , snake_case :int=2 , snake_case :Union[str, Any]=0.02 , snake_case :int=False , snake_case :Union[str, Any]=True , snake_case :Union[str, Any]="None" , snake_case :Dict=3 , snake_case :Dict=4 , snake_case :List[str]=None , ): '''simple docstring''' A_ : Union[str, Any] = parent A_ : Tuple = batch_size A_ : Dict = seq_length A_ : List[str] = is_training A_ : Optional[int] = use_input_mask A_ : Tuple = use_token_type_ids A_ : Optional[int] = use_labels A_ : Tuple = vocab_size A_ : Optional[Any] = hidden_size A_ : str = num_hidden_layers A_ : Optional[Any] = num_attention_heads A_ : Optional[int] = intermediate_size A_ : Any = hidden_act A_ : Any = hidden_dropout_prob A_ : Optional[Any] = attention_probs_dropout_prob A_ : List[Any] = max_position_embeddings A_ : int = type_vocab_size A_ : List[str] = type_sequence_label_size A_ : Optional[Any] = initializer_range A_ : Dict = num_labels A_ : Optional[int] = num_choices A_ : Dict = relative_attention A_ : str = position_biased_input A_ : Union[str, Any] = pos_att_type A_ : Optional[Any] = scope def SCREAMING_SNAKE_CASE ( self :Optional[int] ): '''simple docstring''' A_ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A_ : Any = None if self.use_input_mask: A_ : Any = random_attention_mask([self.batch_size, self.seq_length] ) A_ : Dict = None if self.use_token_type_ids: A_ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) A_ : str = None A_ : List[Any] = None A_ : Any = None if self.use_labels: A_ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A_ : List[str] = DebertaVaConfig( 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 , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=_SCREAMING_SNAKE_CASE , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self :Dict , snake_case :Tuple , snake_case :Dict , snake_case :str , snake_case :List[str] , snake_case :Tuple , snake_case :Optional[Any] , snake_case :Tuple ): '''simple docstring''' A_ : List[str] = TFDebertaVaModel(config=_SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} A_ : Dict = [input_ids, input_mask] A_ : List[Any] = model(_SCREAMING_SNAKE_CASE ) A_ : int = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self :List[Any] , snake_case :Any , snake_case :Optional[int] , snake_case :List[str] , snake_case :Tuple , snake_case :int , snake_case :Any , snake_case :List[Any] ): '''simple docstring''' A_ : int = TFDebertaVaForMaskedLM(config=_SCREAMING_SNAKE_CASE ) A_ : List[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } A_ : int = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self :Any , snake_case :Dict , snake_case :Any , snake_case :Optional[Any] , snake_case :Any , snake_case :List[str] , snake_case :int , snake_case :Any ): '''simple docstring''' A_ : Tuple = self.num_labels A_ : int = TFDebertaVaForSequenceClassification(config=_SCREAMING_SNAKE_CASE ) A_ : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } A_ : List[str] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self :Tuple , snake_case :Union[str, Any] , snake_case :Any , snake_case :Optional[Any] , snake_case :List[Any] , snake_case :Optional[Any] , snake_case :List[Any] , snake_case :List[Any] ): '''simple docstring''' A_ : Union[str, Any] = self.num_labels A_ : Optional[Any] = TFDebertaVaForTokenClassification(config=_SCREAMING_SNAKE_CASE ) A_ : int = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } A_ : Optional[int] = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self :Union[str, Any] , snake_case :List[str] , snake_case :Union[str, Any] , snake_case :Union[str, Any] , snake_case :Optional[int] , snake_case :int , snake_case :Optional[int] , snake_case :List[Any] ): '''simple docstring''' A_ : List[str] = TFDebertaVaForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) A_ : Any = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } A_ : str = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self :List[str] ): '''simple docstring''' A_ : Tuple = self.prepare_config_and_inputs() ( ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ( A_ ) , ) : Tuple = config_and_inputs A_ : Union[str, Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class __magic_name__ ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) __UpperCamelCase = ( { "feature-extraction": TFDebertaVaModel, "fill-mask": TFDebertaVaForMaskedLM, "question-answering": TFDebertaVaForQuestionAnswering, "text-classification": TFDebertaVaForSequenceClassification, "token-classification": TFDebertaVaForTokenClassification, "zero-shot": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def SCREAMING_SNAKE_CASE ( self :List[str] ): '''simple docstring''' A_ : Optional[int] = TFDebertaVaModelTester(self ) A_ : Dict = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def SCREAMING_SNAKE_CASE ( self :List[str] ): '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self :Optional[int] ): '''simple docstring''' A_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' A_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self :Tuple ): '''simple docstring''' A_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE ( self :Tuple ): '''simple docstring''' A_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_SCREAMING_SNAKE_CASE ) @slow def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' A_ : Union[str, Any] = TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge" ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @require_tf class __magic_name__ ( unittest.TestCase ): """simple docstring""" @unittest.skip(reason="Model not available yet" ) def SCREAMING_SNAKE_CASE ( self :Any ): '''simple docstring''' pass @slow def SCREAMING_SNAKE_CASE ( self :Union[str, Any] ): '''simple docstring''' A_ : Optional[Any] = TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge" ) A_ : List[Any] = tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) A_ : str = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) A_ : Tuple = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE )[0] A_ : str = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , _SCREAMING_SNAKE_CASE , atol=1e-4 )
355
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : int = logging.get_logger(__name__) _lowerCAmelCase : Dict = { '''microsoft/git-base''': '''https://huggingface.co/microsoft/git-base/resolve/main/config.json''', } class __magic_name__ ( lowerCamelCase__ ): """simple docstring""" __UpperCamelCase = '''git_vision_model''' def __init__( self :Union[str, Any] , snake_case :str=768 , snake_case :str=3_072 , snake_case :Optional[Any]=12 , snake_case :Any=12 , snake_case :Dict=3 , snake_case :Union[str, Any]=224 , snake_case :Optional[int]=16 , snake_case :Union[str, Any]="quick_gelu" , snake_case :Optional[int]=1e-5 , snake_case :List[str]=0.0 , snake_case :Any=0.02 , **snake_case :str , ): '''simple docstring''' super().__init__(**snake_case ) A_ : Optional[int] = hidden_size A_ : Optional[Any] = intermediate_size A_ : Dict = num_hidden_layers A_ : int = num_attention_heads A_ : int = num_channels A_ : Tuple = patch_size A_ : Dict = image_size A_ : Optional[int] = initializer_range A_ : str = attention_dropout A_ : Tuple = layer_norm_eps A_ : List[str] = hidden_act @classmethod def SCREAMING_SNAKE_CASE ( cls :Any , snake_case :Union[str, os.PathLike] , **snake_case :List[str] ): '''simple docstring''' cls._set_token_in_kwargs(snake_case ) A_ , A_ : Optional[Any] = cls.get_config_dict(snake_case , **snake_case ) # get the vision config dict if we are loading from GITConfig if config_dict.get("model_type" ) == "git": A_ : int = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"You are using a model of type {config_dict['model_type']} to instantiate a model of type " f"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(snake_case , **snake_case ) class __magic_name__ ( lowerCamelCase__ ): """simple docstring""" __UpperCamelCase = '''git''' def __init__( self :List[str] , snake_case :Any=None , snake_case :int=30_522 , snake_case :Dict=768 , snake_case :List[Any]=6 , snake_case :Any=12 , snake_case :Any=3_072 , snake_case :List[Any]="gelu" , snake_case :Union[str, Any]=0.1 , snake_case :Any=0.1 , snake_case :Optional[int]=1_024 , snake_case :str=0.02 , snake_case :int=1e-12 , snake_case :Optional[int]=0 , snake_case :int="absolute" , snake_case :Tuple=True , snake_case :List[str]=False , snake_case :List[str]=101 , snake_case :int=102 , snake_case :str=None , **snake_case :List[Any] , ): '''simple docstring''' super().__init__(bos_token_id=snake_case , eos_token_id=snake_case , pad_token_id=snake_case , **snake_case ) if vision_config is None: A_ : Union[str, Any] = {} logger.info("vision_config is None. initializing the GitVisionConfig with default values." ) A_ : List[Any] = GitVisionConfig(**snake_case ) A_ : Optional[int] = vocab_size A_ : List[str] = hidden_size A_ : int = num_hidden_layers A_ : Union[str, Any] = num_attention_heads A_ : List[str] = hidden_act A_ : Dict = intermediate_size A_ : Tuple = hidden_dropout_prob A_ : str = attention_probs_dropout_prob A_ : Any = max_position_embeddings A_ : List[str] = initializer_range A_ : int = layer_norm_eps A_ : Dict = position_embedding_type A_ : str = use_cache A_ : str = tie_word_embeddings A_ : Optional[Any] = num_image_with_embedding A_ : int = bos_token_id A_ : Optional[int] = eos_token_id def SCREAMING_SNAKE_CASE ( self :Optional[Any] ): '''simple docstring''' A_ : Tuple = copy.deepcopy(self.__dict__ ) A_ : Optional[int] = self.vision_config.to_dict() A_ : Optional[Any] = self.__class__.model_type return output
70
0
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowercase : Union[str, Any] = 16 lowercase : Union[str, Any] = 32 def lowerCAmelCase_ ( snake_case__ , snake_case__ = 16 ): '''simple docstring''' A : str = AutoTokenizer.from_pretrained('''bert-base-cased''' ) A : Optional[Any] = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(snake_case__ ): # max_length=None => use the model max length (it's actually the default) A : Optional[Any] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=snake_case__ , max_length=snake_case__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): A : int = datasets.map( snake_case__ , batched=snake_case__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Union[str, Any] = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(snake_case__ ): # On TPU it's best to pad everything to the same length or training will be very slow. A : Tuple = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": A : int = 16 elif accelerator.mixed_precision != "no": A : Tuple = 8 else: A : Optional[int] = None return tokenizer.pad( snake_case__ , padding='''longest''' , max_length=snake_case__ , pad_to_multiple_of=snake_case__ , return_tensors='''pt''' , ) # Instantiate dataloaders. A : int = DataLoader( tokenized_datasets['''train'''] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) A : Optional[int] = DataLoader( tokenized_datasets['''validation'''] , shuffle=snake_case__ , collate_fn=snake_case__ , batch_size=snake_case__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowercase : List[Any] = mocked_dataloaders # noqa: F811 def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , snake_case__ ) == "1": A : int = 2 # New Code # A : Any = int(args.gradient_accumulation_steps ) A : Any = int(args.local_sgd_steps ) # Initialize accelerator A : List[str] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=snake_case__ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError('''LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)''' ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : Union[str, Any] = config['''lr'''] A : Union[str, Any] = int(config['''num_epochs'''] ) A : List[Any] = int(config['''seed'''] ) A : Tuple = int(config['''batch_size'''] ) A : Dict = evaluate.load('''glue''' , '''mrpc''' ) set_seed(snake_case__ ) A, A : int = get_dataloaders(snake_case__ , snake_case__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[Any] = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=snake_case__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). A : str = model.to(accelerator.device ) # Instantiate optimizer A : List[Any] = AdamW(params=model.parameters() , lr=snake_case__ ) # Instantiate scheduler A : Any = get_linear_schedule_with_warmup( optimizer=snake_case__ , num_warmup_steps=100 , num_training_steps=(len(snake_case__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A, A, A, A, A : List[Any] = accelerator.prepare( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Now we train the model for epoch in range(snake_case__ ): model.train() with LocalSGD( accelerator=snake_case__ , model=snake_case__ , local_sgd_steps=snake_case__ , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case__ ): A : List[str] = model(**snake_case__ ) A : Union[str, Any] = output.loss accelerator.backward(snake_case__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(snake_case__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : List[str] = model(**snake_case__ ) A : Optional[int] = outputs.logits.argmax(dim=-1 ) A, A : str = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=snake_case__ , references=snake_case__ , ) A : Union[str, Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , snake_case__ ) def lowerCAmelCase_ ( ): '''simple docstring''' A : Optional[int] = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=snake_case__ , default=snake_case__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) # New Code # parser.add_argument( '''--gradient_accumulation_steps''' , type=snake_case__ , default=1 , help='''The number of minibatches to be ran before gradients are accumulated.''' , ) parser.add_argument( '''--local_sgd_steps''' , type=snake_case__ , default=8 , help='''Number of local SGD steps or None to disable local SGD''' ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) A : Dict = parser.parse_args() A : Dict = {'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(snake_case__ , snake_case__ ) if __name__ == "__main__": main()
3
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowercase : Optional[Any] = logging.get_logger(__name__) class A ( __snake_case ): __magic_name__ = ['''pixel_values'''] def __init__( self , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = 1 / 255 , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> None: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE ) A : str = size if size is not None else {'''shortest_edge''': 384} A : Tuple = get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) A : str = do_resize A : List[Any] = size # Default value set here for backwards compatibility where the value in config is None A : List[Any] = crop_pct if crop_pct is not None else 224 / 256 A : Optional[int] = resample A : Union[str, Any] = do_rescale A : List[str] = rescale_factor A : Union[str, Any] = do_normalize A : Any = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A : Optional[int] = image_std if image_std is not None else IMAGENET_STANDARD_STD def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> np.ndarray: """simple docstring""" A : str = get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size: raise ValueError(F'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) A : Any = size['''shortest_edge'''] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct A : Dict = int(shortest_edge / crop_pct ) A : str = get_resize_output_image_size(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) A : int = resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" return rescale(SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ) -> np.ndarray: """simple docstring""" return normalize(SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE , ) -> PIL.Image.Image: """simple docstring""" A : int = do_resize if do_resize is not None else self.do_resize A : Tuple = crop_pct if crop_pct is not None else self.crop_pct A : Optional[Any] = resample if resample is not None else self.resample A : List[Any] = do_rescale if do_rescale is not None else self.do_rescale A : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor A : Union[str, Any] = do_normalize if do_normalize is not None else self.do_normalize A : Union[str, Any] = image_mean if image_mean is not None else self.image_mean A : List[str] = image_std if image_std is not None else self.image_std A : Union[str, Any] = size if size is not None else self.size A : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) A : Any = make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError('''crop_pct must be specified if size < 384.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. A : Optional[int] = [to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if do_resize: A : Any = [self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , crop_pct=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: A : str = [self.rescale(image=SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: A : Dict = [self.normalize(image=SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE ) for image in images] A : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] A : Optional[int] = {'''pixel_values''': images} return BatchFeature(data=SCREAMING_SNAKE_CASE , tensor_type=SCREAMING_SNAKE_CASE )
3
1
'''simple docstring''' import argparse from collections import defaultdict import yaml __lowerCAmelCase = """docs/source/en/_toctree.yml""" def UpperCAmelCase_ (__a : str ): """simple docstring""" _a : Any = defaultdict(__a ) for doc in model_doc: counts[doc["local"]] += 1 _a : List[str] = [key for key, value in counts.items() if value > 1] _a : str = [] for duplicate_key in duplicates: _a : Union[str, Any] = list({doc['title'] for doc in model_doc if doc['local'] == duplicate_key} ) if len(__a ) > 1: raise ValueError( f"""{duplicate_key} is present several times in the documentation table of content at """ '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ' 'others.' ) # Only add this once new_doc.append({'local': duplicate_key, 'title': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['local']] == 1] ) # Sort return sorted(__a , key=lambda __a : s["title"].lower() ) def UpperCAmelCase_ (__a : Optional[int]=False ): """simple docstring""" with open(__a , encoding='utf-8' ) as f: _a : Tuple = yaml.safe_load(f.read() ) # Get to the API doc _a : Union[str, Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 _a : Union[str, Any] = content[api_idx]['sections'] # Then to the model doc _a : List[str] = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 _a : List[str] = api_doc[model_idx]['sections'] _a : List[Any] = [(idx, section) for idx, section in enumerate(__a ) if 'sections' in section] _a : Tuple = False for idx, modality_doc in modalities_docs: _a : List[Any] = modality_doc['sections'] _a : Any = clean_model_doc_toc(__a ) if old_modality_doc != new_modality_doc: _a : Union[str, Any] = True if overwrite: _a : str = new_modality_doc if diff: if overwrite: _a : Dict = model_doc _a : Dict = api_doc with open(__a , 'w' , encoding='utf-8' ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) else: raise ValueError( 'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") __lowerCAmelCase = parser.parse_args() check_model_doc(args.fix_and_overwrite)
361
'''simple docstring''' import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCAmelCase__ : """simple docstring""" def __init__( self : int ,_a : List[str] ,_a : Optional[Any]=13 ,_a : str=30 ,_a : str=2 ,_a : Union[str, Any]=3 ,_a : Optional[Any]=True ,_a : int=True ,_a : Union[str, Any]=32 ,_a : List[Any]=5 ,_a : Union[str, Any]=4 ,_a : int=37 ,_a : Any="gelu" ,_a : Union[str, Any]=0.1 ,_a : str=0.1 ,_a : List[str]=10 ,_a : Dict=0.02 ,_a : Tuple=None ,): '''simple docstring''' _a : Any = parent _a : int = batch_size _a : List[Any] = image_size _a : Optional[int] = patch_size _a : List[str] = num_channels _a : Dict = is_training _a : Dict = use_labels _a : Optional[Any] = hidden_size _a : str = num_hidden_layers _a : Optional[int] = num_attention_heads _a : Dict = intermediate_size _a : Union[str, Any] = hidden_act _a : List[str] = hidden_dropout_prob _a : Any = attention_probs_dropout_prob _a : List[str] = type_sequence_label_size _a : int = initializer_range _a : List[Any] = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _a : Union[str, Any] = (image_size // patch_size) ** 2 _a : Tuple = num_patches + 1 def __lowercase ( self : Any ): '''simple docstring''' _a : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : str = None if self.use_labels: _a : Tuple = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) _a : List[str] = self.get_config() return config, pixel_values, labels def __lowercase ( self : Optional[int] ): '''simple docstring''' return ViTMSNConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,initializer_range=self.initializer_range ,) def __lowercase ( self : Tuple ,_a : Any ,_a : List[Any] ,_a : int ): '''simple docstring''' _a : str = ViTMSNModel(config=_a ) model.to(_a ) model.eval() _a : int = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase ( self : List[Any] ,_a : str ,_a : Tuple ,_a : Dict ): '''simple docstring''' _a : Tuple = self.type_sequence_label_size _a : int = ViTMSNForImageClassification(_a ) model.to(_a ) model.eval() _a : Dict = model(_a ,labels=_a ) print('Pixel and labels shape: {pixel_values.shape}, {labels.shape}' ) print('Labels: {labels}' ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images _a : int = 1 _a : Optional[Any] = ViTMSNForImageClassification(_a ) model.to(_a ) model.eval() _a : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _a : Optional[int] = model(_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def __lowercase ( self : Any ): '''simple docstring''' _a : Optional[int] = self.prepare_config_and_inputs() _a, _a, _a : int = config_and_inputs _a : List[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase__ ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Tuple = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () __UpperCAmelCase : List[Any] = ( {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification} if is_torch_available() else {} ) __UpperCAmelCase : str = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : List[str] = False __UpperCAmelCase : int = False def __lowercase ( self : Optional[int] ): '''simple docstring''' _a : List[str] = ViTMSNModelTester(self ) _a : Optional[int] = ConfigTester(self ,config_class=_a ,has_text_modality=_a ,hidden_size=37 ) def __lowercase ( self : str ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='ViTMSN does not use inputs_embeds' ) def __lowercase ( self : List[str] ): '''simple docstring''' pass 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 : List[Any] = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) _a : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a ,nn.Linear ) ) def __lowercase ( self : Any ): '''simple docstring''' _a, _a : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : List[str] = model_class(_a ) _a : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : List[Any] = [*signature.parameters.keys()] _a : int = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_a ) def __lowercase ( self : List[str] ): '''simple docstring''' _a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' _a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) @slow def __lowercase ( self : int ): '''simple docstring''' for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Dict = ViTMSNModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def UpperCAmelCase_ (): """simple docstring""" _a : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase ( self : Union[str, Any] ): '''simple docstring''' return ViTImageProcessor.from_pretrained('facebook/vit-msn-small' ) if is_vision_available() else None @slow def __lowercase ( self : Union[str, Any] ): '''simple docstring''' torch.manual_seed(2 ) _a : List[str] = ViTMSNForImageClassification.from_pretrained('facebook/vit-msn-small' ).to(_a ) _a : List[str] = self.default_image_processor _a : int = prepare_img() _a : Tuple = image_processor(images=_a ,return_tensors='pt' ).to(_a ) # forward pass with torch.no_grad(): _a : Optional[int] = model(**_a ) # verify the logits _a : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,_a ) _a : List[Any] = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_a ,atol=1E-4 ) )
5
0
"""simple docstring""" import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} __A = { "vocab_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", }, "merges_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt", }, "tokenizer_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json", }, } __A = { "allenai/led-base-16384": 16384, } class snake_case ( __snake_case ): SCREAMING_SNAKE_CASE_ : List[Any] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ : Dict = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE_ : Union[str, Any] = LEDTokenizer SCREAMING_SNAKE_CASE_ : Any = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[int] , UpperCamelCase__ : Any=None , UpperCamelCase__ : int=None , UpperCamelCase__ : Dict=None , UpperCamelCase__ : List[str]="replace" , UpperCamelCase__ : Optional[int]="<s>" , UpperCamelCase__ : List[str]="</s>" , UpperCamelCase__ : Optional[int]="</s>" , UpperCamelCase__ : List[Any]="<s>" , UpperCamelCase__ : Tuple="<unk>" , UpperCamelCase__ : Any="<pad>" , UpperCamelCase__ : Optional[int]="<mask>" , UpperCamelCase__ : Union[str, Any]=False , UpperCamelCase__ : str=True , **UpperCamelCase__ : List[Any] , )-> List[Any]: '''simple docstring''' super().__init__( UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , errors=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ , trim_offsets=UpperCamelCase__ , **UpperCamelCase__ , ) __lowerCAmelCase: Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get("add_prefix_space" , UpperCamelCase__) != add_prefix_space: __lowerCAmelCase: Tuple = getattr(UpperCamelCase__ , pre_tok_state.pop("type")) __lowerCAmelCase: List[Any] = add_prefix_space __lowerCAmelCase: Any = pre_tok_class(**UpperCamelCase__) __lowerCAmelCase: int = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` __lowerCAmelCase: List[str] = "post_processor" __lowerCAmelCase: Optional[int] = getattr(self.backend_tokenizer , UpperCamelCase__ , UpperCamelCase__) if tokenizer_component_instance: __lowerCAmelCase: Optional[int] = json.loads(tokenizer_component_instance.__getstate__()) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: __lowerCAmelCase: Any = tuple(state["sep"]) if "cls" in state: __lowerCAmelCase: str = tuple(state["cls"]) __lowerCAmelCase: Dict = False if state.get("add_prefix_space" , UpperCamelCase__) != add_prefix_space: __lowerCAmelCase: Any = add_prefix_space __lowerCAmelCase: Optional[int] = True if state.get("trim_offsets" , UpperCamelCase__) != trim_offsets: __lowerCAmelCase: Optional[Any] = trim_offsets __lowerCAmelCase: Optional[Any] = True if changes_to_apply: __lowerCAmelCase: Optional[int] = getattr(UpperCamelCase__ , state.pop("type")) __lowerCAmelCase: int = component_class(**UpperCamelCase__) setattr(self.backend_tokenizer , UpperCamelCase__ , UpperCamelCase__) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def lowercase_ ( self : Tuple)-> str: '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet.") return None return str(self._mask_token) @mask_token.setter def lowercase_ ( self : int , UpperCamelCase__ : Optional[int])-> Tuple: '''simple docstring''' __lowerCAmelCase: int = AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__) if isinstance(UpperCamelCase__ , UpperCamelCase__) else value __lowerCAmelCase: int = value def lowercase_ ( self : Union[str, Any] , *UpperCamelCase__ : List[str] , **UpperCamelCase__ : Optional[Any])-> BatchEncoding: '''simple docstring''' __lowerCAmelCase: Tuple = kwargs.get("is_split_into_words" , UpperCamelCase__) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs.") return super()._batch_encode_plus(*UpperCamelCase__ , **UpperCamelCase__) def lowercase_ ( self : Dict , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : Optional[Any])-> BatchEncoding: '''simple docstring''' __lowerCAmelCase: Optional[int] = kwargs.get("is_split_into_words" , UpperCamelCase__) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs.") return super()._encode_plus(*UpperCamelCase__ , **UpperCamelCase__) def lowercase_ ( self : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None)-> Tuple[str]: '''simple docstring''' __lowerCAmelCase: Tuple = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__) return tuple(UpperCamelCase__) def lowercase_ ( self : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Union[str, Any]=None)-> Optional[Any]: '''simple docstring''' __lowerCAmelCase: Tuple = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase_ ( self : int , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None)-> List[int]: '''simple docstring''' __lowerCAmelCase: Optional[int] = [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 + sep + token_ids_a + sep) * [0] def lowercase_ ( self : str , UpperCamelCase__ : Union[Dict[str, EncodedInput], BatchEncoding] , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[bool] = None , )-> dict: '''simple docstring''' __lowerCAmelCase: Optional[int] = super()._pad( encoded_inputs=UpperCamelCase__ , max_length=UpperCamelCase__ , padding_strategy=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , ) # Load from model defaults if return_attention_mask is None: __lowerCAmelCase: List[str] = "attention_mask" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: __lowerCAmelCase: str = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. __lowerCAmelCase: Union[str, Any] = len(encoded_inputs["global_attention_mask"]) != len(UpperCamelCase__) if needs_to_be_padded: __lowerCAmelCase: str = len(UpperCamelCase__) - len(encoded_inputs["global_attention_mask"]) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` __lowerCAmelCase: Any = ( encoded_inputs["global_attention_mask"] + [-1] * difference ) elif self.padding_side == "left": __lowerCAmelCase: str = [-1] * difference + encoded_inputs[ "global_attention_mask" ] else: raise ValueError("Invalid padding strategy:" + str(self.padding_side)) return encoded_inputs
217
"""simple docstring""" def a__ ( __SCREAMING_SNAKE_CASE ) -> int: __lowerCAmelCase: Optional[Any] = 1 for i in range(1 , num + 1 ): fact *= i return fact def a__ ( __SCREAMING_SNAKE_CASE ) -> int: __lowerCAmelCase: List[str] = 0 while number > 0: __lowerCAmelCase: Any = number % 1_0 sum_of_digits += last_digit __lowerCAmelCase: List[Any] = number // 1_0 # Removing the last_digit from the given number return sum_of_digits def a__ ( __SCREAMING_SNAKE_CASE = 1_0_0 ) -> int: __lowerCAmelCase: Tuple = factorial(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase: Optional[int] = split_and_add(__SCREAMING_SNAKE_CASE ) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
217
1
"""simple docstring""" from math import loga def __lowerCamelCase ( a_ : int ) -> int: if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(a_ , a_ ): raise TypeError('''Input value must be a \'int\' type''' ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
352
"""simple docstring""" import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class _SCREAMING_SNAKE_CASE( unittest.TestCase ): @require_torch def _UpperCamelCase ( self ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE :Dict = pipeline( task='''zero-shot-audio-classification''' ,model='''hf-internal-testing/tiny-clap-htsat-unfused''' ) __SCREAMING_SNAKE_CASE :Any = load_dataset('''ashraq/esc50''' ) __SCREAMING_SNAKE_CASE :int = dataset['''train''']['''audio'''][-1]['''array'''] __SCREAMING_SNAKE_CASE :Dict = audio_classifier(SCREAMING_SNAKE_CASE__ ,candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) ,[{'''score''': 0.5_0_1, '''label''': '''Sound of a dog'''}, {'''score''': 0.4_9_9, '''label''': '''Sound of vaccum cleaner'''}] ,) @unittest.skip('''No models are available in TF''' ) def _UpperCamelCase ( self ) -> Optional[int]: """simple docstring""" pass @slow @require_torch def _UpperCamelCase ( self ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE :Optional[int] = pipeline( task='''zero-shot-audio-classification''' ,model='''laion/clap-htsat-unfused''' ,) # This is an audio of a dog __SCREAMING_SNAKE_CASE :List[Any] = load_dataset('''ashraq/esc50''' ) __SCREAMING_SNAKE_CASE :Tuple = dataset['''train''']['''audio'''][-1]['''array'''] __SCREAMING_SNAKE_CASE :str = audio_classifier(SCREAMING_SNAKE_CASE__ ,candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) ,[ {'''score''': 0.9_9_9, '''label''': '''Sound of a dog'''}, {'''score''': 0.0_0_1, '''label''': '''Sound of vaccum cleaner'''}, ] ,) __SCREAMING_SNAKE_CASE :Dict = audio_classifier([audio] * 5 ,candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) ,[ [ {'''score''': 0.9_9_9, '''label''': '''Sound of a dog'''}, {'''score''': 0.0_0_1, '''label''': '''Sound of vaccum cleaner'''}, ], ] * 5 ,) __SCREAMING_SNAKE_CASE :Union[str, Any] = audio_classifier( [audio] * 5 ,candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner'''] ,batch_size=5 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) ,[ [ {'''score''': 0.9_9_9, '''label''': '''Sound of a dog'''}, {'''score''': 0.0_0_1, '''label''': '''Sound of vaccum cleaner'''}, ], ] * 5 ,) @unittest.skip('''No models are available in TF''' ) def _UpperCamelCase ( self ) -> List[str]: """simple docstring""" pass
239
0
from collections import deque def a( A : List[Any] ) -> Tuple: """simple docstring""" a = len(A ) a = deque() a = [False for _ in range(A )] a = [-1 for _ in range(A )] a = index_of[:] def strong_connect(A : Any , A : List[str] , A : Optional[Any] ): a = index # the number when this node is seen a = index # lowest rank node reachable from here index += 1 stack.append(A ) a = True for w in g[v]: if index_of[w] == -1: a = strong_connect(A , A , A ) a = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: a = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: a = [] a = stack.pop() a = False component.append(A ) while w != v: a = stack.pop() a = False component.append(A ) components.append(A ) return index a = [] for v in range(A ): if index_of[v] == -1: strong_connect(A , 0 , A ) return components def a( A : List[str] , A : Optional[Any] ) -> Optional[int]: """simple docstring""" a = [[] for _ in range(A )] for u, v in edges: g[u].append(A ) return g if __name__ == "__main__": # Test _lowercase: Optional[int] = 7 _lowercase: List[Any] = [0, 0, 1, 2, 3, 3, 4, 4, 6] _lowercase: List[Any] = [1, 3, 2, 0, 1, 4, 5, 6, 5] _lowercase: List[str] = [(u, v) for u, v in zip(source, target)] _lowercase: int = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
227
import cmath import math def a( A : float , A : float , A : float , A : float ) -> complex: """simple docstring""" a = math.radians(A ) a = math.radians(A ) # Convert voltage and current to rectangular form a = cmath.rect(A , A ) a = cmath.rect(A , A ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
227
1
'''simple docstring''' def SCREAMING_SNAKE_CASE( __lowercase ) -> bool: if number < 0: raise ValueError('''number must not be negative''' ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
334
'''simple docstring''' import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''vocab_file''': { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json''' ), }, } UpperCamelCase = { '''vocab_file''': { '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json''' ), }, } UpperCamelCase = { '''vocab_file''': { '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json''' ), }, } UpperCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': 512, '''facebook/dpr-ctx_encoder-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-question_encoder-single-nq-base''': 512, '''facebook/dpr-question_encoder-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-reader-single-nq-base''': 512, '''facebook/dpr-reader-multiset-base''': 512, } UpperCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase = { '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True}, } UpperCamelCase = { '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True}, '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True}, } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Union[str, Any] = VOCAB_FILES_NAMES UpperCamelCase_ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = DPRContextEncoderTokenizer class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Dict = VOCAB_FILES_NAMES UpperCamelCase_ : List[str] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : List[Any] = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Tuple = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Optional[int] = DPRQuestionEncoderTokenizer UpperCamelCase = collections.namedtuple( '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text'''] ) UpperCamelCase = collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits''']) UpperCamelCase = R''' Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `\'tf\'`: Return TensorFlow `tf.constant` objects. - `\'pt\'`: Return PyTorch `torch.Tensor` objects. - `\'np\'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer\'s default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Return: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. ''' @add_start_docstrings(UpperCAmelCase_ ) class lowerCAmelCase_ : '''simple docstring''' def __call__( self : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Optional[str] = None , SCREAMING_SNAKE_CASE_ : Union[bool, str] = False , SCREAMING_SNAKE_CASE_ : Union[bool, str] = False , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE_ : Optional[bool] = None , **SCREAMING_SNAKE_CASE_ : Dict , ) -> BatchEncoding: '''simple docstring''' if titles is None and texts is None: return super().__call__( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) elif titles is None or texts is None: A: Union[str, Any] = titles if texts is None else texts return super().__call__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) A: Union[str, Any] = titles if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [titles] A: Optional[Any] = texts if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [texts] A: str = len(SCREAMING_SNAKE_CASE_ ) A: List[Any] = questions if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else [questions] * n_passages assert len(SCREAMING_SNAKE_CASE_ ) == len( SCREAMING_SNAKE_CASE_ ), f"""There should be as many titles than texts but got {len(SCREAMING_SNAKE_CASE_ )} titles and {len(SCREAMING_SNAKE_CASE_ )} texts.""" A: Union[str, Any] = super().__call__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] A: Dict = super().__call__(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )['''input_ids'''] A: str = { '''input_ids''': [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ] } if return_attention_mask is not False: A: Union[str, Any] = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) A: Optional[Any] = attention_mask return self.pad(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ ) def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : BatchEncoding , SCREAMING_SNAKE_CASE_ : DPRReaderOutput , SCREAMING_SNAKE_CASE_ : int = 16 , SCREAMING_SNAKE_CASE_ : int = 64 , SCREAMING_SNAKE_CASE_ : int = 4 , ) -> List[DPRSpanPrediction]: '''simple docstring''' A: Any = reader_input['''input_ids'''] A , A , A: str = reader_output[:3] A: str = len(SCREAMING_SNAKE_CASE_ ) A: Union[str, Any] = sorted(range(SCREAMING_SNAKE_CASE_ ) , reverse=SCREAMING_SNAKE_CASE_ , key=relevance_logits.__getitem__ ) A: List[DPRReaderOutput] = [] for doc_id in sorted_docs: A: List[str] = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence A: Dict = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: A: Union[str, Any] = sequence_ids.index(self.pad_token_id ) else: A: int = len(SCREAMING_SNAKE_CASE_ ) A: Dict = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=SCREAMING_SNAKE_CASE_ , top_spans=SCREAMING_SNAKE_CASE_ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=SCREAMING_SNAKE_CASE_ , start_index=SCREAMING_SNAKE_CASE_ , end_index=SCREAMING_SNAKE_CASE_ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(SCREAMING_SNAKE_CASE_ ) >= num_spans: break return nbest_spans_predictions[:num_spans] def _snake_case ( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : List[int] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , ) -> List[DPRSpanPrediction]: '''simple docstring''' A: Union[str, Any] = [] for start_index, start_score in enumerate(SCREAMING_SNAKE_CASE_ ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) A: Any = sorted(SCREAMING_SNAKE_CASE_ , key=lambda SCREAMING_SNAKE_CASE_ : x[1] , reverse=SCREAMING_SNAKE_CASE_ ) A: Dict = [] for (start_index, end_index), score in scores: assert start_index <= end_index, f"""Wrong span indices: [{start_index}:{end_index}]""" A: int = end_index - start_index + 1 assert length <= max_answer_length, f"""Span is too long: {length} > {max_answer_length}""" if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(SCREAMING_SNAKE_CASE_ ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCAmelCase_ ) class lowerCAmelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Tuple = VOCAB_FILES_NAMES UpperCamelCase_ : List[Any] = READER_PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Dict = READER_PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = ["""input_ids""", """attention_mask"""] UpperCamelCase_ : Optional[Any] = DPRReaderTokenizer
334
1
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCamelCase__ ( __lowerCAmelCase : str , __lowerCAmelCase : float | Decimal , __lowerCAmelCase : float = 10**-10 ): """simple docstring""" lowerCAmelCase_ = a while True: lowerCAmelCase_ = Decimal(__lowerCAmelCase ) - ( Decimal(eval(__lowerCAmelCase ) ) / Decimal(eval(str(diff(__lowerCAmelCase ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__lowerCAmelCase ) ) < precision: # noqa: S307 return float(__lowerCAmelCase ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f"""The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}""") # Find root of polynomial print(f"""The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}""") # Find Square Root of 5 print(f"""The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}""") # Exponential Roots print(f"""The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}""")
231
import requests _A = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def lowerCamelCase__ ( __lowerCAmelCase : str ): """simple docstring""" lowerCAmelCase_ = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["articles"] , 1 ): print(F"""{i}.) {article['title']}""" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
231
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCAmelCase : Optional[int] = logging.get_logger(__name__) _lowerCAmelCase : Dict = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class __magic_name__ ( lowerCamelCase__ ): """simple docstring""" __UpperCamelCase = '''data2vec-text''' def __init__( self :Union[str, Any] , snake_case :List[Any]=30_522 , snake_case :Union[str, Any]=768 , snake_case :Optional[int]=12 , snake_case :int=12 , snake_case :Dict=3_072 , snake_case :Union[str, Any]="gelu" , snake_case :List[Any]=0.1 , snake_case :Optional[int]=0.1 , snake_case :Tuple=512 , snake_case :Optional[Any]=2 , snake_case :List[str]=0.02 , snake_case :int=1e-12 , snake_case :Optional[int]=1 , snake_case :List[str]=0 , snake_case :Dict=2 , snake_case :Tuple="absolute" , snake_case :List[str]=True , snake_case :Optional[Any]=None , **snake_case :str , ): '''simple docstring''' super().__init__(pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , **snake_case ) A_ : List[Any] = vocab_size A_ : Any = hidden_size A_ : Tuple = num_hidden_layers A_ : Union[str, Any] = num_attention_heads A_ : List[str] = hidden_act A_ : Optional[Any] = intermediate_size A_ : Optional[Any] = hidden_dropout_prob A_ : Union[str, Any] = attention_probs_dropout_prob A_ : Optional[Any] = max_position_embeddings A_ : Optional[Any] = type_vocab_size A_ : Optional[int] = initializer_range A_ : Optional[int] = layer_norm_eps A_ : str = position_embedding_type A_ : List[str] = use_cache A_ : int = classifier_dropout class __magic_name__ ( lowerCamelCase__ ): """simple docstring""" @property def SCREAMING_SNAKE_CASE ( self :Optional[int] ): '''simple docstring''' if self.task == "multiple-choice": A_ : Any = {0: "batch", 1: "choice", 2: "sequence"} else: A_ : int = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
70
import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 _lowerCAmelCase : Union[str, Any] = { '''return_dict''': False, '''output_hidden_states''': True, '''output_attentions''': True, '''torchscript''': True, '''torch_dtype''': '''float16''', '''use_bfloat16''': True, '''tf_legacy_loss''': True, '''pruned_heads''': {'''a''': 1}, '''tie_word_embeddings''': False, '''is_decoder''': True, '''cross_attention_hidden_size''': 128, '''add_cross_attention''': True, '''tie_encoder_decoder''': True, '''max_length''': 50, '''min_length''': 3, '''do_sample''': True, '''early_stopping''': True, '''num_beams''': 3, '''num_beam_groups''': 3, '''diversity_penalty''': 0.5, '''temperature''': 2.0, '''top_k''': 10, '''top_p''': 0.7, '''typical_p''': 0.2, '''repetition_penalty''': 0.8, '''length_penalty''': 0.8, '''no_repeat_ngram_size''': 5, '''encoder_no_repeat_ngram_size''': 5, '''bad_words_ids''': [1, 2, 3], '''num_return_sequences''': 3, '''chunk_size_feed_forward''': 5, '''output_scores''': True, '''return_dict_in_generate''': True, '''forced_bos_token_id''': 2, '''forced_eos_token_id''': 3, '''remove_invalid_values''': True, '''architectures''': ['''BertModel'''], '''finetuning_task''': '''translation''', '''id2label''': {0: '''label'''}, '''label2id''': {'''label''': '''0'''}, '''tokenizer_class''': '''BertTokenizerFast''', '''prefix''': '''prefix''', '''bos_token_id''': 6, '''pad_token_id''': 7, '''eos_token_id''': 8, '''sep_token_id''': 9, '''decoder_start_token_id''': 10, '''exponential_decay_length_penalty''': (5, 1.01), '''suppress_tokens''': [0, 1], '''begin_suppress_tokens''': 2, '''task_specific_params''': {'''translation''': '''some_params'''}, '''problem_type''': '''regression''', } @is_staging_test class __magic_name__ ( unittest.TestCase ): """simple docstring""" @classmethod def SCREAMING_SNAKE_CASE ( cls :str ): '''simple docstring''' A_ : Tuple = TOKEN HfFolder.save_token(snake_case ) @classmethod def SCREAMING_SNAKE_CASE ( cls :List[str] ): '''simple docstring''' try: delete_repo(token=cls._token , repo_id="test-config" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-config-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-config" ) except HTTPError: pass def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' A_ : int = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("test-config" , use_auth_token=self._token ) A_ : Optional[Any] = BertConfig.from_pretrained(f"{USER}/test-config" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(snake_case , getattr(snake_case , snake_case ) ) # Reset repo delete_repo(token=self._token , repo_id="test-config" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(snake_case , repo_id="test-config" , push_to_hub=snake_case , use_auth_token=self._token ) A_ : Any = BertConfig.from_pretrained(f"{USER}/test-config" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(snake_case , getattr(snake_case , snake_case ) ) def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' A_ : List[Any] = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub("valid_org/test-config-org" , use_auth_token=self._token ) A_ : Optional[Any] = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(snake_case , getattr(snake_case , snake_case ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-config-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( snake_case , repo_id="valid_org/test-config-org" , push_to_hub=snake_case , use_auth_token=self._token ) A_ : Dict = BertConfig.from_pretrained("valid_org/test-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(snake_case , getattr(snake_case , snake_case ) ) def SCREAMING_SNAKE_CASE ( self :Optional[int] ): '''simple docstring''' CustomConfig.register_for_auto_class() A_ : Union[str, Any] = CustomConfig(attribute=42 ) config.push_to_hub("test-dynamic-config" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {"AutoConfig": "custom_configuration.CustomConfig"} ) A_ : Optional[int] = AutoConfig.from_pretrained(f"{USER}/test-dynamic-config" , trust_remote_code=snake_case ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , "CustomConfig" ) self.assertEqual(new_config.attribute , 42 ) class __magic_name__ ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self :Optional[Any] ): '''simple docstring''' A_ : List[Any] = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated A_ : Any = c.n_embd + 1 # int A_ : List[Any] = c.resid_pdrop + 1.0 # float A_ : Optional[int] = not c.scale_attn_weights # bool A_ : str = c.summary_type + "foo" # str c.update_from_string( f"n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}" ) self.assertEqual(snake_case , c.n_embd , "mismatch for key: n_embd" ) self.assertEqual(snake_case , c.resid_pdrop , "mismatch for key: resid_pdrop" ) self.assertEqual(snake_case , c.scale_attn_weights , "mismatch for key: scale_attn_weights" ) self.assertEqual(snake_case , c.summary_type , "mismatch for key: summary_type" ) def SCREAMING_SNAKE_CASE ( self :Any ): '''simple docstring''' A_ : Optional[int] = PretrainedConfig() A_ : Dict = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( snake_case , ["is_encoder_decoder", "_name_or_path", "_commit_hash", "transformers_version"] ) A_ : List[str] = [key for key, value in config_common_kwargs.items() if value == getattr(snake_case , snake_case )] if len(snake_case ) > 0: raise ValueError( "The following keys are set with the default values in" " `test_configuration_common.config_common_kwargs` pick another value for them:" f" {', '.join(snake_case )}." ) def SCREAMING_SNAKE_CASE ( self :Dict ): '''simple docstring''' with self.assertRaises(snake_case ): # config is in subfolder, the following should not work without specifying the subfolder A_ : int = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" ) A_ : int = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder" , subfolder="bert" ) self.assertIsNotNone(snake_case ) def SCREAMING_SNAKE_CASE ( self :Optional[int] ): '''simple docstring''' A_ : int = mock.Mock() A_ : Tuple = 500 A_ : str = {} A_ : Dict = HTTPError A_ : Dict = {} # Download this model to make sure it's in the cache. A_ : Dict = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=snake_case ) as mock_head: A_ : List[Any] = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE ( self :List[str] ): '''simple docstring''' A_ : List[str] = BertConfig.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json" ) def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' A_ : Tuple = AutoConfig.from_pretrained("bert-base-cased" ) A_ : Union[str, Any] = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(snake_case ) A_ : Union[str, Any] = 2 json.dump(configuration.to_dict() , open(os.path.join(snake_case , "config.4.0.0.json" ) , "w" ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 A_ : Dict = AutoConfig.from_pretrained(snake_case ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 A_ : Optional[Any] = ["config.42.0.0.json"] A_ : Optional[int] = 768 configuration.save_pretrained(snake_case ) shutil.move(os.path.join(snake_case , "config.4.0.0.json" ) , os.path.join(snake_case , "config.42.0.0.json" ) ) A_ : Dict = AutoConfig.from_pretrained(snake_case ) self.assertEqual(new_configuration.hidden_size , 768 ) def SCREAMING_SNAKE_CASE ( self :Optional[Any] ): '''simple docstring''' A_ : Any = "hf-internal-testing/test-two-configs" import transformers as new_transformers A_ : Optional[int] = "v4.0.0" A_ , A_ : Optional[Any] = new_transformers.models.auto.AutoConfig.from_pretrained( snake_case , return_unused_kwargs=snake_case ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(snake_case , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers A_ : Union[str, Any] = "v3.0.0" A_ : Dict = old_transformers.models.auto.AutoConfig.from_pretrained(snake_case ) self.assertEqual(old_configuration.hidden_size , 768 )
70
1
from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake UpperCAmelCase_ : Tuple = numpy.array([0, 0]) UpperCAmelCase_ : Any = numpy.array([0.5, 0.8_6_6_0_2_5_4]) UpperCAmelCase_ : Tuple = numpy.array([1, 0]) UpperCAmelCase_ : Optional[int] = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def SCREAMING_SNAKE_CASE_ ( __A : list[numpy.ndarray] , __A : int ) -> list[numpy.ndarray]: """simple docstring""" a_ : Tuple = initial_vectors for _ in range(__A ): a_ : Tuple = iteration_step(__A ) return vectors def SCREAMING_SNAKE_CASE_ ( __A : list[numpy.ndarray] ) -> list[numpy.ndarray]: """simple docstring""" a_ : Optional[int] = [] for i, start_vector in enumerate(vectors[:-1] ): a_ : int = vectors[i + 1] new_vectors.append(__A ) a_ : List[str] = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3 ) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 60 ) ) new_vectors.append(start_vector + difference_vector * 2 / 3 ) new_vectors.append(vectors[-1] ) return new_vectors def SCREAMING_SNAKE_CASE_ ( __A : numpy.ndarray , __A : float ) -> numpy.ndarray: """simple docstring""" a_ : Tuple = numpy.radians(__A ) a_ , a_ : List[str] = numpy.cos(__A ), numpy.sin(__A ) a_ : Optional[int] = numpy.array(((c, -s), (s, c)) ) return numpy.dot(__A , __A ) def SCREAMING_SNAKE_CASE_ ( __A : list[numpy.ndarray] ) -> None: """simple docstring""" a_ : int = plt.gca() axes.set_aspect('equal' ) # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() a_ , a_ : Any = zip(*__A ) plt.plot(__A , __A ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase_ : List[str] = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
32
import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : str = 'T5Config' def SCREAMING_SNAKE_CASE_ ( __A : jnp.array , __A : int , __A : int ) -> jnp.ndarray: """simple docstring""" a_ : Dict = jnp.zeros_like(__A ) a_ : Dict = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) a_ : str = shifted_input_ids.at[:, 0].set(__A ) a_ : int = jnp.where(shifted_input_ids == -1_00 , __A , __A ) return shifted_input_ids class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[Any] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : str = '''mt5''' snake_case__ : List[str] = MTaConfig class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = '''mt5''' snake_case__ : Union[str, Any] = MTaConfig
32
1
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def snake_case__ ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any]=True , SCREAMING_SNAKE_CASE_ : Optional[int]="pt" ): '''simple docstring''' lowercase__ : Union[str, Any] = {"add_prefix_space": True} if isinstance(_lowerCAmelCase , _lowerCAmelCase ) and not line.startswith(' ' ) else {} lowercase__ : Dict = padding_side return tokenizer( [line] , max_length=_lowerCAmelCase , padding='max_length' if pad_to_max_length else None , truncation=_lowerCAmelCase , return_tensors=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase , **_lowerCAmelCase , ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : int=None , ): '''simple docstring''' lowercase__ : Optional[Any] = input_ids.ne(_lowerCAmelCase ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class SCREAMING_SNAKE_CASE__ (lowerCamelCase__ ): def __init__( self , a , a , a , a , a="train" , a=None , a=None , a=None , a="" , ): super().__init__() lowercase__ : List[str] = Path(a).joinpath(type_path + '.source') lowercase__ : Any = Path(a).joinpath(type_path + '.target') lowercase__ : str = self.get_char_lens(self.src_file) lowercase__ : Tuple = max_source_length lowercase__ : int = max_target_length assert min(self.src_lens) > 0, f"""found empty line in {self.src_file}""" lowercase__ : str = tokenizer lowercase__ : List[Any] = prefix if n_obs is not None: lowercase__ : List[str] = self.src_lens[:n_obs] lowercase__ : Any = src_lang lowercase__ : Tuple = tgt_lang def __len__( self): return len(self.src_lens) def __getitem__( self , a): lowercase__ : Optional[int] = index + 1 # linecache starts at 1 lowercase__ : Optional[int] = self.prefix + linecache.getline(str(self.src_file) , a).rstrip('\n') lowercase__ : Union[str, Any] = linecache.getline(str(self.tgt_file) , a).rstrip('\n') assert source_line, f"""empty source line for index {index}""" assert tgt_line, f"""empty tgt line for index {index}""" # Need to add eos token manually for T5 if isinstance(self.tokenizer , a): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right lowercase__ : Tuple = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , a) else self.tokenizer ) lowercase__ : Union[str, Any] = self.tokenizer.generator if isinstance(self.tokenizer , a) else self.tokenizer lowercase__ : int = encode_line(a , a , self.max_source_length , 'right') lowercase__ : Optional[int] = encode_line(a , a , self.max_target_length , 'right') lowercase__ : str = source_inputs["input_ids"].squeeze() lowercase__ : Union[str, Any] = target_inputs["input_ids"].squeeze() lowercase__ : Dict = source_inputs["attention_mask"].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def snake_case_ ( a): return [len(a) for x in Path(a).open().readlines()] def snake_case_ ( self , a): lowercase__ : List[Any] = torch.stack([x['input_ids'] for x in batch]) lowercase__ : Tuple = torch.stack([x['attention_mask'] for x in batch]) lowercase__ : int = torch.stack([x['decoder_input_ids'] for x in batch]) lowercase__ : Union[str, Any] = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , a) else self.tokenizer.pad_token_id ) lowercase__ : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , a) else self.tokenizer.pad_token_id ) lowercase__ : Optional[Any] = trim_batch(a , a) lowercase__ : Optional[int] = trim_batch(a , a , attention_mask=a) lowercase__ : str = { "input_ids": source_ids, "attention_mask": source_mask, "decoder_input_ids": y, } return batch snake_case_ = getLogger(__name__) def snake_case__ ( SCREAMING_SNAKE_CASE_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(_lowerCAmelCase ) ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' lowercase__ : List[Any] = get_git_info() save_json(_lowerCAmelCase , os.path.join(_lowerCAmelCase , 'git_log.json' ) ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : str=4 , **SCREAMING_SNAKE_CASE_ : Dict ): '''simple docstring''' with open(_lowerCAmelCase , 'w' ) as f: json.dump(_lowerCAmelCase , _lowerCAmelCase , indent=_lowerCAmelCase , **_lowerCAmelCase ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : Optional[int] ): '''simple docstring''' with open(_lowerCAmelCase ) as f: return json.load(_lowerCAmelCase ) def snake_case__ ( ): '''simple docstring''' lowercase__ : Tuple = git.Repo(search_parent_directories=_lowerCAmelCase ) lowercase__ : List[str] = { "repo_id": str(_lowerCAmelCase ), "repo_sha": str(repo.head.object.hexsha ), "repo_branch": str(repo.active_branch ), "hostname": str(socket.gethostname() ), } return repo_infos def snake_case__ ( SCREAMING_SNAKE_CASE_ : Callable , SCREAMING_SNAKE_CASE_ : Iterable ): '''simple docstring''' return list(map(_lowerCAmelCase , _lowerCAmelCase ) ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[int] ): '''simple docstring''' with open(_lowerCAmelCase , 'wb' ) as f: return pickle.dump(_lowerCAmelCase , _lowerCAmelCase ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : Dict ): '''simple docstring''' def remove_articles(SCREAMING_SNAKE_CASE_ : Optional[Any] ): return re.sub(R'\b(a|an|the)\b' , ' ' , _lowerCAmelCase ) def white_space_fix(SCREAMING_SNAKE_CASE_ : List[str] ): return " ".join(text.split() ) def remove_punc(SCREAMING_SNAKE_CASE_ : List[str] ): lowercase__ : Tuple = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(SCREAMING_SNAKE_CASE_ : List[Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_lowerCAmelCase ) ) ) ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Dict ): '''simple docstring''' lowercase__ : List[str] = normalize_answer(_lowerCAmelCase ).split() lowercase__ : Optional[Any] = normalize_answer(_lowerCAmelCase ).split() lowercase__ : Tuple = Counter(_lowerCAmelCase ) & Counter(_lowerCAmelCase ) lowercase__ : List[Any] = sum(common.values() ) if num_same == 0: return 0 lowercase__ : List[str] = 1.0 * num_same / len(_lowerCAmelCase ) lowercase__ : Optional[int] = 1.0 * num_same / len(_lowerCAmelCase ) lowercase__ : Dict = (2 * precision * recall) / (precision + recall) return fa def snake_case__ ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple ): '''simple docstring''' return normalize_answer(_lowerCAmelCase ) == normalize_answer(_lowerCAmelCase ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[str] ): '''simple docstring''' assert len(_lowerCAmelCase ) == len(_lowerCAmelCase ) lowercase__ : List[Any] = 0 for hypo, pred in zip(_lowerCAmelCase , _lowerCAmelCase ): em += exact_match_score(_lowerCAmelCase , _lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: em /= len(_lowerCAmelCase ) return {"em": em} def snake_case__ ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): '''simple docstring''' return model_prefix.startswith('rag' ) def snake_case__ ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Dict ): '''simple docstring''' lowercase__ : Tuple = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead lowercase__ : int = "dropout_rate" for p in extra_params: if getattr(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): if not hasattr(_lowerCAmelCase , _lowerCAmelCase ) and not hasattr(_lowerCAmelCase , equivalent_param[p] ): logger.info('config doesn\'t have a `{}` attribute'.format(_lowerCAmelCase ) ) delattr(_lowerCAmelCase , _lowerCAmelCase ) continue lowercase__ : Union[str, Any] = p if hasattr(_lowerCAmelCase , _lowerCAmelCase ) else equivalent_param[p] setattr(_lowerCAmelCase , _lowerCAmelCase , getattr(_lowerCAmelCase , _lowerCAmelCase ) ) delattr(_lowerCAmelCase , _lowerCAmelCase ) return hparams, config
354
from __future__ import annotations class SCREAMING_SNAKE_CASE__ : def __init__( self , a , a): lowercase__ , lowercase__ : Dict = text, pattern lowercase__ , lowercase__ : Any = len(a), len(a) def snake_case_ ( self , a): for i in range(self.patLen - 1 , -1 , -1): if char == self.pattern[i]: return i return -1 def snake_case_ ( self , a): for i in range(self.patLen - 1 , -1 , -1): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def snake_case_ ( self): # searches pattern in text and returns index positions lowercase__ : Any = [] for i in range(self.textLen - self.patLen + 1): lowercase__ : Optional[Any] = self.mismatch_in_text(a) if mismatch_index == -1: positions.append(a) else: lowercase__ : Optional[int] = self.match_in_pattern(self.text[mismatch_index]) lowercase__ : Optional[Any] = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions snake_case_ = '''ABAABA''' snake_case_ = '''AB''' snake_case_ = BoyerMooreSearch(text, pattern) snake_case_ = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
216
0
'''simple docstring''' from dataclasses import dataclass, field from typing import Optional @dataclass class SCREAMING_SNAKE_CASE : lowerCAmelCase = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be trained.'''} ) lowerCAmelCase = field( default='''./''' , metadata={'''help''': '''Save dir where model repo is cloned and models updates are saved to.'''} ) lowerCAmelCase = field( default='''codeparrot/codeparrot-clean-train''' , metadata={'''help''': '''Name or path of training dataset.'''} ) lowerCAmelCase = field( default='''codeparrot/codeparrot-clean-valid''' , metadata={'''help''': '''Name or path of validation dataset.'''} ) lowerCAmelCase = field(default=2 , metadata={'''help''': '''Batch size for training.'''} ) lowerCAmelCase = field(default=2 , metadata={'''help''': '''Batch size for evaluation.'''} ) lowerCAmelCase = field(default=0.1 , metadata={'''help''': '''Value of weight decay.'''} ) lowerCAmelCase = field( default=1_0000 , metadata={'''help''': '''Size of buffer used to shuffle streaming dataset.'''} ) lowerCAmelCase = field(default=2E-4 , metadata={'''help''': '''Learning rate fo training.'''} ) lowerCAmelCase = field(default='''cosine''' , metadata={'''help''': '''Learning rate.'''} ) lowerCAmelCase = field( default=750 , metadata={'''help''': '''Number of warmup steps in the learning rate schedule.'''} ) lowerCAmelCase = field( default=16 , metadata={'''help''': '''Number of gradient accumulation steps.'''} ) lowerCAmelCase = field( default=_a , metadata={'''help''': '''Use gradient checkpointing to reduce memory footprint.'''} ) lowerCAmelCase = field(default=5_0000 , metadata={'''help''': '''Maximum number of training steps.'''} ) lowerCAmelCase = field( default=-1 , metadata={'''help''': '''Maximum number of evaluation steps. If -1 the full dataset is evaluated.'''} ) lowerCAmelCase = field(default=1024 , metadata={'''help''': '''Sequence lengths used for training.'''} ) lowerCAmelCase = field(default=1 , metadata={'''help''': '''Training seed.'''} ) lowerCAmelCase = field( default=1024 , metadata={'''help''': '''Interval to save checkpoints. Measured as number of forward passes not training steps.'''} , ) lowerCAmelCase = field( default=_a , metadata={'''help''': '''States path if the training should continue from a checkpoint folder.'''} ) lowerCAmelCase = field(default=_a , metadata={'''help''': '''If True the data is pretokenized.'''} ) @dataclass class SCREAMING_SNAKE_CASE : lowerCAmelCase = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be evaluated.'''} ) lowerCAmelCase = field( default='''codeparrot/codeparrot-clean-valid''' , metadata={'''help''': '''Name or path of validation dataset.'''} ) lowerCAmelCase = field(default=2 , metadata={'''help''': '''Batch size used for evaluation.'''} ) lowerCAmelCase = field( default=-1 , metadata={'''help''': '''Maximum number of evaluation steps. If -1 the full dataset is evaluated.'''} ) lowerCAmelCase = field(default=1024 , metadata={'''help''': '''Length of sequences to be evaluated.'''} ) lowerCAmelCase = field(default=1 , metadata={'''help''': '''Random seed used for evaluation.'''} ) @dataclass class SCREAMING_SNAKE_CASE : lowerCAmelCase = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be evaluated.'''} ) lowerCAmelCase = field(default=_a , metadata={'''help''': '''Number of workers used for code evaluation.'''} ) lowerCAmelCase = field( default=_a , metadata={'''help''': '''The number of human-eval tasks to run. If not included all tasks are evaluated.'''} , ) lowerCAmelCase = field( default=_a , metadata={'''help''': '''Sample from the language model\'s output distribution.'''} ) lowerCAmelCase = field(default=0.2 , metadata={'''help''': '''Sampling temperature used for generation.'''} ) lowerCAmelCase = field(default=256 , metadata={'''help''': '''Maximum number of newly generated tokens.'''} ) lowerCAmelCase = field(default=0 , metadata={'''help''': '''Top-k parameter used for generation.'''} ) lowerCAmelCase = field(default=0.95 , metadata={'''help''': '''Top-p parameter used for nucleus sampling.'''} ) lowerCAmelCase = field(default=10 , metadata={'''help''': '''Number of generations to run in parallel.'''} ) lowerCAmelCase = field( default=200 , metadata={'''help''': '''Number of completions to generate for each sample.'''} ) lowerCAmelCase = field(default=1 , metadata={'''help''': '''Random seed used for evaluation.'''} ) lowerCAmelCase = field( default='''eval_results.json''' , metadata={'''help''': '''Random seed used for evaluation.'''} ) lowerCAmelCase = field( default='''0''' , metadata={'''help''': '''Allow `code_eval` to execute Python code on machine'''} ) lowerCAmelCase = field( default=-1 , metadata={ '''help''': ( '''Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive''' ''' number corresponds to which GPU device id to run on.''' ) } , ) @dataclass class SCREAMING_SNAKE_CASE : lowerCAmelCase = field( default=_a , metadata={ '''help''': '''The number of CPU cores to use for parallel preprocessing. Default uses the maximum available.''' } , ) lowerCAmelCase = field( default='''transformersbook/codeparrot''' , metadata={'''help''': '''Folder or name of dataset to process.'''} ) lowerCAmelCase = field( default='''codeparrot-clean''' , metadata={'''help''': '''Folder to save processed processed dataset.'''} ) lowerCAmelCase = field( default=10_0000 , metadata={'''help''': '''Number of files to save per JSON output file.'''} ) lowerCAmelCase = field(default='''content''' , metadata={'''help''': '''Column containing text data to process.'''} ) lowerCAmelCase = field( default=1000 , metadata={'''help''': '''Maximum line length in file, otherwise file is filtered.'''} ) lowerCAmelCase = field( default=100 , metadata={'''help''': '''Maximum mean line length in file, otherwise file is filtered.'''} ) lowerCAmelCase = field( default=0.25 , metadata={'''help''': '''Maximum fraction of non-alphanumeric characters, otherwise file is filtered.'''} ) lowerCAmelCase = field( default=1.5 , metadata={'''help''': '''Minimum character token ratio for the file, otherwise file is filtered.'''} ) lowerCAmelCase = field( default=0.7 , metadata={'''help''': '''Probability for filtering config, test and uncommon files.'''} ) lowerCAmelCase = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Name or path to the tokenizer.'''} , ) lowerCAmelCase = field( default=_a , metadata={'''help''': '''If True, near-duplicate samples are removed.'''} ) lowerCAmelCase = field( default=0.85 , metadata={'''help''': '''Jaccard threshold for near-duplicate samples.'''} ) @dataclass class SCREAMING_SNAKE_CASE : lowerCAmelCase = field( default='''gpt2''' , metadata={'''help''': '''Base tokenizer to build new tokenizer from.'''} ) lowerCAmelCase = field( default='''transformersbook/codeparrot-train''' , metadata={'''help''': '''Dataset to train tokenizer on.'''} ) lowerCAmelCase = field(default='''content''' , metadata={'''help''': '''Column containing text data to process.'''} ) lowerCAmelCase = field(default=20_0000 , metadata={'''help''': '''Number of examples to train tokenizer on.'''} ) lowerCAmelCase = field( default=3_2768 , metadata={'''help''': '''Number of examples to train the tokenizer on.'''} ) lowerCAmelCase = field(default='''codeparrot''' , metadata={'''help''': '''Name of new tokenizer.'''} ) lowerCAmelCase = field(default=_a , metadata={'''help''': '''Push saved tokenizer to the hub.'''} ) @dataclass class SCREAMING_SNAKE_CASE : lowerCAmelCase = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Name or path to the tokenizer.'''} ) lowerCAmelCase = field( default='''codeparrot/codeparrot-clean-train''' , metadata={'''help''': '''Name or path to the dataset to pretokenize.'''} ) lowerCAmelCase = field( default='''tokenized-codeparrot-train''' , metadata={'''help''': '''Repo name of the pretokenized data.'''} ) lowerCAmelCase = field(default=_a , metadata={'''help''': '''Number of workers used for code evaluation.'''} ) @dataclass class SCREAMING_SNAKE_CASE : lowerCAmelCase = field( default='''gpt2-large''' , metadata={'''help''': '''Configuration to use for model initialization.'''} ) lowerCAmelCase = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Tokenizer attached to model.'''} ) lowerCAmelCase = field(default='''codeparrot''' , metadata={'''help''': '''Name of the created model.'''} ) lowerCAmelCase = field(default=_a , metadata={'''help''': '''Push saved tokenizer to the hub.'''} )
190
'''simple docstring''' import argparse import os import re __a = "src/transformers" # Pattern that looks at the indentation in a line. __a = re.compile(R"^(\s*)\S") # Pattern that matches `"key":" and puts `key` in group 0. __a = re.compile(R"^\s*\"([^\"]+)\":") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __a = re.compile(R"^\s*_import_structure\[\"([^\"]+)\"\]") # Pattern that matches `"key",` and puts `key` in group 0. __a = re.compile(R"^\s*\"([^\"]+)\",\s*$") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __a = re.compile(R"\[([^\]]+)\]") def __snake_case( _lowerCAmelCase ) -> List[Any]: snake_case__ : int = _re_indent.search(_lowerCAmelCase ) return "" if search is None else search.groups()[0] def __snake_case( _lowerCAmelCase , _lowerCAmelCase="" , _lowerCAmelCase=None , _lowerCAmelCase=None ) -> List[str]: snake_case__ : str = 0 snake_case__ : Union[str, Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(_lowerCAmelCase ): index += 1 snake_case__ : Tuple = ["""\n""".join(lines[:index] )] else: snake_case__ : List[str] = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). snake_case__ : Optional[int] = [lines[index]] index += 1 while index < len(_lowerCAmelCase ) and (end_prompt is None or not lines[index].startswith(_lowerCAmelCase )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_lowerCAmelCase ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(_lowerCAmelCase ) ) if index < len(_lowerCAmelCase ) - 1: snake_case__ : str = [lines[index + 1]] index += 1 else: snake_case__ : int = [] else: blocks.append("""\n""".join(_lowerCAmelCase ) ) snake_case__ : Optional[Any] = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_lowerCAmelCase ) > 0: blocks.append("""\n""".join(_lowerCAmelCase ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_lowerCAmelCase ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def __snake_case( _lowerCAmelCase ) -> Tuple: def _inner(_lowerCAmelCase ): return key(_lowerCAmelCase ).lower().replace("""_""" , """""" ) return _inner def __snake_case( _lowerCAmelCase , _lowerCAmelCase=None ) -> List[Any]: # If no key is provided, we use a noop. def noop(_lowerCAmelCase ): return x if key is None: snake_case__ : Optional[int] = noop # Constants are all uppercase, they go first. snake_case__ : Optional[int] = [obj for obj in objects if key(_lowerCAmelCase ).isupper()] # Classes are not all uppercase but start with a capital, they go second. snake_case__ : int = [obj for obj in objects if key(_lowerCAmelCase )[0].isupper() and not key(_lowerCAmelCase ).isupper()] # Functions begin with a lowercase, they go last. snake_case__ : str = [obj for obj in objects if not key(_lowerCAmelCase )[0].isupper()] snake_case__ : List[str] = ignore_underscore(_lowerCAmelCase ) return sorted(_lowerCAmelCase , key=_lowerCAmelCase ) + sorted(_lowerCAmelCase , key=_lowerCAmelCase ) + sorted(_lowerCAmelCase , key=_lowerCAmelCase ) def __snake_case( _lowerCAmelCase ) -> int: # This inner function sort imports between [ ]. def _replace(_lowerCAmelCase ): snake_case__ : Union[str, Any] = match.groups()[0] if "," not in imports: return f"[{imports}]" snake_case__ : int = [part.strip().replace("""\"""" , """""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: snake_case__ : List[str] = keys[:-1] return "[" + ", ".join([f"\"{k}\"" for k in sort_objects(_lowerCAmelCase )] ) + "]" snake_case__ : str = import_statement.split("""\n""" ) if len(_lowerCAmelCase ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. snake_case__ : Dict = 2 if lines[1].strip() == """[""" else 1 snake_case__ : str = [(i, _re_strip_line.search(_lowerCAmelCase ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] snake_case__ : str = sort_objects(_lowerCAmelCase , key=lambda _lowerCAmelCase : x[1] ) snake_case__ : Union[str, Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_lowerCAmelCase ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: snake_case__ : Union[str, Any] = _re_bracket_content.sub(_replace , lines[1] ) else: snake_case__ : List[Any] = [part.strip().replace("""\"""" , """""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: snake_case__ : List[str] = keys[:-1] snake_case__ : int = get_indent(lines[1] ) + """, """.join([f"\"{k}\"" for k in sort_objects(_lowerCAmelCase )] ) return "\n".join(_lowerCAmelCase ) else: # Finally we have to deal with imports fitting on one line snake_case__ : Optional[Any] = _re_bracket_content.sub(_replace , _lowerCAmelCase ) return import_statement def __snake_case( _lowerCAmelCase , _lowerCAmelCase=True ) -> Dict: with open(_lowerCAmelCase , encoding="""utf-8""" ) as f: snake_case__ : Optional[int] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 snake_case__ : Optional[int] = split_code_in_indented_blocks( _lowerCAmelCase , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(_lowerCAmelCase ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. snake_case__ : Optional[Any] = main_blocks[block_idx] snake_case__ : Dict = block.split("""\n""" ) # Get to the start of the imports. snake_case__ : Dict = 0 while line_idx < len(_lowerCAmelCase ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: snake_case__ : Union[str, Any] = len(_lowerCAmelCase ) else: line_idx += 1 if line_idx >= len(_lowerCAmelCase ): continue # Ignore beginning and last line: they don't contain anything. snake_case__ : List[str] = """\n""".join(block_lines[line_idx:-1] ) snake_case__ : str = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. snake_case__ : Optional[int] = split_code_in_indented_blocks(_lowerCAmelCase , indent_level=_lowerCAmelCase ) # We have two categories of import key: list or _import_structure[key].append/extend snake_case__ : Tuple = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. snake_case__ : Optional[Any] = [(pattern.search(_lowerCAmelCase ).groups()[0] if pattern.search(_lowerCAmelCase ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. snake_case__ : Dict = [(i, key) for i, key in enumerate(_lowerCAmelCase ) if key is not None] snake_case__ : Union[str, Any] = [x[0] for x in sorted(_lowerCAmelCase , key=lambda _lowerCAmelCase : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. snake_case__ : List[Any] = 0 snake_case__ : Optional[Any] = [] for i in range(len(_lowerCAmelCase ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: snake_case__ : Optional[Any] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(_lowerCAmelCase ) count += 1 # And we put our main block back together with its first and last line. snake_case__ : Dict = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(_lowerCAmelCase ): if check_only: return True else: print(f"Overwriting {file}." ) with open(_lowerCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write("""\n""".join(_lowerCAmelCase ) ) def __snake_case( _lowerCAmelCase=True ) -> Tuple: snake_case__ : str = [] for root, _, files in os.walk(_lowerCAmelCase ): if "__init__.py" in files: snake_case__ : Union[str, Any] = sort_imports(os.path.join(_lowerCAmelCase , """__init__.py""" ) , check_only=_lowerCAmelCase ) if result: snake_case__ : Union[str, Any] = [os.path.join(_lowerCAmelCase , """__init__.py""" )] if len(_lowerCAmelCase ) > 0: raise ValueError(f"Would overwrite {len(_lowerCAmelCase )} files, run `make style`." ) if __name__ == "__main__": __a = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") __a = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
35
0
"""simple docstring""" import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class a : @staticmethod def lowerCAmelCase_ ( *__lowerCAmelCase : Optional[Any] , **__lowerCAmelCase : Optional[int] ): pass @is_pipeline_test @require_torch @require_vision class a ( unittest.TestCase ): _snake_case : Optional[int] = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def lowerCAmelCase_ ( self : List[str] , __lowerCAmelCase : Any , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] ): _UpperCAmelCase = pipeline("""visual-question-answering""" , model="""hf-internal-testing/tiny-vilt-random-vqa""" ) _UpperCAmelCase = [ { """image""": Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """question""": """How many cats are there?""", }, { """image""": """./tests/fixtures/tests_samples/COCO/000000039769.png""", """question""": """How many cats are there?""", }, ] return vqa_pipeline, examples def lowerCAmelCase_ ( self : List[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] ): _UpperCAmelCase = vqa_pipeline(lowercase_ , top_k=1 ) self.assertEqual( lowercase_ , [ [{"""score""": ANY(lowercase_ ), """answer""": ANY(lowercase_ )}], [{"""score""": ANY(lowercase_ ), """answer""": ANY(lowercase_ )}], ] , ) @require_torch def lowerCAmelCase_ ( self : Dict ): _UpperCAmelCase = pipeline("""visual-question-answering""" , model="""hf-internal-testing/tiny-vilt-random-vqa""" ) _UpperCAmelCase = """./tests/fixtures/tests_samples/COCO/000000039769.png""" _UpperCAmelCase = """How many cats are there?""" _UpperCAmelCase = vqa_pipeline(image=lowercase_ , question="""How many cats are there?""" , top_k=2 ) self.assertEqual( lowercase_ , [{"""score""": ANY(lowercase_ ), """answer""": ANY(lowercase_ )}, {"""score""": ANY(lowercase_ ), """answer""": ANY(lowercase_ )}] ) _UpperCAmelCase = vqa_pipeline({"""image""": image, """question""": question} , top_k=2 ) self.assertEqual( lowercase_ , [{"""score""": ANY(lowercase_ ), """answer""": ANY(lowercase_ )}, {"""score""": ANY(lowercase_ ), """answer""": ANY(lowercase_ )}] ) @slow @require_torch def lowerCAmelCase_ ( self : Dict ): _UpperCAmelCase = pipeline("""visual-question-answering""" , model="""dandelin/vilt-b32-finetuned-vqa""" ) _UpperCAmelCase = """./tests/fixtures/tests_samples/COCO/000000039769.png""" _UpperCAmelCase = """How many cats are there?""" _UpperCAmelCase = vqa_pipeline(image=lowercase_ , question=lowercase_ , top_k=2 ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [{"""score""": 0.8_799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}] ) _UpperCAmelCase = vqa_pipeline({"""image""": image, """question""": question} , top_k=2 ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [{"""score""": 0.8_799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}] ) _UpperCAmelCase = vqa_pipeline( [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] , top_k=2 ) self.assertEqual( nested_simplify(lowercase_ , decimals=4 ) , [[{"""score""": 0.8_799, """answer""": """2"""}, {"""score""": 0.296, """answer""": """1"""}]] * 2 , ) @require_tf @unittest.skip("""Visual question answering not implemented in TF""" ) def lowerCAmelCase_ ( self : Optional[Any] ): pass
355
"""simple docstring""" import csv import tweepy # Twitter API credentials UpperCAmelCase__ = """""" UpperCAmelCase__ = """""" UpperCAmelCase__ = """""" UpperCAmelCase__ = """""" def __UpperCAmelCase ( lowercase ): """simple docstring""" # authorize twitter, initialize tweepy _UpperCAmelCase = tweepy.OAuthHandler(lowercase ,lowercase ) auth.set_access_token(lowercase ,lowercase ) _UpperCAmelCase = tweepy.API(lowercase ) # initialize a list to hold all the tweepy Tweets _UpperCAmelCase = [] # make initial request for most recent tweets (200 is the maximum allowed count) _UpperCAmelCase = api.user_timeline(screen_name=lowercase ,count=2_00 ) # save most recent tweets alltweets.extend(lowercase ) # save the id of the oldest tweet less one _UpperCAmelCase = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowercase ) > 0: print(f'''getting tweets before {oldest}''' ) # all subsequent requests use the max_id param to prevent duplicates _UpperCAmelCase = api.user_timeline( screen_name=lowercase ,count=2_00 ,max_id=lowercase ) # save most recent tweets alltweets.extend(lowercase ) # update the id of the oldest tweet less one _UpperCAmelCase = alltweets[-1].id - 1 print(f'''...{len(lowercase )} tweets downloaded so far''' ) # transform the tweepy tweets into a 2D array that will populate the csv _UpperCAmelCase = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(f'''new_{screen_name}_tweets.csv''' ,"""w""" ) as f: _UpperCAmelCase = csv.writer(lowercase ) writer.writerow(["""id""", """created_at""", """text"""] ) writer.writerows(lowercase ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
30
0
"""simple docstring""" import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging __UpperCamelCase = "\\n\n" __UpperCamelCase = "\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n" __UpperCamelCase = "\nArgs:\n model_id (str): model used for calculating Perplexity\n NOTE: Perplexity can only be calculated for causal language models.\n This includes models such as gpt2, causal variations of bert,\n causal versions of t5, and more (the full list can be found\n in the AutoModelForCausalLM documentation here:\n https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n input_texts (list of str): input text, each separate text snippet\n is one list entry.\n batch_size (int): the batch size to run texts through the model. Defaults to 16.\n add_start_token (bool): whether to add the start token to the texts,\n so the perplexity can include the probability of the first word. Defaults to True.\n device (str): device to run on, defaults to 'cuda' when available\nReturns:\n perplexity: dictionary containing the perplexity scores for the texts\n in the input list, as well as the mean perplexity. If one of the input texts is\n longer than the max input length of the model, then it is truncated to the\n max length for the perplexity computation.\nExamples:\n Example 1:\n >>> perplexity = datasets.load_metric(\"perplexity\")\n >>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"]\n >>> results = perplexity.compute(model_id='gpt2',\n ... add_start_token=False,\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n ['perplexities', 'mean_perplexity']\n >>> print(round(results[\"mean_perplexity\"], 2))\n 78.22\n >>> print(round(results[\"perplexities\"][0], 2))\n 11.11\n\n Example 2:\n >>> perplexity = datasets.load_metric(\"perplexity\")\n >>> input_texts = datasets.load_dataset(\"wikitext\",\n ... \"wikitext-2-raw-v1\",\n ... split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS\n [...]\n >>> input_texts = [s for s in input_texts if s!='']\n >>> results = perplexity.compute(model_id='gpt2',\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n ['perplexities', 'mean_perplexity']\n >>> print(round(results[\"mean_perplexity\"], 2))\n 60.35\n >>> print(round(results[\"perplexities\"][0], 2))\n 81.12\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def __A ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'input_texts': datasets.Value('string' ), } ) , reference_urls=['https://huggingface.co/docs/transformers/perplexity'] , ) def __A ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = 16 , lowerCAmelCase__ = True , lowerCAmelCase__=None ) -> Tuple: if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": SCREAMING_SNAKE_CASE = "cuda" else: SCREAMING_SNAKE_CASE = "cuda" if torch.cuda.is_available() else "cpu" SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_a ) SCREAMING_SNAKE_CASE = model.to(_a ) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(_a ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: SCREAMING_SNAKE_CASE = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(_a ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({'pad_token': existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" SCREAMING_SNAKE_CASE = model.config.max_length - 1 else: SCREAMING_SNAKE_CASE = model.config.max_length SCREAMING_SNAKE_CASE = tokenizer( _a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , return_tensors='pt' , return_attention_mask=_a , ).to(_a ) SCREAMING_SNAKE_CASE = encodings["input_ids"] SCREAMING_SNAKE_CASE = encodings["attention_mask"] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = CrossEntropyLoss(reduction='none' ) for start_index in logging.tqdm(range(0 , len(_a ) , _a ) ): SCREAMING_SNAKE_CASE = min(start_index + batch_size , len(_a ) ) SCREAMING_SNAKE_CASE = encoded_texts[start_index:end_index] SCREAMING_SNAKE_CASE = attn_masks[start_index:end_index] if add_start_token: SCREAMING_SNAKE_CASE = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(_a ) SCREAMING_SNAKE_CASE = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) SCREAMING_SNAKE_CASE = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(_a ), attn_mask] , dim=1 ) SCREAMING_SNAKE_CASE = encoded_batch with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_a , attention_mask=_a ).logits SCREAMING_SNAKE_CASE = out_logits[..., :-1, :].contiguous() SCREAMING_SNAKE_CASE = labels[..., 1:].contiguous() SCREAMING_SNAKE_CASE = attn_mask[..., 1:].contiguous() SCREAMING_SNAKE_CASE = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , _a ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(_a )}
113
snake_case : Optional[int] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowerCAmelCase_ ( _snake_case : bytes ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ): __magic_name__ : Tuple = F'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(_snake_case ) __magic_name__ : Optional[int] = "".join(bin(_snake_case )[2:].zfill(8 ) for byte in data ) __magic_name__ : List[Any] = len(_snake_case ) % 6 != 0 if padding_needed: # The padding that will be added later __magic_name__ : List[str] = B"=" * ((6 - len(_snake_case ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_snake_case ) % 6) else: __magic_name__ : List[str] = B"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(_snake_case ) , 6 ) ).encode() + padding ) def lowerCAmelCase_ ( _snake_case : str ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ) and not isinstance(_snake_case , _snake_case ): __magic_name__ : List[str] = ( "argument should be a bytes-like object or ASCII string, " F'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(_snake_case ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_snake_case , _snake_case ): try: __magic_name__ : List[Any] = encoded_data.decode("utf-8" ) except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters" ) __magic_name__ : List[str] = encoded_data.count("=" ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_snake_case ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __magic_name__ : Optional[int] = encoded_data[:-padding] __magic_name__ : Dict = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __magic_name__ : Union[str, Any] = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data ) __magic_name__ : List[Any] = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(_snake_case ) , 8 ) ] return bytes(_snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
281
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase__ : str ={'''configuration_vit_mae''': ['''VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTMAEConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : Optional[int] =[ '''VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ViTMAEForPreTraining''', '''ViTMAELayer''', '''ViTMAEModel''', '''ViTMAEPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : List[str] =[ '''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__ : Optional[int] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
368
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ : Optional[int] =logging.get_logger(__name__) def __lowercase ( a__ , a__=False ) -> Tuple: __SCREAMING_SNAKE_CASE = [] 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"""deit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""deit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""deit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""deit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""deit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""deit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""deit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""deit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""deit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""deit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ('cls_token', 'deit.embeddings.cls_token'), ('dist_token', 'deit.embeddings.distillation_token'), ('patch_embed.proj.weight', 'deit.embeddings.patch_embeddings.projection.weight'), ('patch_embed.proj.bias', 'deit.embeddings.patch_embeddings.projection.bias'), ('pos_embed', 'deit.embeddings.position_embeddings'), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ('pre_logits.fc.weight', 'pooler.dense.weight'), ('pre_logits.fc.bias', 'pooler.dense.bias'), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" __SCREAMING_SNAKE_CASE = [(pair[0], pair[1][4:]) if pair[1].startswith('deit' ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ('norm.weight', 'deit.layernorm.weight'), ('norm.bias', 'deit.layernorm.bias'), ('head.weight', 'cls_classifier.weight'), ('head.bias', 'cls_classifier.bias'), ('head_dist.weight', 'distillation_classifier.weight'), ('head_dist.bias', 'distillation_classifier.bias'), ] ) return rename_keys def __lowercase ( a__ , a__ , a__=False ) -> Tuple: for i in range(config.num_hidden_layers ): if base_model: __SCREAMING_SNAKE_CASE = '' else: __SCREAMING_SNAKE_CASE = 'deit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __SCREAMING_SNAKE_CASE = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) __SCREAMING_SNAKE_CASE = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict __SCREAMING_SNAKE_CASE = in_proj_weight[ : config.hidden_size, : ] __SCREAMING_SNAKE_CASE = in_proj_bias[: config.hidden_size] __SCREAMING_SNAKE_CASE = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __SCREAMING_SNAKE_CASE = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __SCREAMING_SNAKE_CASE = in_proj_weight[ -config.hidden_size :, : ] __SCREAMING_SNAKE_CASE = in_proj_bias[-config.hidden_size :] def __lowercase ( a__ , a__ , a__ ) -> str: __SCREAMING_SNAKE_CASE = dct.pop(a__ ) __SCREAMING_SNAKE_CASE = val def __lowercase ( ) -> List[Any]: __SCREAMING_SNAKE_CASE = 'http://images.cocodataset.org/val2017/000000039769.jpg' __SCREAMING_SNAKE_CASE = Image.open(requests.get(a__ , stream=a__ ).raw ) return im @torch.no_grad() def __lowercase ( a__ , a__ ) -> Dict: __SCREAMING_SNAKE_CASE = DeiTConfig() # all deit models have fine-tuned heads __SCREAMING_SNAKE_CASE = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size __SCREAMING_SNAKE_CASE = 10_00 __SCREAMING_SNAKE_CASE = 'huggingface/label-files' __SCREAMING_SNAKE_CASE = 'imagenet-1k-id2label.json' __SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(a__ , a__ , repo_type='dataset' ) , 'r' ) ) __SCREAMING_SNAKE_CASE = {int(a__ ): 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 = int(deit_name[-6:-4] ) __SCREAMING_SNAKE_CASE = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith('tiny' ): __SCREAMING_SNAKE_CASE = 1_92 __SCREAMING_SNAKE_CASE = 7_68 __SCREAMING_SNAKE_CASE = 12 __SCREAMING_SNAKE_CASE = 3 elif deit_name[9:].startswith('small' ): __SCREAMING_SNAKE_CASE = 3_84 __SCREAMING_SNAKE_CASE = 15_36 __SCREAMING_SNAKE_CASE = 12 __SCREAMING_SNAKE_CASE = 6 if deit_name[9:].startswith('base' ): pass elif deit_name[4:].startswith('large' ): __SCREAMING_SNAKE_CASE = 10_24 __SCREAMING_SNAKE_CASE = 40_96 __SCREAMING_SNAKE_CASE = 24 __SCREAMING_SNAKE_CASE = 16 # load original model from timm __SCREAMING_SNAKE_CASE = timm.create_model(a__ , pretrained=a__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys __SCREAMING_SNAKE_CASE = timm_model.state_dict() __SCREAMING_SNAKE_CASE = create_rename_keys(a__ , a__ ) for src, dest in rename_keys: rename_key(a__ , a__ , a__ ) read_in_q_k_v(a__ , a__ , a__ ) # load HuggingFace model __SCREAMING_SNAKE_CASE = DeiTForImageClassificationWithTeacher(a__ ).eval() model.load_state_dict(a__ ) # Check outputs on an image, prepared by DeiTImageProcessor __SCREAMING_SNAKE_CASE = int( (2_56 / 2_24) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 __SCREAMING_SNAKE_CASE = DeiTImageProcessor(size=a__ , crop_size=config.image_size ) __SCREAMING_SNAKE_CASE = image_processor(images=prepare_img() , return_tensors='pt' ) __SCREAMING_SNAKE_CASE = encoding['pixel_values'] __SCREAMING_SNAKE_CASE = model(a__ ) __SCREAMING_SNAKE_CASE = timm_model(a__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(a__ , outputs.logits , atol=1E-3 ) Path(a__ ).mkdir(exist_ok=a__ ) print(f"""Saving model {deit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(a__ ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(a__ ) if __name__ == "__main__": lowerCAmelCase__ : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--deit_name''', default='''vit_deit_base_distilled_patch16_224''', type=str, help='''Name of the DeiT 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.''' ) lowerCAmelCase__ : str =parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
118
0
from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker __a = 'CompVis/stable-diffusion-v1-1' __a = 'CompVis/stable-diffusion-v1-2' __a = 'CompVis/stable-diffusion-v1-3' __a = 'CompVis/stable-diffusion-v1-4' class lowercase__( __lowerCamelCase ): """simple docstring""" def __init__( self : str , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[str] = True , ) -> Optional[int]: super()._init_() lowercase_ = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowercase_ = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowercase_ = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ ) lowercase_ = StableDiffusionPipeline( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , requires_safety_checker=SCREAMING_SNAKE_CASE_ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def _lowercase ( self : Dict ) -> Tuple: return {k: getattr(self , SCREAMING_SNAKE_CASE_ ) for k in self.config.keys() if not k.startswith('''_''' )} def _lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] = "auto" ) -> List[Any]: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory lowercase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : int ) -> str: self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def _lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] = 5_1_2 , SCREAMING_SNAKE_CASE_ : Optional[Any] = 5_1_2 , SCREAMING_SNAKE_CASE_ : Any = 5_0 , SCREAMING_SNAKE_CASE_ : int = 7.5 , SCREAMING_SNAKE_CASE_ : int = None , SCREAMING_SNAKE_CASE_ : Dict = 1 , SCREAMING_SNAKE_CASE_ : List[str] = 0.0 , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : List[Any] = None , SCREAMING_SNAKE_CASE_ : Optional[Any] = "pil" , SCREAMING_SNAKE_CASE_ : List[Any] = True , SCREAMING_SNAKE_CASE_ : List[Any] = None , SCREAMING_SNAKE_CASE_ : Any = 1 , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> Optional[Any]: return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : str = 5_1_2 , SCREAMING_SNAKE_CASE_ : int = 5_1_2 , SCREAMING_SNAKE_CASE_ : Any = 5_0 , SCREAMING_SNAKE_CASE_ : Tuple = 7.5 , SCREAMING_SNAKE_CASE_ : Dict = None , SCREAMING_SNAKE_CASE_ : Optional[int] = 1 , SCREAMING_SNAKE_CASE_ : Any = 0.0 , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = None , SCREAMING_SNAKE_CASE_ : Any = "pil" , SCREAMING_SNAKE_CASE_ : Dict = True , SCREAMING_SNAKE_CASE_ : Any = None , SCREAMING_SNAKE_CASE_ : Any = 1 , **SCREAMING_SNAKE_CASE_ : Any , ) -> Optional[Any]: return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def _lowercase ( self : Dict , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[Any] = 5_1_2 , SCREAMING_SNAKE_CASE_ : Any = 5_1_2 , SCREAMING_SNAKE_CASE_ : Dict = 5_0 , SCREAMING_SNAKE_CASE_ : Union[str, Any] = 7.5 , SCREAMING_SNAKE_CASE_ : List[Any] = None , SCREAMING_SNAKE_CASE_ : Optional[int] = 1 , SCREAMING_SNAKE_CASE_ : Dict = 0.0 , SCREAMING_SNAKE_CASE_ : Dict = None , SCREAMING_SNAKE_CASE_ : List[str] = None , SCREAMING_SNAKE_CASE_ : Union[str, Any] = "pil" , SCREAMING_SNAKE_CASE_ : str = True , SCREAMING_SNAKE_CASE_ : List[str] = None , SCREAMING_SNAKE_CASE_ : int = 1 , **SCREAMING_SNAKE_CASE_ : Tuple , ) -> List[Any]: return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def _lowercase ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[str] = 5_1_2 , SCREAMING_SNAKE_CASE_ : Dict = 5_1_2 , SCREAMING_SNAKE_CASE_ : Optional[int] = 5_0 , SCREAMING_SNAKE_CASE_ : List[Any] = 7.5 , SCREAMING_SNAKE_CASE_ : Optional[Any] = None , SCREAMING_SNAKE_CASE_ : str = 1 , SCREAMING_SNAKE_CASE_ : Union[str, Any] = 0.0 , SCREAMING_SNAKE_CASE_ : int = None , SCREAMING_SNAKE_CASE_ : Tuple = None , SCREAMING_SNAKE_CASE_ : Any = "pil" , SCREAMING_SNAKE_CASE_ : str = True , SCREAMING_SNAKE_CASE_ : Any = None , SCREAMING_SNAKE_CASE_ : int = 1 , **SCREAMING_SNAKE_CASE_ : Dict , ) -> Optional[int]: return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def _lowercase ( self : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : List[Any] = 5_1_2 , SCREAMING_SNAKE_CASE_ : Optional[int] = 5_1_2 , SCREAMING_SNAKE_CASE_ : Optional[int] = 5_0 , SCREAMING_SNAKE_CASE_ : List[Any] = 7.5 , SCREAMING_SNAKE_CASE_ : Any = None , SCREAMING_SNAKE_CASE_ : Union[str, Any] = 1 , SCREAMING_SNAKE_CASE_ : Optional[int] = 0.0 , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : str = None , SCREAMING_SNAKE_CASE_ : int = "pil" , SCREAMING_SNAKE_CASE_ : Any = True , SCREAMING_SNAKE_CASE_ : List[Any] = None , SCREAMING_SNAKE_CASE_ : List[str] = 1 , **SCREAMING_SNAKE_CASE_ : Tuple , ) -> Dict: lowercase_ = '''cuda''' if torch.cuda.is_available() else '''cpu''' self.to(SCREAMING_SNAKE_CASE_ ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` must be divisible by 8 but are {height} and {width}.''' ) # Get first result from Stable Diffusion Checkpoint v1.1 lowercase_ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get first result from Stable Diffusion Checkpoint v1.2 lowercase_ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get first result from Stable Diffusion Checkpoint v1.3 lowercase_ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get first result from Stable Diffusion Checkpoint v1.4 lowercase_ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
30
from collections.abc import Generator def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = 0, 1 while True: UpperCamelCase__ , UpperCamelCase__ = b, a + b yield b def __magic_name__ ( __a : int = 1_000 ): '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = fibonacci_generator() while len(str(next(__a ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
244
0
"""simple docstring""" import tensorflow as tf from ...tf_utils import shape_list class A_ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self :List[Any] , lowercase_ :Union[str, Any] , lowercase_ :List[Any] , lowercase_ :List[Any] , lowercase_ :str , lowercase_ :List[Any]=1 , lowercase_ :Dict=False , **lowercase_ :List[Any] ) -> Union[str, Any]: super().__init__(**lowercase_ ) UpperCAmelCase = vocab_size UpperCAmelCase = d_embed UpperCAmelCase = d_proj UpperCAmelCase = cutoffs + [vocab_size] UpperCAmelCase = [0] + self.cutoffs UpperCAmelCase = div_val UpperCAmelCase = self.cutoffs[0] UpperCAmelCase = len(self.cutoffs ) - 1 UpperCAmelCase = self.shortlist_size + self.n_clusters UpperCAmelCase = keep_order UpperCAmelCase = [] UpperCAmelCase = [] def UpperCAmelCase__ ( self :Any , lowercase_ :Any ) -> Tuple: if self.n_clusters > 0: UpperCAmelCase = self.add_weight( shape=(self.n_clusters, self.d_embed) , initializer='zeros' , trainable=lowercase_ , name='cluster_weight' ) UpperCAmelCase = self.add_weight( shape=(self.n_clusters,) , initializer='zeros' , trainable=lowercase_ , name='cluster_bias' ) if self.div_val == 1: for i in range(len(self.cutoffs ) ): if self.d_proj != self.d_embed: UpperCAmelCase = self.add_weight( shape=(self.d_embed, self.d_proj) , initializer='zeros' , trainable=lowercase_ , name=f"""out_projs_._{i}""" , ) self.out_projs.append(lowercase_ ) else: self.out_projs.append(lowercase_ ) UpperCAmelCase = self.add_weight( shape=(self.vocab_size, self.d_embed) , initializer='zeros' , trainable=lowercase_ , name=f"""out_layers_._{i}_._weight""" , ) UpperCAmelCase = self.add_weight( shape=(self.vocab_size,) , initializer='zeros' , trainable=lowercase_ , name=f"""out_layers_._{i}_._bias""" , ) self.out_layers.append((weight, bias) ) else: for i in range(len(self.cutoffs ) ): UpperCAmelCase , UpperCAmelCase = self.cutoff_ends[i], self.cutoff_ends[i + 1] UpperCAmelCase = self.d_embed // (self.div_val**i) UpperCAmelCase = self.add_weight( shape=(d_emb_i, self.d_proj) , initializer='zeros' , trainable=lowercase_ , name=f"""out_projs_._{i}""" ) self.out_projs.append(lowercase_ ) UpperCAmelCase = self.add_weight( shape=(r_idx - l_idx, d_emb_i) , initializer='zeros' , trainable=lowercase_ , name=f"""out_layers_._{i}_._weight""" , ) UpperCAmelCase = self.add_weight( shape=(r_idx - l_idx,) , initializer='zeros' , trainable=lowercase_ , name=f"""out_layers_._{i}_._bias""" , ) self.out_layers.append((weight, bias) ) super().build(lowercase_ ) @staticmethod def UpperCAmelCase__ ( lowercase_ :str , lowercase_ :Union[str, Any] , lowercase_ :List[str] , lowercase_ :Tuple=None ) -> Optional[int]: UpperCAmelCase = x if proj is not None: UpperCAmelCase = tf.einsum('ibd,ed->ibe' , lowercase_ , lowercase_ ) return tf.einsum('ibd,nd->ibn' , lowercase_ , lowercase_ ) + b @staticmethod def UpperCAmelCase__ ( lowercase_ :Dict , lowercase_ :Optional[int] ) -> Optional[Any]: UpperCAmelCase = shape_list(lowercase_ ) UpperCAmelCase = tf.range(lp_size[0] , dtype=target.dtype ) UpperCAmelCase = tf.stack([r, target] , 1 ) return tf.gather_nd(lowercase_ , lowercase_ ) def UpperCAmelCase__ ( self :Optional[Any] , lowercase_ :int , lowercase_ :Dict , lowercase_ :int=True , lowercase_ :Any=False ) -> Optional[Any]: UpperCAmelCase = 0 if self.n_clusters == 0: UpperCAmelCase = self._logit(lowercase_ , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0] ) if target is not None: UpperCAmelCase = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=lowercase_ , logits=lowercase_ ) UpperCAmelCase = tf.nn.log_softmax(lowercase_ , axis=-1 ) else: UpperCAmelCase = shape_list(lowercase_ ) UpperCAmelCase = [] UpperCAmelCase = tf.zeros(hidden_sizes[:2] ) for i in range(len(self.cutoffs ) ): UpperCAmelCase , UpperCAmelCase = self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: UpperCAmelCase = (target >= l_idx) & (target < r_idx) UpperCAmelCase = tf.where(lowercase_ ) UpperCAmelCase = tf.boolean_mask(lowercase_ , lowercase_ ) - l_idx if self.div_val == 1: UpperCAmelCase = self.out_layers[0][0][l_idx:r_idx] UpperCAmelCase = self.out_layers[0][1][l_idx:r_idx] else: UpperCAmelCase = self.out_layers[i][0] UpperCAmelCase = self.out_layers[i][1] if i == 0: UpperCAmelCase = tf.concat([cur_W, self.cluster_weight] , 0 ) UpperCAmelCase = tf.concat([cur_b, self.cluster_bias] , 0 ) UpperCAmelCase = self._logit(lowercase_ , lowercase_ , lowercase_ , self.out_projs[0] ) UpperCAmelCase = tf.nn.log_softmax(lowercase_ ) out.append(head_logprob[..., : self.cutoffs[0]] ) if target is not None: UpperCAmelCase = tf.boolean_mask(lowercase_ , lowercase_ ) UpperCAmelCase = self._gather_logprob(lowercase_ , lowercase_ ) else: UpperCAmelCase = self._logit(lowercase_ , lowercase_ , lowercase_ , self.out_projs[i] ) UpperCAmelCase = tf.nn.log_softmax(lowercase_ ) UpperCAmelCase = self.cutoffs[0] + i - 1 # No probability for the head cluster UpperCAmelCase = head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(lowercase_ ) if target is not None: UpperCAmelCase = tf.boolean_mask(lowercase_ , lowercase_ ) UpperCAmelCase = tf.boolean_mask(lowercase_ , lowercase_ ) UpperCAmelCase = self._gather_logprob(lowercase_ , lowercase_ ) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(lowercase_ , -cur_logprob , shape_list(lowercase_ ) ) UpperCAmelCase = tf.concat(lowercase_ , axis=-1 ) if target is not None: if return_mean: UpperCAmelCase = tf.reduce_mean(lowercase_ ) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(lowercase_ ) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(lowercase_ , name=self.name , aggregation='mean' if return_mean else '' ) return out
181
"""simple docstring""" def _lowerCAmelCase ( ): for n in range(1 , 1000000 ): yield n * (n + 1) // 2 def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = 1 UpperCAmelCase = 2 while i * i <= n: UpperCAmelCase = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _lowerCAmelCase ( ): return next(i for i in triangle_number_generator() if count_divisors(lowercase_ ) > 500 ) if __name__ == "__main__": print(solution())
181
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() __lowerCAmelCase : List[Any] = logging.get_logger(__name__) def UpperCAmelCase_ ( __lowerCAmelCase ) -> Optional[Any]: __lowercase : Optional[Any] = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: __lowercase : List[str] = 192 __lowercase : Union[str, Any] = 768 __lowercase : Dict = 12 __lowercase : Dict = 3 __lowercase : Optional[int] = [800, 1_333] __lowercase : str = False elif yolos_name == "yolos_s_dWr": __lowercase : Union[str, Any] = 330 __lowercase : Dict = 14 __lowercase : Any = 6 __lowercase : int = 1_320 elif "yolos_s" in yolos_name: __lowercase : List[Any] = 384 __lowercase : Any = 1_536 __lowercase : Dict = 12 __lowercase : Optional[Any] = 6 elif "yolos_b" in yolos_name: __lowercase : int = [800, 1_344] __lowercase : Tuple = 91 __lowercase : Tuple = "huggingface/label-files" __lowercase : Dict = "coco-detection-id2label.json" __lowercase : List[str] = json.load(open(hf_hub_download(__lowerCAmelCase , __lowerCAmelCase , repo_type='''dataset''' ) , '''r''' ) ) __lowercase : Tuple = {int(__lowerCAmelCase ): v for k, v in idalabel.items()} __lowercase : int = idalabel __lowercase : Tuple = {v: k for k, v in idalabel.items()} return config def UpperCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> Union[str, Any]: for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __lowercase : str = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) __lowercase : List[Any] = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict __lowercase : List[str] = in_proj_weight[: config.hidden_size, :] __lowercase : int = in_proj_bias[: config.hidden_size] __lowercase : Optional[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __lowercase : Any = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __lowercase : Any = in_proj_weight[-config.hidden_size :, :] __lowercase : Optional[int] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase_ ( __lowerCAmelCase ) -> Union[str, Any]: if "backbone" in name: __lowercase : str = name.replace('''backbone''' , '''vit''' ) if "cls_token" in name: __lowercase : int = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "det_token" in name: __lowercase : Optional[int] = name.replace('''det_token''' , '''embeddings.detection_tokens''' ) if "mid_pos_embed" in name: __lowercase : List[str] = name.replace('''mid_pos_embed''' , '''encoder.mid_position_embeddings''' ) if "pos_embed" in name: __lowercase : Optional[Any] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: __lowercase : Any = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "blocks" in name: __lowercase : str = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: __lowercase : List[Any] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: __lowercase : int = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: __lowercase : Any = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: __lowercase : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: __lowercase : Tuple = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: __lowercase : Dict = name.replace('''mlp.fc2''' , '''output.dense''' ) if "class_embed" in name: __lowercase : str = name.replace('''class_embed''' , '''class_labels_classifier''' ) if "bbox_embed" in name: __lowercase : List[str] = name.replace('''bbox_embed''' , '''bbox_predictor''' ) if "vit.norm" in name: __lowercase : List[Any] = name.replace('''vit.norm''' , '''vit.layernorm''' ) return name def UpperCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]: for key in orig_state_dict.copy().keys(): __lowercase : int = orig_state_dict.pop(__lowerCAmelCase ) if "qkv" in key: __lowercase : List[Any] = key.split('''.''' ) __lowercase : Optional[Any] = int(key_split[2] ) __lowercase : List[Any] = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: __lowercase : str = val[:dim, :] __lowercase : Optional[Any] = val[ dim : dim * 2, : ] __lowercase : Dict = val[-dim:, :] else: __lowercase : Optional[Any] = val[:dim] __lowercase : List[str] = val[dim : dim * 2] __lowercase : List[str] = val[-dim:] else: __lowercase : str = val return orig_state_dict def UpperCAmelCase_ ( ) -> List[Any]: __lowercase : str = "http://images.cocodataset.org/val2017/000000039769.jpg" __lowercase : int = Image.open(requests.get(__lowerCAmelCase , stream=__lowerCAmelCase ).raw ) return im @torch.no_grad() def UpperCAmelCase_ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = False ) -> List[str]: __lowercase : List[str] = get_yolos_config(__lowerCAmelCase ) # load original state_dict __lowercase : Optional[Any] = torch.load(__lowerCAmelCase , map_location='''cpu''' )["model"] # load 🤗 model __lowercase : Optional[Any] = YolosForObjectDetection(__lowerCAmelCase ) model.eval() __lowercase : Any = convert_state_dict(__lowerCAmelCase , __lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) # Check outputs on an image, prepared by YolosImageProcessor __lowercase : Tuple = 800 if yolos_name != "yolos_ti" else 512 __lowercase : Union[str, Any] = YolosImageProcessor(format='''coco_detection''' , size=__lowerCAmelCase ) __lowercase : Optional[Any] = image_processor(images=prepare_img() , return_tensors='''pt''' ) __lowercase : List[Any] = model(**__lowerCAmelCase ) __lowercase : Optional[Any] = outputs.logits, outputs.pred_boxes __lowercase : List[Any] = None, None if yolos_name == "yolos_ti": __lowercase : Any = torch.tensor( [[-39.5_022, -11.9_820, -17.6_888], [-29.9_574, -9.9769, -17.7_691], [-42.3_281, -20.7_200, -30.6_294]] ) __lowercase : Union[str, Any] = torch.tensor( [[0.4021, 0.0836, 0.7979], [0.0184, 0.2609, 0.0364], [0.1781, 0.2004, 0.2095]] ) elif yolos_name == "yolos_s_200_pre": __lowercase : str = torch.tensor( [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]] ) __lowercase : Tuple = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] ) elif yolos_name == "yolos_s_300_pre": __lowercase : Dict = torch.tensor( [[-36.2_220, -14.4_385, -23.5_457], [-35.6_970, -14.7_583, -21.3_935], [-31.5_939, -13.6_042, -16.8_049]] ) __lowercase : Optional[int] = torch.tensor( [[0.7614, 0.2316, 0.4728], [0.7168, 0.4495, 0.3855], [0.4996, 0.1466, 0.9996]] ) elif yolos_name == "yolos_s_dWr": __lowercase : Union[str, Any] = torch.tensor( [[-42.8_668, -24.1_049, -41.1_690], [-34.7_456, -14.1_274, -24.9_194], [-33.7_898, -12.1_946, -25.6_495]] ) __lowercase : Optional[Any] = torch.tensor( [[0.5587, 0.2773, 0.0605], [0.5004, 0.3014, 0.9994], [0.4999, 0.1548, 0.9994]] ) elif yolos_name == "yolos_base": __lowercase : List[Any] = torch.tensor( [[-40.6_064, -24.3_084, -32.6_447], [-55.1_990, -30.7_719, -35.5_877], [-51.4_311, -33.3_507, -35.6_462]] ) __lowercase : Tuple = torch.tensor( [[0.5555, 0.2794, 0.0655], [0.9049, 0.2664, 0.1894], [0.9183, 0.1984, 0.1635]] ) else: raise ValueError(F'Unknown yolos_name: {yolos_name}' ) assert torch.allclose(logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , __lowerCAmelCase , atol=1E-4 ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) print(F'Saving model {yolos_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__lowerCAmelCase ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: __lowercase : Dict = { "yolos_ti": "yolos-tiny", "yolos_s_200_pre": "yolos-small", "yolos_s_300_pre": "yolos-small-300", "yolos_s_dWr": "yolos-small-dwr", "yolos_base": "yolos-base", } print('''Pushing to the hub...''' ) __lowercase : int = model_mapping[yolos_name] image_processor.push_to_hub(__lowerCAmelCase , organization='''hustvl''' ) model.push_to_hub(__lowerCAmelCase , organization='''hustvl''' ) if __name__ == "__main__": __lowerCAmelCase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--yolos_name", default="yolos_s_200_pre", type=str, help=( "Name of the YOLOS model you'd like to convert. Should be one of 'yolos_ti', 'yolos_s_200_pre'," " 'yolos_s_300_pre', 'yolos_s_dWr', 'yolos_base'." ), ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original state dict (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) __lowerCAmelCase : str = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
156
def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) if len(SCREAMING_SNAKE_CASE ) == 1: return True a__ : Union[str, Any] =series[1] - series[0] for index in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def _A ( SCREAMING_SNAKE_CASE : list ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Input list must be a non empty list" ) a__ : Any =0 for val in series: answer += val return answer / len(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
95
0
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class A ( lowercase__ , unittest.TestCase ): UpperCamelCase_ : List[Any] =CTRLTokenizer UpperCamelCase_ : Optional[Any] =False UpperCamelCase_ : Union[str, Any] =False def _A (self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __lowercase= ['adapt', 're@@', 'a@@', 'apt', 'c@@', 't', '<unk>'] __lowercase= dict(zip(_a , range(len(_a ) ) ) ) __lowercase= ['#version: 0.2', 'a p', 'ap t</w>', 'r e', 'a d', 'ad apt</w>', ''] __lowercase= {'unk_token': '<unk>'} __lowercase= os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowercase= os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_a ) ) def _A (self , **lowerCAmelCase ): kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **_a ) def _A (self , lowerCAmelCase ): __lowercase= 'adapt react readapt apt' __lowercase= 'adapt react readapt apt' return input_text, output_text def _A (self ): __lowercase= CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowercase= 'adapt react readapt apt' __lowercase= 'adapt re@@ a@@ c@@ t re@@ adapt apt'.split() __lowercase= tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) __lowercase= tokens + [tokenizer.unk_token] __lowercase= [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , _a )
355
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 A : def __init__(self , lowerCAmelCase , lowerCAmelCase=1_3 , lowerCAmelCase=7 , lowerCAmelCase=True , lowerCAmelCase=True , lowerCAmelCase=True , lowerCAmelCase=True , lowerCAmelCase=True , lowerCAmelCase=False , lowerCAmelCase=False , lowerCAmelCase=False , lowerCAmelCase=2 , lowerCAmelCase=9_9 , lowerCAmelCase=0 , lowerCAmelCase=3_2 , lowerCAmelCase=5 , lowerCAmelCase=4 , lowerCAmelCase=0.1 , lowerCAmelCase=0.1 , lowerCAmelCase=5_1_2 , lowerCAmelCase=2 , lowerCAmelCase=0.02 , lowerCAmelCase=2 , lowerCAmelCase=4 , lowerCAmelCase="last" , lowerCAmelCase=True , lowerCAmelCase=None , lowerCAmelCase=0 , ): __lowercase= parent __lowercase= batch_size __lowercase= seq_length __lowercase= is_training __lowercase= use_input_lengths __lowercase= use_token_type_ids __lowercase= use_labels __lowercase= gelu_activation __lowercase= sinusoidal_embeddings __lowercase= causal __lowercase= asm __lowercase= n_langs __lowercase= vocab_size __lowercase= n_special __lowercase= hidden_size __lowercase= num_hidden_layers __lowercase= num_attention_heads __lowercase= hidden_dropout_prob __lowercase= attention_probs_dropout_prob __lowercase= max_position_embeddings __lowercase= type_sequence_label_size __lowercase= initializer_range __lowercase= num_labels __lowercase= num_choices __lowercase= summary_type __lowercase= use_proj __lowercase= scope __lowercase= bos_token_id def _A (self ): __lowercase= ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase= random_attention_mask([self.batch_size, self.seq_length] ) __lowercase= None if self.use_input_lengths: __lowercase= ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __lowercase= None if self.use_token_type_ids: __lowercase= ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __lowercase= None __lowercase= None __lowercase= None if self.use_labels: __lowercase= ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowercase= ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowercase= ids_tensor([self.batch_size] , 2 ).float() __lowercase= ids_tensor([self.batch_size] , self.num_choices ) __lowercase= self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _A (self ): 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 _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): __lowercase= XLMModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() __lowercase= model(lowerCAmelCase , lengths=lowerCAmelCase , langs=lowerCAmelCase ) __lowercase= model(lowerCAmelCase , langs=lowerCAmelCase ) __lowercase= model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): __lowercase= XLMWithLMHeadModel(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() __lowercase= model(lowerCAmelCase , token_type_ids=lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): __lowercase= XLMForQuestionAnsweringSimple(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() __lowercase= model(lowerCAmelCase ) __lowercase= model(lowerCAmelCase , start_positions=lowerCAmelCase , end_positions=lowerCAmelCase ) __lowercase= 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 _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): __lowercase= XLMForQuestionAnswering(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() __lowercase= model(lowerCAmelCase ) __lowercase= model( lowerCAmelCase , start_positions=lowerCAmelCase , end_positions=lowerCAmelCase , cls_index=lowerCAmelCase , is_impossible=lowerCAmelCase , p_mask=lowerCAmelCase , ) __lowercase= model( lowerCAmelCase , start_positions=lowerCAmelCase , end_positions=lowerCAmelCase , cls_index=lowerCAmelCase , is_impossible=lowerCAmelCase , ) ((__lowercase), )= result_with_labels.to_tuple() __lowercase= model(lowerCAmelCase , start_positions=lowerCAmelCase , end_positions=lowerCAmelCase ) ((__lowercase), )= 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 _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): __lowercase= XLMForSequenceClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() __lowercase= model(lowerCAmelCase ) __lowercase= model(lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): __lowercase= self.num_labels __lowercase= XLMForTokenClassification(lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() __lowercase= model(lowerCAmelCase , attention_mask=lowerCAmelCase , labels=lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): __lowercase= self.num_choices __lowercase= XLMForMultipleChoice(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() __lowercase= input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowercase= token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowercase= input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowercase= model( lowerCAmelCase , attention_mask=lowerCAmelCase , token_type_ids=lowerCAmelCase , labels=lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _A (self ): __lowercase= self.prepare_config_and_inputs() ( ( __lowercase ), ( __lowercase ), ( __lowercase ), ( __lowercase ), ( __lowercase ), ( __lowercase ), ( __lowercase ), ( __lowercase ), ( __lowercase ), )= config_and_inputs __lowercase= {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class A ( A_ , A_ , A_ , unittest.TestCase ): UpperCamelCase_ : int =( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) UpperCamelCase_ : Dict =( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable UpperCamelCase_ : 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 _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): 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 _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False ): __lowercase= super()._prepare_for_class(lowerCAmelCase , lowerCAmelCase , return_labels=lowerCAmelCase ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": __lowercase= torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowerCAmelCase ) __lowercase= torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowerCAmelCase ) return inputs_dict def _A (self ): __lowercase= XLMModelTester(self ) __lowercase= ConfigTester(self , config_class=lowerCAmelCase , emb_dim=3_7 ) def _A (self ): self.config_tester.run_common_tests() def _A (self ): __lowercase= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*lowerCAmelCase ) def _A (self ): __lowercase= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*lowerCAmelCase ) def _A (self ): __lowercase= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*lowerCAmelCase ) def _A (self ): __lowercase= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*lowerCAmelCase ) def _A (self ): __lowercase= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*lowerCAmelCase ) def _A (self ): __lowercase= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*lowerCAmelCase ) def _A (self ): __lowercase= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*lowerCAmelCase ) def _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False , lowerCAmelCase=1 ): self.assertIsInstance(lowerCAmelCase , lowerCAmelCase ) self.assertListEqual( [isinstance(lowerCAmelCase , lowerCAmelCase ) for iter_attentions in attentions] , [True] * len(lowerCAmelCase ) ) self.assertEqual(len(lowerCAmelCase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(lowerCAmelCase ): # adds PAD dummy token __lowercase= min_length + idx + 1 __lowercase= min_length + idx + 1 __lowercase= ( 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(lowerCAmelCase ) ) def _A (self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False , lowerCAmelCase=1 ): self.assertIsInstance(lowerCAmelCase , lowerCAmelCase ) self.assertListEqual( [isinstance(lowerCAmelCase , lowerCAmelCase ) for iter_hidden_states in hidden_states] , [True] * len(lowerCAmelCase ) , ) self.assertEqual(len(lowerCAmelCase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(lowerCAmelCase ): # adds PAD dummy token __lowercase= min_length + idx + 1 __lowercase= (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(lowerCAmelCase ) , ) pass @slow def _A (self ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase= XLMModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) @require_torch class A ( unittest.TestCase ): @slow def _A (self ): __lowercase= XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(lowerCAmelCase ) __lowercase= torch.tensor([[1_4, 4_4_7]] , dtype=torch.long , device=lowerCAmelCase ) # the president __lowercase= [ 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, ] # 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 __lowercase= model.generate(lowerCAmelCase , do_sample=lowerCAmelCase ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , lowerCAmelCase )
304
0
'''simple docstring''' import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class A_ ( lowerCAmelCase_ , unittest.TestCase ): _lowerCamelCase : str = MobileBertTokenizer _lowerCamelCase : Any = MobileBertTokenizerFast _lowerCamelCase : Any = True _lowerCamelCase : Optional[Any] = True _lowerCamelCase : List[str] = filter_non_english _lowerCamelCase : List[Any] = """google/mobilebert-uncased""" def lowercase ( self : List[str] ): super().setUp() _UpperCAmelCase = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] _UpperCAmelCase = 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] ) ) _UpperCAmelCase = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def lowercase ( self : Union[str, Any] , snake_case_ : Any ): _UpperCAmelCase = "UNwant\u00E9d,running" _UpperCAmelCase = "unwanted, running" return input_text, output_text def lowercase ( self : Union[str, Any] ): _UpperCAmelCase = self.tokenizer_class(self.vocab_file ) _UpperCAmelCase = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(snake_case_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case_ ) , [9, 6, 7, 1_2, 1_0, 1_1] ) def lowercase ( self : str ): if not self.test_rust_tokenizer: return _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = "UNwant\u00E9d,running" _UpperCAmelCase = tokenizer.tokenize(snake_case_ ) _UpperCAmelCase = rust_tokenizer.tokenize(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = rust_tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = tokenizer.encode(snake_case_ ) _UpperCAmelCase = rust_tokenizer.encode(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) # With lower casing _UpperCAmelCase = self.get_tokenizer(do_lower_case=snake_case_ ) _UpperCAmelCase = self.get_rust_tokenizer(do_lower_case=snake_case_ ) _UpperCAmelCase = "UNwant\u00E9d,running" _UpperCAmelCase = tokenizer.tokenize(snake_case_ ) _UpperCAmelCase = rust_tokenizer.tokenize(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) _UpperCAmelCase = tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = rust_tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) _UpperCAmelCase = self.get_rust_tokenizer() _UpperCAmelCase = tokenizer.encode(snake_case_ ) _UpperCAmelCase = rust_tokenizer.encode(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) def lowercase ( self : Any ): _UpperCAmelCase = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def lowercase ( self : Optional[int] ): _UpperCAmelCase = BasicTokenizer(do_lower_case=snake_case_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def lowercase ( self : List[str] ): _UpperCAmelCase = BasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def lowercase ( self : Optional[int] ): _UpperCAmelCase = BasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def lowercase ( self : str ): _UpperCAmelCase = BasicTokenizer(do_lower_case=snake_case_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def lowercase ( self : Dict ): _UpperCAmelCase = BasicTokenizer(do_lower_case=snake_case_ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def lowercase ( self : List[Any] ): _UpperCAmelCase = BasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def lowercase ( self : Optional[int] ): _UpperCAmelCase = BasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def lowercase ( self : Optional[Any] ): _UpperCAmelCase = BasicTokenizer(do_lower_case=snake_case_ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def lowercase ( self : List[str] ): _UpperCAmelCase = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] _UpperCAmelCase = {} for i, token in enumerate(snake_case_ ): _UpperCAmelCase = i _UpperCAmelCase = WordpieceTokenizer(vocab=snake_case_ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def lowercase ( self : List[Any] ): self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def lowercase ( self : Optional[int] ): self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def lowercase ( self : str ): self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def lowercase ( self : Any ): _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(snake_case_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) self.assertListEqual( [rust_tokenizer.tokenize(snake_case_ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) @slow def lowercase ( self : List[str] ): _UpperCAmelCase = self.tokenizer_class.from_pretrained("google/mobilebert-uncased" ) _UpperCAmelCase = tokenizer.encode("sequence builders" , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer.encode("multi-sequence build" , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(snake_case_ ) _UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(snake_case_ , snake_case_ ) assert encoded_sentence == [1_0_1] + text + [1_0_2] assert encoded_pair == [1_0_1] + text + [1_0_2] + text_a + [1_0_2] def lowercase ( self : Optional[Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(snake_case_ , **snake_case_ ) _UpperCAmelCase = f'A, naïve {tokenizer_r.mask_token} AllenNLP sentence.' _UpperCAmelCase = tokenizer_r.encode_plus( snake_case_ , return_attention_mask=snake_case_ , return_token_type_ids=snake_case_ , return_offsets_mapping=snake_case_ , add_special_tokens=snake_case_ , ) _UpperCAmelCase = tokenizer_r.do_lower_case if hasattr(snake_case_ , "do_lower_case" ) else False _UpperCAmelCase = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def lowercase ( self : List[str] ): _UpperCAmelCase = ["的", "人", "有"] _UpperCAmelCase = "".join(snake_case_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): _UpperCAmelCase = True _UpperCAmelCase = self.tokenizer_class.from_pretrained(snake_case_ , **snake_case_ ) _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(snake_case_ , **snake_case_ ) _UpperCAmelCase = tokenizer_p.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer_r.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer_r.convert_ids_to_tokens(snake_case_ ) _UpperCAmelCase = tokenizer_p.convert_ids_to_tokens(snake_case_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(snake_case_ , snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) _UpperCAmelCase = False _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(snake_case_ , **snake_case_ ) _UpperCAmelCase = self.tokenizer_class.from_pretrained(snake_case_ , **snake_case_ ) _UpperCAmelCase = tokenizer_r.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer_p.encode(snake_case_ , add_special_tokens=snake_case_ ) _UpperCAmelCase = tokenizer_r.convert_ids_to_tokens(snake_case_ ) _UpperCAmelCase = tokenizer_p.convert_ids_to_tokens(snake_case_ ) # it is expected that only the first Chinese character is not preceded by "##". _UpperCAmelCase = [ f'##{token}' if idx != 0 else token for idx, token in enumerate(snake_case_ ) ] self.assertListEqual(snake_case_ , snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ )
22
'''simple docstring''' import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef __SCREAMING_SNAKE_CASE :List[str] = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase_ ( __lowercase : Any , __lowercase : Tuple ) -> int: '''simple docstring''' warnings.warn(__lowercase , __lowercase ) requires_backends(__lowercase , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase_ ( __lowercase : int , __lowercase : str ) -> Optional[Any]: '''simple docstring''' warnings.warn(__lowercase , __lowercase ) requires_backends(__lowercase , "sklearn" ) _UpperCAmelCase = simple_accuracy(__lowercase , __lowercase ) _UpperCAmelCase = fa_score(y_true=__lowercase , y_pred=__lowercase ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase_ ( __lowercase : Optional[int] , __lowercase : List[str] ) -> List[Any]: '''simple docstring''' warnings.warn(__lowercase , __lowercase ) requires_backends(__lowercase , "sklearn" ) _UpperCAmelCase = pearsonr(__lowercase , __lowercase )[0] _UpperCAmelCase = spearmanr(__lowercase , __lowercase )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase_ ( __lowercase : Optional[Any] , __lowercase : str , __lowercase : str ) -> Tuple: '''simple docstring''' warnings.warn(__lowercase , __lowercase ) requires_backends(__lowercase , "sklearn" ) assert len(__lowercase ) == len(__lowercase ), f'Predictions and labels have mismatched lengths {len(__lowercase )} and {len(__lowercase )}' if task_name == "cola": return {"mcc": matthews_corrcoef(__lowercase , __lowercase )} elif task_name == "sst-2": return {"acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "mrpc": return acc_and_fa(__lowercase , __lowercase ) elif task_name == "sts-b": return pearson_and_spearman(__lowercase , __lowercase ) elif task_name == "qqp": return acc_and_fa(__lowercase , __lowercase ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "qnli": return {"acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "rte": return {"acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "wnli": return {"acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "hans": return {"acc": simple_accuracy(__lowercase , __lowercase )} else: raise KeyError(__lowercase ) def UpperCAmelCase_ ( __lowercase : List[Any] , __lowercase : Dict , __lowercase : str ) -> Union[str, Any]: '''simple docstring''' warnings.warn(__lowercase , __lowercase ) requires_backends(__lowercase , "sklearn" ) if len(__lowercase ) != len(__lowercase ): raise ValueError(f'Predictions and labels have mismatched lengths {len(__lowercase )} and {len(__lowercase )}' ) if task_name == "xnli": return {"acc": simple_accuracy(__lowercase , __lowercase )} else: raise KeyError(__lowercase )
22
1
import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : int = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all LED models at https://huggingface.co/models?filter=LED UpperCAmelCase : List[Any] = { "vocab_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", }, "merges_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt", }, "tokenizer_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json", }, } UpperCAmelCase : Dict = { "allenai/led-base-16384": 1_63_84, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def __lowerCamelCase ( ): '''simple docstring''' lowerCamelCase = ( list(range(ord("""!""" ) , ord("""~""" ) + 1 ) ) + list(range(ord("""¡""" ) , ord("""¬""" ) + 1 ) ) + list(range(ord("""®""" ) , ord("""ÿ""" ) + 1 ) ) ) lowerCamelCase = bs[:] lowerCamelCase = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCamelCase__ ) cs.append(2**8 + n ) n += 1 lowerCamelCase = [chr(lowerCamelCase__ ) for n in cs] return dict(zip(lowerCamelCase__ , lowerCamelCase__ ) ) def __lowerCamelCase ( lowerCamelCase__ : List[str] ): '''simple docstring''' lowerCamelCase = set() lowerCamelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCamelCase = char return pairs class __lowercase ( a_ ): """simple docstring""" UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase : Union[str, Any] = ["input_ids", "attention_mask"] def __init__( self , A , A , A="replace" , A="<s>" , A="</s>" , A="</s>" , A="<s>" , A="<unk>" , A="<pad>" , A="<mask>" , A=False , **A , ) -> Tuple: '''simple docstring''' lowerCamelCase = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else bos_token lowerCamelCase = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else eos_token lowerCamelCase = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else sep_token lowerCamelCase = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else cls_token lowerCamelCase = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else unk_token lowerCamelCase = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowerCamelCase = AddedToken(A , lstrip=A , rstrip=A ) if isinstance(A , A ) else mask_token super().__init__( errors=A , bos_token=A , eos_token=A , unk_token=A , sep_token=A , cls_token=A , pad_token=A , mask_token=A , add_prefix_space=A , **A , ) with open(A , encoding="""utf-8""" ) as vocab_handle: lowerCamelCase = json.load(A ) lowerCamelCase = {v: k for k, v in self.encoder.items()} lowerCamelCase = errors # how to handle errors in decoding lowerCamelCase = bytes_to_unicode() lowerCamelCase = {v: k for k, v in self.byte_encoder.items()} with open(A , encoding="""utf-8""" ) as merges_handle: lowerCamelCase = merges_handle.read().split("""\n""" )[1:-1] lowerCamelCase = [tuple(merge.split() ) for merge in bpe_merges] lowerCamelCase = dict(zip(A , range(len(A ) ) ) ) lowerCamelCase = {} lowerCamelCase = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowerCamelCase = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def __A ( self ) -> Tuple: '''simple docstring''' return len(self.encoder ) def __A ( self ) -> Optional[int]: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def __A ( self , A ) -> List[str]: '''simple docstring''' if token in self.cache: return self.cache[token] lowerCamelCase = tuple(A ) lowerCamelCase = get_pairs(A ) if not pairs: return token while True: lowerCamelCase = min(A , key=lambda A : self.bpe_ranks.get(A , float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break lowerCamelCase , lowerCamelCase = bigram lowerCamelCase = [] lowerCamelCase = 0 while i < len(A ): try: lowerCamelCase = word.index(A , A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCamelCase = j if word[i] == first and i < len(A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCamelCase = tuple(A ) lowerCamelCase = new_word if len(A ) == 1: break else: lowerCamelCase = get_pairs(A ) lowerCamelCase = """ """.join(A ) lowerCamelCase = word return word def __A ( self , A ) -> List[str]: '''simple docstring''' lowerCamelCase = [] for token in re.findall(self.pat , A ): lowerCamelCase = """""".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(A ).split(""" """ ) ) return bpe_tokens def __A ( self , A ) -> Optional[Any]: '''simple docstring''' return self.encoder.get(A , self.encoder.get(self.unk_token ) ) def __A ( self , A ) -> Optional[int]: '''simple docstring''' return self.decoder.get(A ) def __A ( self , A ) -> Tuple: '''simple docstring''' lowerCamelCase = """""".join(A ) lowerCamelCase = bytearray([self.byte_decoder[c] for c in text] ).decode("""utf-8""" , errors=self.errors ) return text def __A ( self , A , A = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(A ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return lowerCamelCase = os.path.join( A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) lowerCamelCase = os.path.join( A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(A , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=A , ensure_ascii=A ) + """\n""" ) lowerCamelCase = 0 with open(A , """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 A : 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!""" ) lowerCamelCase = token_index writer.write(""" """.join(A ) + """\n""" ) index += 1 return vocab_file, merge_file def __A ( self , A , A = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCamelCase = [self.cls_token_id] lowerCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __A ( self , A , A = None , A = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A , token_ids_a=A , already_has_special_tokens=A ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def __A ( self , A , A = None ) -> List[int]: '''simple docstring''' lowerCamelCase = [self.sep_token_id] lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __A ( self , A , A=False , **A ) -> List[str]: '''simple docstring''' lowerCamelCase = kwargs.pop("""add_prefix_space""" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(A ) > 0 and not text[0].isspace()): lowerCamelCase = """ """ + text return (text, kwargs) def __A ( self , A , A = None , A = PaddingStrategy.DO_NOT_PAD , A = None , A = None , ) -> dict: '''simple docstring''' lowerCamelCase = super()._pad( encoded_inputs=A , max_length=A , padding_strategy=A , pad_to_multiple_of=A , return_attention_mask=A , ) # Load from model defaults if return_attention_mask is None: lowerCamelCase = """attention_mask""" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: lowerCamelCase = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. lowerCamelCase = len(encoded_inputs["""global_attention_mask"""] ) != len(A ) if needs_to_be_padded: lowerCamelCase = len(A ) - len(encoded_inputs["""global_attention_mask"""] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` lowerCamelCase = ( encoded_inputs["""global_attention_mask"""] + [-1] * difference ) elif self.padding_side == "left": lowerCamelCase = [-1] * difference + encoded_inputs[ """global_attention_mask""" ] else: raise ValueError("""Invalid padding strategy:""" + str(self.padding_side ) ) return encoded_inputs
360
import argparse import logging import os import re import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, DataCollatorForLanguageModeling, PushToHubCallback, TFAutoModelForMaskedLM, create_optimizer, ) UpperCAmelCase : Optional[int] = logging.getLogger(__name__) UpperCAmelCase : Dict = tf.data.AUTOTUNE def __lowerCamelCase ( ): '''simple docstring''' lowerCamelCase = argparse.ArgumentParser(description="""Train a masked language model on TPU.""" ) parser.add_argument( """--pretrained_model_config""" , type=lowerCamelCase__ , default="""roberta-base""" , help="""The model config to use. Note that we don't copy the model's weights, only the config!""" , ) parser.add_argument( """--tokenizer""" , type=lowerCamelCase__ , default="""unigram-tokenizer-wikitext""" , help="""The name of the tokenizer to load. We use the pretrained tokenizer to initialize the model's vocab size.""" , ) parser.add_argument( """--per_replica_batch_size""" , type=lowerCamelCase__ , default=8 , help="""Batch size per TPU core.""" , ) parser.add_argument( """--no_tpu""" , action="""store_true""" , help="""If set, run on CPU and don't try to initialize a TPU. Useful for debugging on non-TPU instances.""" , ) parser.add_argument( """--tpu_name""" , type=lowerCamelCase__ , help="""Name of TPU resource to initialize. Should be blank on Colab, and 'local' on TPU VMs.""" , default="""local""" , ) parser.add_argument( """--tpu_zone""" , type=lowerCamelCase__ , help="""Google cloud zone that TPU resource is located in. Only used for non-Colab TPU nodes.""" , ) parser.add_argument( """--gcp_project""" , type=lowerCamelCase__ , help="""Google cloud project name. Only used for non-Colab TPU nodes.""" ) parser.add_argument( """--bfloat16""" , action="""store_true""" , help="""Use mixed-precision bfloat16 for training. This is the recommended lower-precision format for TPU.""" , ) parser.add_argument( """--train_dataset""" , type=lowerCamelCase__ , help="""Path to training dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--shuffle_buffer_size""" , type=lowerCamelCase__ , default=2**18 , help="""Size of the shuffle buffer (in samples)""" , ) parser.add_argument( """--eval_dataset""" , type=lowerCamelCase__ , help="""Path to evaluation dataset to load. If the path begins with `gs://`""" """ then the dataset will be loaded from a Google Cloud Storage bucket.""" , ) parser.add_argument( """--num_epochs""" , type=lowerCamelCase__ , default=1 , help="""Number of epochs to train for.""" , ) parser.add_argument( """--learning_rate""" , type=lowerCamelCase__ , default=1E-4 , help="""Learning rate to use for training.""" , ) parser.add_argument( """--weight_decay_rate""" , type=lowerCamelCase__ , default=1E-3 , help="""Weight decay rate to use for training.""" , ) parser.add_argument( """--max_length""" , type=lowerCamelCase__ , default=512 , help="""Maximum length of tokenized sequences. Should match the setting used in prepare_tfrecord_shards.py""" , ) parser.add_argument( """--mlm_probability""" , type=lowerCamelCase__ , default=0.1_5 , help="""Fraction of tokens to mask during training.""" , ) parser.add_argument("""--output_dir""" , type=lowerCamelCase__ , required=lowerCamelCase__ , help="""Path to save model checkpoints to.""" ) parser.add_argument("""--hub_model_id""" , type=lowerCamelCase__ , help="""Model ID to upload to on the Hugging Face Hub.""" ) lowerCamelCase = parser.parse_args() return args def __lowerCamelCase ( lowerCamelCase__ : List[str] ): '''simple docstring''' try: if args.tpu_name: lowerCamelCase = tf.distribute.cluster_resolver.TPUClusterResolver( args.tpu_name , zone=args.tpu_zone , project=args.gcp_project ) else: lowerCamelCase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: raise RuntimeError( """Couldn't connect to TPU! Most likely you need to specify --tpu_name, --tpu_zone, or """ """--gcp_project. When running on a TPU VM, use --tpu_name local.""" ) tf.config.experimental_connect_to_cluster(lowerCamelCase__ ) tf.tpu.experimental.initialize_tpu_system(lowerCamelCase__ ) return tpu def __lowerCamelCase ( lowerCamelCase__ : List[str] ): '''simple docstring''' lowerCamelCase = 0 for file in file_list: lowerCamelCase = file.split("""/""" )[-1] lowerCamelCase = re.search(R"""-\d+-(\d+)\.tfrecord""" , lowerCamelCase__ ).group(1 ) lowerCamelCase = int(lowerCamelCase__ ) num_samples += sample_count return num_samples def __lowerCamelCase ( lowerCamelCase__ : List[str] , lowerCamelCase__ : Any , lowerCamelCase__ : Dict , lowerCamelCase__ : Tuple , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : int=None ): '''simple docstring''' lowerCamelCase = count_samples(lowerCamelCase__ ) lowerCamelCase = tf.data.Dataset.from_tensor_slices(lowerCamelCase__ ) if shuffle: lowerCamelCase = dataset.shuffle(len(lowerCamelCase__ ) ) lowerCamelCase = tf.data.TFRecordDataset(lowerCamelCase__ , num_parallel_reads=lowerCamelCase__ ) # TF can't infer the total sample count because it doesn't read all the records yet, so we assert it here lowerCamelCase = dataset.apply(tf.data.experimental.assert_cardinality(lowerCamelCase__ ) ) lowerCamelCase = dataset.map(lowerCamelCase__ , num_parallel_calls=lowerCamelCase__ ) if shuffle: assert shuffle_buffer_size is not None lowerCamelCase = dataset.shuffle(args.shuffle_buffer_size ) lowerCamelCase = dataset.batch(lowerCamelCase__ , drop_remainder=lowerCamelCase__ ) lowerCamelCase = dataset.map(lowerCamelCase__ , num_parallel_calls=lowerCamelCase__ ) lowerCamelCase = dataset.prefetch(lowerCamelCase__ ) return dataset def __lowerCamelCase ( lowerCamelCase__ : Any ): '''simple docstring''' if not args.no_tpu: lowerCamelCase = initialize_tpu(lowerCamelCase__ ) lowerCamelCase = tf.distribute.TPUStrategy(lowerCamelCase__ ) else: lowerCamelCase = tf.distribute.OneDeviceStrategy(device="""/gpu:0""" ) if args.bfloataa: tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16""" ) lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer ) lowerCamelCase = AutoConfig.from_pretrained(args.pretrained_model_config ) lowerCamelCase = tokenizer.vocab_size lowerCamelCase = tf.io.gfile.glob(os.path.join(args.train_dataset , """*.tfrecord""" ) ) if not training_records: raise ValueError(f'No .tfrecord files found in {args.train_dataset}.' ) lowerCamelCase = tf.io.gfile.glob(os.path.join(args.eval_dataset , """*.tfrecord""" ) ) if not eval_records: raise ValueError(f'No .tfrecord files found in {args.eval_dataset}.' ) lowerCamelCase = count_samples(lowerCamelCase__ ) lowerCamelCase = num_train_samples // (args.per_replica_batch_size * strategy.num_replicas_in_sync) lowerCamelCase = steps_per_epoch * args.num_epochs with strategy.scope(): lowerCamelCase = TFAutoModelForMaskedLM.from_config(lowerCamelCase__ ) model(model.dummy_inputs ) # Pass some dummy inputs through the model to ensure all the weights are built lowerCamelCase , lowerCamelCase = create_optimizer( num_train_steps=lowerCamelCase__ , num_warmup_steps=total_train_steps // 20 , init_lr=args.learning_rate , weight_decay_rate=args.weight_decay_rate , ) # Transformers models compute the right loss for their task by default when labels are passed, and will # use this for training unless you specify your own loss function in compile(). model.compile(optimizer=lowerCamelCase__ , metrics=["""accuracy"""] ) def decode_fn(lowerCamelCase__ : Optional[Any] ): lowerCamelCase = { """input_ids""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), """attention_mask""": tf.io.FixedLenFeature(dtype=tf.intaa , shape=(args.max_length,) ), } return tf.io.parse_single_example(lowerCamelCase__ , lowerCamelCase__ ) # Many of the data collators in Transformers are TF-compilable when return_tensors == "tf", so we can # use their methods in our data pipeline. lowerCamelCase = DataCollatorForLanguageModeling( tokenizer=lowerCamelCase__ , mlm_probability=args.mlm_probability , mlm=lowerCamelCase__ , return_tensors="""tf""" ) def mask_with_collator(lowerCamelCase__ : List[Any] ): # TF really needs an isin() function lowerCamelCase = ( ~tf.cast(batch["""attention_mask"""] , tf.bool ) | (batch["""input_ids"""] == tokenizer.cls_token_id) | (batch["""input_ids"""] == tokenizer.sep_token_id) ) lowerCamelCase , lowerCamelCase = data_collator.tf_mask_tokens( batch["""input_ids"""] , vocab_size=len(lowerCamelCase__ ) , mask_token_id=tokenizer.mask_token_id , special_tokens_mask=lowerCamelCase__ , ) return batch lowerCamelCase = args.per_replica_batch_size * strategy.num_replicas_in_sync lowerCamelCase = prepare_dataset( lowerCamelCase__ , decode_fn=lowerCamelCase__ , mask_fn=lowerCamelCase__ , batch_size=lowerCamelCase__ , shuffle=lowerCamelCase__ , shuffle_buffer_size=args.shuffle_buffer_size , ) lowerCamelCase = prepare_dataset( lowerCamelCase__ , decode_fn=lowerCamelCase__ , mask_fn=lowerCamelCase__ , batch_size=lowerCamelCase__ , shuffle=lowerCamelCase__ , ) lowerCamelCase = [] if args.hub_model_id: callbacks.append( PushToHubCallback(output_dir=args.output_dir , hub_model_id=args.hub_model_id , tokenizer=lowerCamelCase__ ) ) model.fit( lowerCamelCase__ , validation_data=lowerCamelCase__ , epochs=args.num_epochs , callbacks=lowerCamelCase__ , ) model.save_pretrained(args.output_dir ) if __name__ == "__main__": UpperCAmelCase : Tuple = parse_args() main(args)
66
0
import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor lowerCAmelCase__ = random.Random() def _UpperCAmelCase (UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int]=1.0 , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Optional[Any]=None ): if rng is None: _A : Dict = global_rng _A : Tuple = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class lowerCAmelCase__ ( unittest.TestCase): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase=7 , __lowerCamelCase=4_0_0 , __lowerCamelCase=2_0_0_0 , __lowerCamelCase=2_4 , __lowerCamelCase=2_4 , __lowerCamelCase=0.0 , __lowerCamelCase=1_6_0_0_0 , __lowerCamelCase=True , __lowerCamelCase=True , ) -> Tuple: _A : Tuple = parent _A : Any = batch_size _A : List[Any] = min_seq_length _A : List[Any] = max_seq_length _A : int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _A : Optional[Any] = feature_size _A : List[Any] = num_mel_bins _A : Optional[int] = padding_value _A : List[Any] = sampling_rate _A : List[Any] = return_attention_mask _A : List[str] = do_normalize def _lowerCamelCase ( self) -> List[Any]: return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _lowerCamelCase ( self , __lowerCamelCase=False , __lowerCamelCase=False) -> Union[str, Any]: def _flatten(__lowerCamelCase): return list(itertools.chain(*__lowerCamelCase)) if equal_length: _A : List[Any] = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)] else: # make sure that inputs increase in size _A : List[Any] = [ floats_list((x, self.feature_size)) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff) ] if numpify: _A : str = [np.asarray(__lowerCamelCase) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class lowerCAmelCase__ ( a , unittest.TestCase): '''simple docstring''' __SCREAMING_SNAKE_CASE = SpeechaTextFeatureExtractor if is_speech_available() else None def _lowerCamelCase ( self) -> Any: _A : Dict = SpeechaTextFeatureExtractionTester(self) def _lowerCamelCase ( self , __lowerCamelCase) -> Any: self.assertTrue(np.all(np.mean(__lowerCamelCase , axis=0) < 1e-3)) self.assertTrue(np.all(np.abs(np.var(__lowerCamelCase , axis=0) - 1) < 1e-3)) def _lowerCamelCase ( self) -> Dict: # Tests that all call wrap to encode_plus and batch_encode_plus _A : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) # create three inputs of length 800, 1000, and 1200 _A : List[str] = [floats_list((1, x))[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0)] _A : Any = [np.asarray(__lowerCamelCase) for speech_input in speech_inputs] # Test feature size _A : List[Any] = feature_extractor(__lowerCamelCase , padding=__lowerCamelCase , return_tensors="np").input_features self.assertTrue(input_features.ndim == 3) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size) # Test not batched input _A : Optional[int] = feature_extractor(speech_inputs[0] , return_tensors="np").input_features _A : List[Any] = feature_extractor(np_speech_inputs[0] , return_tensors="np").input_features self.assertTrue(np.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-3)) # Test batched _A : Optional[int] = feature_extractor(__lowerCamelCase , return_tensors="np").input_features _A : Optional[int] = feature_extractor(__lowerCamelCase , return_tensors="np").input_features 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 : int = [floats_list((1, x))[0] for x in (8_0_0, 8_0_0, 8_0_0)] _A : Optional[Any] = np.asarray(__lowerCamelCase) _A : Dict = feature_extractor(__lowerCamelCase , return_tensors="np").input_features _A : Union[str, Any] = feature_extractor(__lowerCamelCase , return_tensors="np").input_features for enc_seq_a, enc_seq_a in zip(__lowerCamelCase , __lowerCamelCase): self.assertTrue(np.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-3)) def _lowerCamelCase ( self) -> Dict: _A : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) _A : int = [floats_list((1, x))[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0)] _A : int = ["longest", "max_length", "do_not_pad"] _A : int = [None, 1_6, None] for max_length, padding in zip(__lowerCamelCase , __lowerCamelCase): _A : Optional[Any] = feature_extractor( __lowerCamelCase , padding=__lowerCamelCase , max_length=__lowerCamelCase , return_attention_mask=__lowerCamelCase) _A : Union[str, Any] = inputs.input_features _A : int = inputs.attention_mask _A : List[str] = [np.sum(__lowerCamelCase) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]) def _lowerCamelCase ( self) -> Optional[int]: _A : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) _A : int = [floats_list((1, x))[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0)] _A : Any = ["longest", "max_length", "do_not_pad"] _A : str = [None, 1_6, None] for max_length, padding in zip(__lowerCamelCase , __lowerCamelCase): _A : Any = feature_extractor( __lowerCamelCase , max_length=__lowerCamelCase , padding=__lowerCamelCase , return_tensors="np" , return_attention_mask=__lowerCamelCase) _A : Dict = inputs.input_features _A : str = inputs.attention_mask _A : int = [np.sum(__lowerCamelCase) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]) def _lowerCamelCase ( self) -> Dict: _A : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) _A : Optional[int] = [floats_list((1, x))[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0)] _A : Tuple = feature_extractor( __lowerCamelCase , padding="max_length" , max_length=4 , truncation=__lowerCamelCase , return_tensors="np" , return_attention_mask=__lowerCamelCase , ) _A : Tuple = inputs.input_features _A : Optional[int] = inputs.attention_mask _A : Optional[Any] = np.sum(attention_mask == 1 , axis=1) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]) self._check_zero_mean_unit_variance(input_features[1]) self._check_zero_mean_unit_variance(input_features[2]) def _lowerCamelCase ( self) -> Dict: _A : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) _A : Union[str, Any] = [floats_list((1, x))[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0)] _A : Optional[int] = feature_extractor( __lowerCamelCase , padding="longest" , max_length=4 , truncation=__lowerCamelCase , return_tensors="np" , return_attention_mask=__lowerCamelCase , ) _A : List[Any] = inputs.input_features _A : int = inputs.attention_mask _A : Tuple = np.sum(attention_mask == 1 , axis=1) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]) self._check_zero_mean_unit_variance(input_features[2]) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 4, 2_4)) _A : List[str] = [floats_list((1, x))[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0)] _A : List[Any] = feature_extractor( __lowerCamelCase , padding="longest" , max_length=1_6 , truncation=__lowerCamelCase , return_tensors="np" , return_attention_mask=__lowerCamelCase , ) _A : Optional[int] = inputs.input_features _A : Tuple = inputs.attention_mask _A : List[str] = np.sum(attention_mask == 1 , axis=1) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]) self._check_zero_mean_unit_variance(input_features[2]) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 6, 2_4)) def _lowerCamelCase ( self) -> str: import torch _A : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) _A : str = np.random.rand(1_0_0 , 3_2).astype(np.floataa) _A : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _A : Dict = feature_extractor.pad([{"input_features": inputs}] , return_tensors="np") self.assertTrue(np_processed.input_features.dtype == np.floataa) _A : Dict = feature_extractor.pad([{"input_features": inputs}] , return_tensors="pt") self.assertTrue(pt_processed.input_features.dtype == torch.floataa) def _lowerCamelCase ( self , __lowerCamelCase) -> str: from datasets import load_dataset _A : Union[str, Any] = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation") # automatic decoding with librispeech _A : Dict = ds.sort("id").select(range(__lowerCamelCase))[:num_samples]["audio"] return [x["array"] for x in speech_samples] def _lowerCamelCase ( self) -> Any: # fmt: off _A : Dict = np.array([ -1.5_7_4_5, -1.7_7_1_3, -1.7_0_2_0, -1.6_0_6_9, -1.2_2_5_0, -1.1_1_0_5, -0.9_0_7_2, -0.8_2_4_1, -1.2_3_1_0, -0.8_0_9_8, -0.3_3_2_0, -0.4_1_0_1, -0.7_9_8_5, -0.4_9_9_6, -0.8_2_1_3, -0.9_1_2_8, -1.0_4_2_0, -1.1_2_8_6, -1.0_4_4_0, -0.7_9_9_9, -0.8_4_0_5, -1.2_2_7_5, -1.5_4_4_3, -1.4_6_2_5, ]) # fmt: on _A : Union[str, Any] = self._load_datasamples(1) _A : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) _A : Tuple = feature_extractor(__lowerCamelCase , return_tensors="pt").input_features self.assertEquals(input_features.shape , (1, 5_8_4, 2_4)) self.assertTrue(np.allclose(input_features[0, 0, :3_0] , __lowerCamelCase , atol=1e-4))
11
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def _UpperCamelCase ( ): __SCREAMING_SNAKE_CASE : Dict = '''https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png''' __SCREAMING_SNAKE_CASE : List[str] = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ).convert('''RGB''' ) return image def _UpperCamelCase ( lowercase__ ): __SCREAMING_SNAKE_CASE : List[Any] = [] # fmt: off # vision encoder rename_keys.append(('''visual_encoder.cls_token''', '''vision_model.embeddings.class_embedding''') ) rename_keys.append(('''visual_encoder.pos_embed''', '''vision_model.embeddings.position_embedding''') ) rename_keys.append(('''visual_encoder.patch_embed.proj.weight''', '''vision_model.embeddings.patch_embedding.weight''') ) rename_keys.append(('''visual_encoder.patch_embed.proj.bias''', '''vision_model.embeddings.patch_embedding.bias''') ) rename_keys.append(('''ln_vision.weight''', '''vision_model.post_layernorm.weight''') ) rename_keys.append(('''ln_vision.bias''', '''vision_model.post_layernorm.bias''') ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.weight''', '''qformer.layernorm.weight''') ) rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.bias''', '''qformer.layernorm.bias''') ) # fmt: on return rename_keys def _UpperCamelCase ( lowercase__ , lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : List[Any] = dct.pop(lowercase__ ) __SCREAMING_SNAKE_CASE : List[Any] = val def _UpperCamelCase ( lowercase__ , lowercase__ ): for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases __SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) __SCREAMING_SNAKE_CASE : int = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict __SCREAMING_SNAKE_CASE : Optional[int] = torch.cat((q_bias, torch.zeros_like(lowercase__ , requires_grad=lowercase__ ), v_bias) ) __SCREAMING_SNAKE_CASE : Optional[Any] = qkv_bias def _UpperCamelCase ( lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Any = 364 if '''coco''' in model_name else 224 __SCREAMING_SNAKE_CASE : List[str] = BlipaVisionConfig(image_size=lowercase__ ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: __SCREAMING_SNAKE_CASE : Union[str, Any] = OPTConfig.from_pretrained('''facebook/opt-2.7b''' , eos_token_id=lowercase__ ).to_dict() elif "opt-6.7b" in model_name: __SCREAMING_SNAKE_CASE : List[Any] = OPTConfig.from_pretrained('''facebook/opt-6.7b''' , eos_token_id=lowercase__ ).to_dict() elif "t5-xl" in model_name: __SCREAMING_SNAKE_CASE : Optional[Any] = TaConfig.from_pretrained('''google/flan-t5-xl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: __SCREAMING_SNAKE_CASE : Union[str, Any] = TaConfig.from_pretrained('''google/flan-t5-xxl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict() __SCREAMING_SNAKE_CASE : Optional[int] = BlipaConfig(vision_config=lowercase__ , text_config=lowercase__ ) return config, image_size @torch.no_grad() def _UpperCamelCase ( lowercase__ , lowercase__=None , lowercase__=False ): __SCREAMING_SNAKE_CASE : Any = ( AutoTokenizer.from_pretrained('''facebook/opt-2.7b''' ) if '''opt''' in model_name else AutoTokenizer.from_pretrained('''google/flan-t5-xl''' ) ) __SCREAMING_SNAKE_CASE : str = tokenizer('''\n''' , add_special_tokens=lowercase__ ).input_ids[0] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = get_blipa_config(lowercase__ , eos_token_id=lowercase__ ) __SCREAMING_SNAKE_CASE : int = BlipaForConditionalGeneration(lowercase__ ).eval() __SCREAMING_SNAKE_CASE : int = { '''blip2-opt-2.7b''': ('''blip2_opt''', '''pretrain_opt2.7b'''), '''blip2-opt-6.7b''': ('''blip2_opt''', '''pretrain_opt6.7b'''), '''blip2-opt-2.7b-coco''': ('''blip2_opt''', '''caption_coco_opt2.7b'''), '''blip2-opt-6.7b-coco''': ('''blip2_opt''', '''caption_coco_opt6.7b'''), '''blip2-flan-t5-xl''': ('''blip2_t5''', '''pretrain_flant5xl'''), '''blip2-flan-t5-xl-coco''': ('''blip2_t5''', '''caption_coco_flant5xl'''), '''blip2-flan-t5-xxl''': ('''blip2_t5''', '''pretrain_flant5xxl'''), } __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = model_name_to_original[model_name] # load original model print('''Loading original model...''' ) __SCREAMING_SNAKE_CASE : List[str] = '''cuda''' if torch.cuda.is_available() else '''cpu''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = load_model_and_preprocess( name=lowercase__ , model_type=lowercase__ , is_eval=lowercase__ , device=lowercase__ ) original_model.eval() print('''Done!''' ) # update state dict keys __SCREAMING_SNAKE_CASE : List[str] = original_model.state_dict() __SCREAMING_SNAKE_CASE : Optional[int] = create_rename_keys(lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): __SCREAMING_SNAKE_CASE : Tuple = state_dict.pop(lowercase__ ) if key.startswith('''Qformer.bert''' ): __SCREAMING_SNAKE_CASE : List[str] = key.replace('''Qformer.bert''' , '''qformer''' ) if "attention.self" in key: __SCREAMING_SNAKE_CASE : Union[str, Any] = key.replace('''self''' , '''attention''' ) if "opt_proj" in key: __SCREAMING_SNAKE_CASE : Dict = key.replace('''opt_proj''' , '''language_projection''' ) if "t5_proj" in key: __SCREAMING_SNAKE_CASE : Tuple = key.replace('''t5_proj''' , '''language_projection''' ) if key.startswith('''opt''' ): __SCREAMING_SNAKE_CASE : List[str] = key.replace('''opt''' , '''language''' ) if key.startswith('''t5''' ): __SCREAMING_SNAKE_CASE : Tuple = key.replace('''t5''' , '''language''' ) __SCREAMING_SNAKE_CASE : Tuple = val # read in qv biases read_in_q_v_bias(lowercase__ , lowercase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = hf_model.load_state_dict(lowercase__ , strict=lowercase__ ) assert len(lowercase__ ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] __SCREAMING_SNAKE_CASE : List[str] = load_demo_image() __SCREAMING_SNAKE_CASE : Any = vis_processors['''eval'''](lowercase__ ).unsqueeze(0 ).to(lowercase__ ) __SCREAMING_SNAKE_CASE : str = tokenizer(['''\n'''] , return_tensors='''pt''' ).input_ids.to(lowercase__ ) # create processor __SCREAMING_SNAKE_CASE : List[Any] = BlipImageProcessor( size={'''height''': image_size, '''width''': image_size} , image_mean=lowercase__ , image_std=lowercase__ ) __SCREAMING_SNAKE_CASE : int = BlipaProcessor(image_processor=lowercase__ , tokenizer=lowercase__ ) __SCREAMING_SNAKE_CASE : Any = processor(images=lowercase__ , return_tensors='''pt''' ).pixel_values.to(lowercase__ ) # make sure processor creates exact same pixel values assert torch.allclose(lowercase__ , lowercase__ ) original_model.to(lowercase__ ) hf_model.to(lowercase__ ) with torch.no_grad(): if "opt" in model_name: __SCREAMING_SNAKE_CASE : Dict = original_model({'''image''': original_pixel_values, '''text_input''': ['''''']} ).logits __SCREAMING_SNAKE_CASE : Dict = hf_model(lowercase__ , lowercase__ ).logits else: __SCREAMING_SNAKE_CASE : int = original_model( {'''image''': original_pixel_values, '''text_input''': ['''\n'''], '''text_output''': ['''\n''']} ).logits __SCREAMING_SNAKE_CASE : List[Any] = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) __SCREAMING_SNAKE_CASE : Optional[int] = hf_model(lowercase__ , lowercase__ , labels=lowercase__ ).logits assert original_logits.shape == logits.shape print('''First values of original logits:''' , original_logits[0, :3, :3] ) print('''First values of HF logits:''' , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": __SCREAMING_SNAKE_CASE : Dict = torch.tensor( [[-41.5850, -4.4440, -8.9922], [-47.4322, -5.9143, -1.7340]] , device=lowercase__ ) assert torch.allclose(logits[0, :3, :3] , lowercase__ , atol=1e-4 ) elif model_name == "blip2-flan-t5-xl-coco": __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-57.0109, -9.8967, -12.6280], [-68.6578, -12.7191, -10.5065]] , device=lowercase__ ) else: # cast to same type __SCREAMING_SNAKE_CASE : Optional[Any] = logits.dtype assert torch.allclose(original_logits.to(lowercase__ ) , lowercase__ , atol=1e-2 ) print('''Looks ok!''' ) print('''Generating a caption...''' ) __SCREAMING_SNAKE_CASE : Any = '''''' __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(lowercase__ , return_tensors='''pt''' ).input_ids.to(lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = original_model.generate({'''image''': original_pixel_values} ) __SCREAMING_SNAKE_CASE : Union[str, Any] = hf_model.generate( lowercase__ , lowercase__ , do_sample=lowercase__ , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print('''Original generation:''' , lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = input_ids.shape[1] __SCREAMING_SNAKE_CASE : Any = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = [text.strip() for text in output_text] print('''HF generation:''' , lowercase__ ) if pytorch_dump_folder_path is not None: processor.save_pretrained(lowercase__ ) hf_model.save_pretrained(lowercase__ ) if push_to_hub: processor.push_to_hub(F'''nielsr/{model_name}''' ) hf_model.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": __lowerCAmelCase : List[str] =argparse.ArgumentParser() __lowerCAmelCase : Tuple =[ 'blip2-opt-2.7b', 'blip2-opt-6.7b', 'blip2-opt-2.7b-coco', 'blip2-opt-6.7b-coco', 'blip2-flan-t5-xl', 'blip2-flan-t5-xl-coco', 'blip2-flan-t5-xxl', ] parser.add_argument( '--model_name', default='blip2-opt-2.7b', choices=choices, type=str, help='Path to hf config.json of model to convert', ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub after converting', ) __lowerCAmelCase : List[Any] =parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
9
0
"""simple docstring""" def __lowercase ( snake_case_ : str ,snake_case_ : str ) ->Tuple: '''simple docstring''' assert x is not None assert y is not None __A : Any = len(snake_case_ ) __A : Optional[int] = len(snake_case_ ) # declaring the array for storing the dp values __A : List[Any] = [[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741 for i in range(1 ,m + 1 ): for j in range(1 ,n + 1 ): __A : Optional[Any] = 1 if x[i - 1] == y[j - 1] else 0 __A : Optional[Any] = max(l[i - 1][j] ,l[i][j - 1] ,l[i - 1][j - 1] + match ) __A : Tuple = '''''' __A , __A : List[Any] = m, n while i > 0 and j > 0: __A : Optional[Any] = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: __A : Optional[int] = x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": a_ = """AGGTAB""" a_ = """GXTXAYB""" a_ = 4 a_ = """GTAB""" a_ , a_ = longest_common_subsequence(a, b) print("""len =""", ln, """, sub-sequence =""", subseq) import doctest doctest.testmod()
291
"""simple docstring""" import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a_ = { """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a_ = """ETAOINSHRDLCUMWFGYPBVKJXQZ""" a_ = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def __lowercase ( snake_case_ : str ) ->dict[str, int]: '''simple docstring''' __A : Any = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def __lowercase ( snake_case_ : tuple ) ->str: '''simple docstring''' return x[0] def __lowercase ( snake_case_ : str ) ->str: '''simple docstring''' __A : Union[str, Any] = get_letter_count(snake_case_ ) __A : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(snake_case_ ) __A : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find ,reverse=snake_case_ ) __A : Optional[int] = ''''''.join(freq_to_letter[freq] ) __A : str = list(freq_to_letter_str.items() ) freq_pairs.sort(key=snake_case_ ,reverse=snake_case_ ) __A : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(snake_case_ ) def __lowercase ( snake_case_ : str ) ->int: '''simple docstring''' __A : Any = get_frequency_order(snake_case_ ) __A : str = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
291
1
import os import sys import unittest __UpperCamelCase : Optional[Any] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) __UpperCamelCase : List[Any] = os.path.join('tests', 'models', 'bert', 'test_modeling_bert.py') __UpperCamelCase : Tuple = os.path.join('tests', 'models', 'blip', 'test_modeling_blip.py') class lowercase__ ( unittest.TestCase): def __A ( self : int ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = get_test_to_tester_mapping(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Tuple = get_test_to_tester_mapping(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = {'''BertModelTest''': '''BertModelTester'''} SCREAMING_SNAKE_CASE : Tuple = { '''BlipModelTest''': '''BlipModelTester''', '''BlipTextImageModelTest''': '''BlipTextImageModelsModelTester''', '''BlipTextModelTest''': '''BlipTextModelTester''', '''BlipTextRetrievalModelTest''': '''BlipTextRetrievalModelTester''', '''BlipVQAModelTest''': '''BlipVQAModelTester''', '''BlipVisionModelTest''': '''BlipVisionModelTester''', } self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = get_model_to_test_mapping(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = get_model_to_test_mapping(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : int = { '''BertForMaskedLM''': ['''BertModelTest'''], '''BertForMultipleChoice''': ['''BertModelTest'''], '''BertForNextSentencePrediction''': ['''BertModelTest'''], '''BertForPreTraining''': ['''BertModelTest'''], '''BertForQuestionAnswering''': ['''BertModelTest'''], '''BertForSequenceClassification''': ['''BertModelTest'''], '''BertForTokenClassification''': ['''BertModelTest'''], '''BertLMHeadModel''': ['''BertModelTest'''], '''BertModel''': ['''BertModelTest'''], } SCREAMING_SNAKE_CASE : Optional[Any] = { '''BlipForConditionalGeneration''': ['''BlipTextImageModelTest'''], '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTest'''], '''BlipForQuestionAnswering''': ['''BlipVQAModelTest'''], '''BlipModel''': ['''BlipModelTest'''], '''BlipTextModel''': ['''BlipTextModelTest'''], '''BlipVisionModel''': ['''BlipVisionModelTest'''], } self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = get_model_to_tester_mapping(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : Any = get_model_to_tester_mapping(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = { '''BertForMaskedLM''': ['''BertModelTester'''], '''BertForMultipleChoice''': ['''BertModelTester'''], '''BertForNextSentencePrediction''': ['''BertModelTester'''], '''BertForPreTraining''': ['''BertModelTester'''], '''BertForQuestionAnswering''': ['''BertModelTester'''], '''BertForSequenceClassification''': ['''BertModelTester'''], '''BertForTokenClassification''': ['''BertModelTester'''], '''BertLMHeadModel''': ['''BertModelTester'''], '''BertModel''': ['''BertModelTester'''], } SCREAMING_SNAKE_CASE : str = { '''BlipForConditionalGeneration''': ['''BlipTextImageModelsModelTester'''], '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTester'''], '''BlipForQuestionAnswering''': ['''BlipVQAModelTester'''], '''BlipModel''': ['''BlipModelTester'''], '''BlipTextModel''': ['''BlipTextModelTester'''], '''BlipVisionModel''': ['''BlipVisionModelTester'''], } self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(get_test_info.to_json(UpperCamelCase__ ) , UpperCamelCase__ )
182
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def A ( _lowercase ): if "model" in orig_key: SCREAMING_SNAKE_CASE : int = orig_key.replace('''model.''' , '''''' ) if "norm1" in orig_key: SCREAMING_SNAKE_CASE : List[Any] = orig_key.replace('''norm1''' , '''attention.output.LayerNorm''' ) if "norm2" in orig_key: SCREAMING_SNAKE_CASE : str = orig_key.replace('''norm2''' , '''output.LayerNorm''' ) if "norm" in orig_key: SCREAMING_SNAKE_CASE : Tuple = orig_key.replace('''norm''' , '''LayerNorm''' ) if "transformer" in orig_key: SCREAMING_SNAKE_CASE : int = orig_key.split('''.''' )[0].split('''_''' )[-1] SCREAMING_SNAKE_CASE : List[str] = orig_key.replace(f"""transformer_{layer_num}""" , f"""encoder.layer.{layer_num}""" ) if "mha.attn" in orig_key: SCREAMING_SNAKE_CASE : Any = orig_key.replace('''mha.attn''' , '''attention.self''' ) if "mha" in orig_key: SCREAMING_SNAKE_CASE : Optional[int] = orig_key.replace('''mha''' , '''attention''' ) if "W_q" in orig_key: SCREAMING_SNAKE_CASE : List[Any] = orig_key.replace('''W_q''' , '''self.query''' ) if "W_k" in orig_key: SCREAMING_SNAKE_CASE : Optional[int] = orig_key.replace('''W_k''' , '''self.key''' ) if "W_v" in orig_key: SCREAMING_SNAKE_CASE : str = orig_key.replace('''W_v''' , '''self.value''' ) if "ff1" in orig_key: SCREAMING_SNAKE_CASE : Any = orig_key.replace('''ff1''' , '''intermediate.dense''' ) if "ff2" in orig_key: SCREAMING_SNAKE_CASE : List[Any] = orig_key.replace('''ff2''' , '''output.dense''' ) if "ff" in orig_key: SCREAMING_SNAKE_CASE : Dict = orig_key.replace('''ff''' , '''output.dense''' ) if "mlm_class" in orig_key: SCREAMING_SNAKE_CASE : Optional[int] = orig_key.replace('''mlm.mlm_class''' , '''cls.predictions.decoder''' ) if "mlm" in orig_key: SCREAMING_SNAKE_CASE : str = orig_key.replace('''mlm''' , '''cls.predictions.transform''' ) if "cls" not in orig_key: SCREAMING_SNAKE_CASE : List[str] = '''yoso.''' + orig_key return orig_key def A ( _lowercase , _lowercase ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Union[str, Any] = orig_state_dict.pop(_lowercase ) if ("pooler" in key) or ("sen_class" in key): continue else: SCREAMING_SNAKE_CASE : Union[str, Any] = val SCREAMING_SNAKE_CASE : List[str] = orig_state_dict['''cls.predictions.decoder.bias'''] SCREAMING_SNAKE_CASE : Dict = torch.arange(_lowercase ).expand((1, -1) ) + 2 return orig_state_dict def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Tuple = torch.load(_lowercase , map_location='''cpu''' )['''model_state_dict'''] SCREAMING_SNAKE_CASE : List[Any] = YosoConfig.from_json_file(_lowercase ) SCREAMING_SNAKE_CASE : str = YosoForMaskedLM(_lowercase ) SCREAMING_SNAKE_CASE : Union[str, Any] = convert_checkpoint_helper(config.max_position_embeddings , _lowercase ) print(model.load_state_dict(_lowercase ) ) model.eval() model.save_pretrained(_lowercase ) print(f"""Checkpoint successfuly converted. Model saved at {pytorch_dump_path}""" ) if __name__ == "__main__": __UpperCamelCase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to YOSO pytorch checkpoint.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for YOSO model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __UpperCamelCase : Optional[Any] = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
182
1
'''simple docstring''' from .data_collator import ( DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeqaSeq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, DefaultDataCollator, default_data_collator, ) from .metrics import glue_compute_metrics, xnli_compute_metrics from .processors import ( DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor, SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels, squad_convert_examples_to_features, xnli_output_modes, xnli_processors, xnli_tasks_num_labels, )
270
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __lowerCAmelCase = { 'configuration_efficientformer': [ 'EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientFormerConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = ['EfficientFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ 'EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientFormerForImageClassification', 'EfficientFormerForImageClassificationWithTeacher', 'EfficientFormerModel', 'EfficientFormerPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ 'TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFEfficientFormerForImageClassification', 'TFEfficientFormerForImageClassificationWithTeacher', 'TFEfficientFormerModel', 'TFEfficientFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
270
1
a_ = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []} a_ = ['a', 'b', 'c', 'd', 'e'] def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : List[Any] = start # add current to visited visited.append(_a) SCREAMING_SNAKE_CASE : Any = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: SCREAMING_SNAKE_CASE : Optional[int] = topological_sort(_a , _a , _a) # if all neighbors visited add current to sort sort.append(_a) # if all vertices haven't been visited select a new one to visit if len(_a) != len(_a): for vertice in vertices: if vertice not in visited: SCREAMING_SNAKE_CASE : Optional[int] = topological_sort(_a , _a , _a) # return sort return sort if __name__ == "__main__": a_ = topological_sort('a', [], []) print(sort)
76
from typing import Any class __SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , A : Any ) ->Optional[int]: lowerCamelCase__ : Optional[int] = data lowerCamelCase__ : Any = None class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] ) ->str: lowerCamelCase__ : Any = None def __lowerCamelCase ( self : Tuple ) ->Any: lowerCamelCase__ : str = self.head while temp is not None: print(temp.data , end=''' ''' ) lowerCamelCase__ : Dict = temp.next print() def __lowerCamelCase ( self : Dict , A : Any ) ->Optional[int]: lowerCamelCase__ : Union[str, Any] = Node(A ) lowerCamelCase__ : Dict = self.head lowerCamelCase__ : List[str] = new_node def __lowerCamelCase ( self : Optional[int] , A : int , A : Tuple ) ->List[Any]: if node_data_a == node_data_a: return else: lowerCamelCase__ : Tuple = self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase__ : Union[str, Any] = node_a.next lowerCamelCase__ : int = self.head while node_a is not None and node_a.data != node_data_a: lowerCamelCase__ : Optional[int] = node_a.next if node_a is None or node_a is None: return lowerCamelCase__ , lowerCamelCase__ : str = node_a.data, node_a.data if __name__ == "__main__": _A : List[Any] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('After swapping') ll.print_list()
142
0
# Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def _a ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: '''simple docstring''' return 1 / (1 + np.exp(-z )) def _a ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return (-y * np.log(snake_case__ ) - (1 - y) * np.log(1 - h )).mean() def _a ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = np.dot(snake_case__ , snake_case__ ) return np.sum(y * scores - np.log(1 + np.exp(snake_case__ ) ) ) def _a ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int=7_00_00 ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = np.zeros(x.shape[1] ) for iterations in range(snake_case__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.dot(snake_case__ , snake_case__ ) SCREAMING_SNAKE_CASE__ : int = sigmoid_function(snake_case__ ) SCREAMING_SNAKE_CASE__ : str = np.dot(x.T , h - y ) / y.size SCREAMING_SNAKE_CASE__ : Optional[Any] = theta - alpha * gradient # updating the weights SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(snake_case__ , snake_case__ ) SCREAMING_SNAKE_CASE__ : Tuple = sigmoid_function(snake_case__ ) SCREAMING_SNAKE_CASE__ : int = cost_function(snake_case__ , snake_case__ ) if iterations % 1_00 == 0: print(f'''loss: {j} \t''' ) # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": _lowerCamelCase : str = datasets.load_iris() _lowerCamelCase : Optional[Any] = iris.data[:, :2] _lowerCamelCase : Dict = (iris.target != 0) * 1 _lowerCamelCase : Optional[Any] = 0.1 _lowerCamelCase : Dict = logistic_reg(alpha, x, y, max_iterations=7_0_0_0_0) print('''theta: ''', theta) # printing the theta i.e our weights vector def _a ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return sigmoid_function( np.dot(snake_case__ , snake_case__ ) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(1_0, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color='''b''', label='''0''') plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color='''r''', label='''1''') ((_lowerCamelCase) , (_lowerCamelCase)) : Any = (x[:, 0].min(), x[:, 0].max()) ((_lowerCamelCase) , (_lowerCamelCase)) : Dict = (x[:, 1].min(), x[:, 1].max()) ((_lowerCamelCase) , (_lowerCamelCase)) : int = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max)) _lowerCamelCase : Dict = np.c_[xxa.ravel(), xxa.ravel()] _lowerCamelCase : List[Any] = predict_prob(grid).reshape(xxa.shape) plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors='''black''') plt.legend() plt.show()
365
from queue import PriorityQueue from typing import Any import numpy as np def _a ( SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : set , SCREAMING_SNAKE_CASE__ : set , SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : PriorityQueue , SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : float | int , ) -> float | int: '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue SCREAMING_SNAKE_CASE__ : Union[str, Any] = cst_fwd.get(SCREAMING_SNAKE_CASE__ , np.inf ) SCREAMING_SNAKE_CASE__ : Optional[int] = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) SCREAMING_SNAKE_CASE__ : List[Any] = new_cost_f SCREAMING_SNAKE_CASE__ : Union[str, Any] = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: SCREAMING_SNAKE_CASE__ : Optional[int] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _a ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : dict ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = -1 SCREAMING_SNAKE_CASE__ : List[str] = set() SCREAMING_SNAKE_CASE__ : List[Any] = set() SCREAMING_SNAKE_CASE__ : int = {source: 0} SCREAMING_SNAKE_CASE__ : Union[str, Any] = {destination: 0} SCREAMING_SNAKE_CASE__ : List[Any] = {source: None} SCREAMING_SNAKE_CASE__ : Union[str, Any] = {destination: None} SCREAMING_SNAKE_CASE__ : PriorityQueue[Any] = PriorityQueue() SCREAMING_SNAKE_CASE__ : PriorityQueue[Any] = PriorityQueue() SCREAMING_SNAKE_CASE__ : Dict = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[str] = queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ : List[Any] = queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = pass_and_relaxation( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) SCREAMING_SNAKE_CASE__ : List[Any] = pass_and_relaxation( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: SCREAMING_SNAKE_CASE__ : int = shortest_distance return shortest_path_distance _lowerCamelCase : Optional[Any] = { '''B''': [['''C''', 1]], '''C''': [['''D''', 1]], '''D''': [['''F''', 1]], '''E''': [['''B''', 1], ['''G''', 2]], '''F''': [], '''G''': [['''F''', 1]], } _lowerCamelCase : Tuple = { '''B''': [['''E''', 1]], '''C''': [['''B''', 1]], '''D''': [['''C''', 1]], '''F''': [['''D''', 1], ['''G''', 1]], '''E''': [[None, np.inf]], '''G''': [['''E''', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
191
0
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) __A = "hf-internal-testing/tiny-random-bert" __A = os.path.join(TRANSFORMERS_CACHE, "models--hf-internal-testing--tiny-random-bert") __A = "9b8c223d42b2188cb49d29af482996f9d0f3e5a6" class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__: Any =cached_file(UpperCAmelCase_ , UpperCAmelCase_) # Should have downloaded the file in here self.assertTrue(os.path.isdir(UpperCAmelCase_)) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(UpperCAmelCase_ , UpperCAmelCase_))) with open(os.path.join(UpperCAmelCase_ , "refs" , "main")) as f: lowerCamelCase__: List[Any] =f.read() self.assertEqual(UpperCAmelCase_ , os.path.join(UpperCAmelCase_ , "snapshots" , UpperCAmelCase_ , UpperCAmelCase_)) self.assertTrue(os.path.isfile(UpperCAmelCase_)) # File is cached at the same place the second time. lowerCamelCase__: Optional[Any] =cached_file(UpperCAmelCase_ , UpperCAmelCase_) self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_) # Using a specific revision to test the full commit hash. lowerCamelCase__: str =cached_file(UpperCAmelCase_ , UpperCAmelCase_ , revision="9b8c223") self.assertEqual(UpperCAmelCase_ , os.path.join(UpperCAmelCase_ , "snapshots" , UpperCAmelCase_ , UpperCAmelCase_)) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->str: '''simple docstring''' with self.assertRaisesRegex(UpperCAmelCase_ , "is not a valid model identifier"): lowerCamelCase__: List[Any] =cached_file("tiny-random-bert" , UpperCAmelCase_) with self.assertRaisesRegex(UpperCAmelCase_ , "is not a valid git identifier"): lowerCamelCase__: List[str] =cached_file(UpperCAmelCase_ , UpperCAmelCase_ , revision="aaaa") with self.assertRaisesRegex(UpperCAmelCase_ , "does not appear to have a file named"): lowerCamelCase__: Optional[Any] =cached_file(UpperCAmelCase_ , "conf") def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->List[str]: '''simple docstring''' with self.assertRaisesRegex(UpperCAmelCase_ , "does not appear to have a file named"): lowerCamelCase__: Dict =cached_file(UpperCAmelCase_ , "conf") with open(os.path.join(UpperCAmelCase_ , "refs" , "main")) as f: lowerCamelCase__: List[str] =f.read() self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase_ , ".no_exist" , UpperCAmelCase_ , "conf"))) lowerCamelCase__: Union[str, Any] =cached_file(UpperCAmelCase_ , "conf" , _raise_exceptions_for_missing_entries=UpperCAmelCase_) self.assertIsNone(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =cached_file(UpperCAmelCase_ , "conf" , local_files_only=UpperCAmelCase_ , _raise_exceptions_for_missing_entries=UpperCAmelCase_) self.assertIsNone(UpperCAmelCase_) lowerCamelCase__: List[Any] =mock.Mock() lowerCamelCase__: int =500 lowerCamelCase__: Union[str, Any] ={} lowerCamelCase__: Any =HTTPError lowerCamelCase__: List[Any] ={} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=UpperCAmelCase_) as mock_head: lowerCamelCase__: int =cached_file(UpperCAmelCase_ , "conf" , _raise_exceptions_for_connection_errors=UpperCAmelCase_) self.assertIsNone(UpperCAmelCase_) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Tuple: '''simple docstring''' self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only" , UpperCAmelCase_)) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , UpperCAmelCase_)) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , UpperCAmelCase_)) def SCREAMING_SNAKE_CASE_ (self : Dict) ->List[str]: '''simple docstring''' self.assertIsNone(get_file_from_repo("bert-base-cased" , "ahah.txt")) # The function raises if the repository does not exist. with self.assertRaisesRegex(UpperCAmelCase_ , "is not a valid model identifier"): get_file_from_repo("bert-base-case" , UpperCAmelCase_) # The function raises if the revision does not exist. with self.assertRaisesRegex(UpperCAmelCase_ , "is not a valid git identifier"): get_file_from_repo("bert-base-cased" , UpperCAmelCase_ , revision="ahaha") lowerCamelCase__: List[str] =get_file_from_repo("bert-base-cased" , UpperCAmelCase_) # The name is the cached name which is not very easy to test, so instead we load the content. lowerCamelCase__: List[str] =json.loads(open(UpperCAmelCase_ , "r").read()) self.assertEqual(config["hidden_size"] , 768) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase__: List[Any] =Path(UpperCAmelCase_) / "a.txt" filename.touch() self.assertEqual(get_file_from_repo(UpperCAmelCase_ , "a.txt") , str(UpperCAmelCase_)) self.assertIsNone(get_file_from_repo(UpperCAmelCase_ , "b.txt"))
10
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class a ( a_ ): def __init__( self , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase ): lowercase = parent lowercase = config_class lowercase = has_text_modality lowercase = kwargs lowercase = common_properties def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict ) lowercase = ( ['hidden_size', 'num_attention_heads', 'num_hidden_layers'] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(['vocab_size'] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(_lowerCamelCase , _lowerCamelCase ) , msg=F'`{prop}` does not exist' ) # Test that config has the common properties as setter for idx, name in enumerate(_lowerCamelCase ): try: setattr(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.parent.assertEqual( getattr(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , msg=F'`{name} value {idx} expected, but was {getattr(_lowerCamelCase , _lowerCamelCase )}' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(_lowerCamelCase ): try: lowercase = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , msg=F'`{name} value {idx} expected, but was {getattr(_lowerCamelCase , _lowerCamelCase )}' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict ) lowercase = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , _lowerCamelCase ) def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowercase = os.path.join(_lowerCamelCase , 'config.json' ) config_first.to_json_file(_lowerCamelCase ) lowercase = self.config_class.from_json_file(_lowerCamelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(_lowerCamelCase ) lowercase = self.config_class.from_pretrained(_lowerCamelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict ) lowercase = 'test' with tempfile.TemporaryDirectory() as tmpdirname: lowercase = os.path.join(_lowerCamelCase , _lowerCamelCase ) config_first.save_pretrained(_lowerCamelCase ) lowercase = self.config_class.from_pretrained(_lowerCamelCase , subfolder=_lowerCamelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def UpperCamelCase_ ( self ): lowercase = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) lowercase = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def UpperCamelCase_ ( self ): if self.config_class.is_composition: return lowercase = self.config_class() self.parent.assertIsNotNone(_lowerCamelCase ) def UpperCamelCase_ ( self ): lowercase = copy.deepcopy(_lowerCamelCase ) lowercase = self.config_class(**_lowerCamelCase ) lowercase = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(('torch_dtype', config.torch_dtype, torch.floataa) ) elif getattr(_lowerCamelCase , _lowerCamelCase ) != value: wrong_values.append((key, getattr(_lowerCamelCase , _lowerCamelCase ), value) ) if len(_lowerCamelCase ) > 0: lowercase = '\n'.join([F'- {v[0]}: got {v[1]} instead of {v[2]}' for v in wrong_values] ) raise ValueError(F'The following keys were not properly set in the config:\n{errors}' ) def UpperCamelCase_ ( self ): self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
220
0
'''simple docstring''' import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class __UpperCamelCase ( pl.LightningModule ): def __init__( self, lowerCAmelCase ): """simple docstring""" super().__init__() lowerCamelCase_ =model lowerCamelCase_ =2 lowerCamelCase_ =nn.Linear(self.model.config.hidden_size, self.num_labels ) def lowercase__ ( self ): """simple docstring""" pass def a_ ( __snake_case : List[Any] , __snake_case : Tuple , __snake_case : List[Any] ) -> Tuple: """simple docstring""" lowerCamelCase_ =LongformerModel.from_pretrained(_UpperCAmelCase ) lowerCamelCase_ =LightningModel(_UpperCAmelCase ) lowerCamelCase_ =torch.load(_UpperCAmelCase , map_location=torch.device('''cpu''' ) ) lightning_model.load_state_dict(ckpt['''state_dict'''] ) # init longformer question answering model lowerCamelCase_ =LongformerForQuestionAnswering.from_pretrained(_UpperCAmelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(_UpperCAmelCase ) print(F'''Conversion successful. Model saved under {pytorch_dump_folder_path}''' ) if __name__ == "__main__": a_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--longformer_model""", default=None, type=str, required=True, help="""model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.""", ) parser.add_argument( """--longformer_question_answering_ckpt_path""", default=None, type=str, required=True, help="""Path the official PyTorch Lightning Checkpoint.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) a_ : str = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
358
'''simple docstring''' from argparse import ArgumentParser from . import BaseTransformersCLICommand def a_ ( __snake_case : Tuple ) -> str: """simple docstring""" return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __UpperCamelCase ( lowerCamelCase__ ): @staticmethod def lowercase__ ( lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =parser.add_parser('''download''' ) download_parser.add_argument( '''--cache-dir''', type=lowerCAmelCase, default=lowerCAmelCase, help='''Path to location to store the models''' ) download_parser.add_argument( '''--force''', action='''store_true''', help='''Force the model to be download even if already in cache-dir''' ) download_parser.add_argument( '''--trust-remote-code''', action='''store_true''', help='''Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine''', ) download_parser.add_argument('''model''', type=lowerCAmelCase, help='''Name of the model to download''' ) download_parser.set_defaults(func=lowerCAmelCase ) def __init__( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =model lowerCamelCase_ =cache lowerCamelCase_ =force lowerCamelCase_ =trust_remote_code def lowercase__ ( self ): """simple docstring""" from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model, cache_dir=self._cache, force_download=self._force, trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model, cache_dir=self._cache, force_download=self._force, trust_remote_code=self._trust_remote_code )
6
0
"""simple docstring""" import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node lowerCAmelCase_ = 4 lowerCAmelCase_ = 3 class __A ( A_ ): '''simple docstring''' pass def __UpperCAmelCase ( __lowerCamelCase ) -> Dict: for shard in shards: for i in range(__lowerCamelCase ): yield {"i": i, "shard": shard} def __UpperCAmelCase ( ) -> Tuple: lowercase__ : int = int(os.environ['''RANK'''] ) lowercase__ : str = int(os.environ['''WORLD_SIZE'''] ) lowercase__ : List[Any] = ArgumentParser() parser.add_argument('''--streaming''' , type=__lowerCamelCase ) parser.add_argument('''--local_rank''' , type=__lowerCamelCase ) parser.add_argument('''--num_workers''' , type=__lowerCamelCase , default=0 ) lowercase__ : int = parser.parse_args() lowercase__ : Optional[Any] = args.streaming lowercase__ : List[Any] = args.num_workers lowercase__ : Optional[Any] = {'''shards''': [f"""shard_{shard_idx}""" for shard_idx in range(__lowerCamelCase )]} lowercase__ : Dict = IterableDataset.from_generator(__lowerCamelCase , gen_kwargs=__lowerCamelCase ) if not streaming: lowercase__ : int = Dataset.from_list(list(__lowerCamelCase ) ) lowercase__ : int = split_dataset_by_node(__lowerCamelCase , rank=__lowerCamelCase , world_size=__lowerCamelCase ) lowercase__ : Optional[Any] = torch.utils.data.DataLoader(__lowerCamelCase , num_workers=__lowerCamelCase ) lowercase__ : Optional[Any] = NUM_SHARDS * NUM_ITEMS_PER_SHARD lowercase__ : str = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) lowercase__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(f"""local_size {local_size} != expected_local_size {expected_local_size}""" ) if __name__ == "__main__": main()
16
"""simple docstring""" import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _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 SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] ,_snake_case : Optional[Any] ,_snake_case : Union[str, Any]=13 ,_snake_case : Any=32 ,_snake_case : int=2 ,_snake_case : str=3 ,_snake_case : Optional[Any]=16 ,_snake_case : List[Any]=[1, 2, 1] ,_snake_case : Dict=[2, 2, 4] ,_snake_case : List[Any]=2 ,_snake_case : Any=2.0 ,_snake_case : Optional[int]=True ,_snake_case : Optional[int]=0.0 ,_snake_case : Union[str, Any]=0.0 ,_snake_case : str=0.1 ,_snake_case : List[Any]="gelu" ,_snake_case : Tuple=False ,_snake_case : Optional[int]=True ,_snake_case : str=0.02 ,_snake_case : List[str]=1e-5 ,_snake_case : int=True ,_snake_case : Dict=None ,_snake_case : str=True ,_snake_case : List[Any]=10 ,_snake_case : Any=8 ,) -> Union[str, Any]: """simple docstring""" lowercase__ : Dict = parent lowercase__ : Any = batch_size lowercase__ : Union[str, Any] = image_size lowercase__ : Dict = patch_size lowercase__ : int = num_channels lowercase__ : Any = embed_dim lowercase__ : int = depths lowercase__ : Dict = num_heads lowercase__ : List[Any] = window_size lowercase__ : int = mlp_ratio lowercase__ : Optional[int] = qkv_bias lowercase__ : str = hidden_dropout_prob lowercase__ : List[Any] = attention_probs_dropout_prob lowercase__ : Dict = drop_path_rate lowercase__ : int = hidden_act lowercase__ : Tuple = use_absolute_embeddings lowercase__ : Tuple = patch_norm lowercase__ : Tuple = layer_norm_eps lowercase__ : Optional[Any] = initializer_range lowercase__ : int = is_training lowercase__ : Optional[int] = scope lowercase__ : str = use_labels lowercase__ : Dict = type_sequence_label_size lowercase__ : Union[str, Any] = encoder_stride def UpperCAmelCase ( self : Dict ) -> Any: """simple docstring""" lowercase__ : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ : Optional[Any] = None if self.use_labels: lowercase__ : Optional[int] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) lowercase__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def UpperCAmelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" return SwinvaConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,embed_dim=self.embed_dim ,depths=self.depths ,num_heads=self.num_heads ,window_size=self.window_size ,mlp_ratio=self.mlp_ratio ,qkv_bias=self.qkv_bias ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,drop_path_rate=self.drop_path_rate ,hidden_act=self.hidden_act ,use_absolute_embeddings=self.use_absolute_embeddings ,path_norm=self.patch_norm ,layer_norm_eps=self.layer_norm_eps ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def UpperCAmelCase ( self : str ,_snake_case : Dict ,_snake_case : List[str] ,_snake_case : Optional[int] ) -> Optional[int]: """simple docstring""" lowercase__ : Any = SwinvaModel(config=_snake_case ) model.to(_snake_case ) model.eval() lowercase__ : str = model(_snake_case ) lowercase__ : List[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) lowercase__ : Tuple = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, expected_seq_len, expected_dim) ) def UpperCAmelCase ( self : Union[str, Any] ,_snake_case : List[str] ,_snake_case : Optional[Any] ,_snake_case : int ) -> Any: """simple docstring""" lowercase__ : Union[str, Any] = SwinvaForMaskedImageModeling(config=_snake_case ) model.to(_snake_case ) model.eval() lowercase__ : Tuple = model(_snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images lowercase__ : Optional[int] = 1 lowercase__ : List[Any] = SwinvaForMaskedImageModeling(_snake_case ) model.to(_snake_case ) model.eval() lowercase__ : Union[str, Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase__ : str = model(_snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, 1, self.image_size, self.image_size) ) def UpperCAmelCase ( self : str ,_snake_case : str ,_snake_case : str ,_snake_case : Tuple ) -> Any: """simple docstring""" lowercase__ : Tuple = self.type_sequence_label_size lowercase__ : Dict = SwinvaForImageClassification(_snake_case ) model.to(_snake_case ) model.eval() lowercase__ : str = model(_snake_case ,labels=_snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase ( self : Dict ) -> Dict: """simple docstring""" lowercase__ : Optional[int] = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ : Union[str, Any] = config_and_inputs lowercase__ : List[str] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __A ( A_ ,A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) lowerCAmelCase : Optional[int] = ( {"feature-extraction": SwinvaModel, "image-classification": SwinvaForImageClassification} if is_torch_available() else {} ) lowerCAmelCase : List[Any] = False lowerCAmelCase : Dict = False lowerCAmelCase : List[Any] = False lowerCAmelCase : Any = False def UpperCAmelCase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" lowercase__ : Optional[Any] = SwinvaModelTester(self ) lowercase__ : List[str] = ConfigTester(self ,config_class=_snake_case ,embed_dim=37 ) def UpperCAmelCase ( self : int ) -> Any: """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 UpperCAmelCase ( self : str ) -> List[Any]: """simple docstring""" lowercase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) @unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.''' ) def UpperCAmelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" pass @unittest.skip(reason='''Swinv2 does not use inputs_embeds''' ) def UpperCAmelCase ( self : List[str] ) -> str: """simple docstring""" pass def UpperCAmelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" lowercase__ , lowercase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : List[Any] = model_class(_snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) lowercase__ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_snake_case ,nn.Linear ) ) def UpperCAmelCase ( self : int ) -> List[Any]: """simple docstring""" lowercase__ , lowercase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : str = model_class(_snake_case ) lowercase__ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Optional[Any] = [*signature.parameters.keys()] lowercase__ : Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] ,_snake_case ) def UpperCAmelCase ( self : List[Any] ) -> Any: """simple docstring""" lowercase__ , lowercase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Tuple = True for model_class in self.all_model_classes: lowercase__ : Optional[int] = True lowercase__ : str = False lowercase__ : Union[str, Any] = True lowercase__ : Optional[Any] = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): lowercase__ : str = model(**self._prepare_for_class(_snake_case ,_snake_case ) ) lowercase__ : Dict = outputs.attentions lowercase__ : Any = len(self.model_tester.depths ) self.assertEqual(len(_snake_case ) ,_snake_case ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowercase__ : List[Any] = True lowercase__ : Optional[Any] = config.window_size**2 lowercase__ : Any = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): lowercase__ : List[str] = model(**self._prepare_for_class(_snake_case ,_snake_case ) ) lowercase__ : Optional[Any] = outputs.attentions self.assertEqual(len(_snake_case ) ,_snake_case ) self.assertListEqual( list(attentions[0].shape[-3:] ) ,[self.model_tester.num_heads[0], window_size_squared, window_size_squared] ,) lowercase__ : Optional[Any] = len(_snake_case ) # Check attention is always last and order is fine lowercase__ : Optional[int] = True lowercase__ : Tuple = True lowercase__ : Optional[Any] = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): lowercase__ : Optional[Any] = model(**self._prepare_for_class(_snake_case ,_snake_case ) ) if hasattr(self.model_tester ,'''num_hidden_states_types''' ): lowercase__ : int = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states lowercase__ : List[str] = 2 self.assertEqual(out_len + added_hidden_states ,len(_snake_case ) ) lowercase__ : Optional[int] = outputs.attentions self.assertEqual(len(_snake_case ) ,_snake_case ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) ,[self.model_tester.num_heads[0], window_size_squared, window_size_squared] ,) def UpperCAmelCase ( self : List[str] ,_snake_case : int ,_snake_case : List[str] ,_snake_case : Optional[int] ,_snake_case : List[Any] ) -> Union[str, Any]: """simple docstring""" lowercase__ : List[Any] = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): lowercase__ : int = model(**self._prepare_for_class(_snake_case ,_snake_case ) ) lowercase__ : Optional[int] = outputs.hidden_states lowercase__ : List[Any] = getattr( self.model_tester ,'''expected_num_hidden_layers''' ,len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_snake_case ) ,_snake_case ) # Swinv2 has a different seq_length lowercase__ : Dict = ( config.patch_size if isinstance(config.patch_size ,collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ : int = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[num_patches, self.model_tester.embed_dim] ,) lowercase__ : Tuple = outputs.reshaped_hidden_states self.assertEqual(len(_snake_case ) ,_snake_case ) lowercase__ , lowercase__ , lowercase__ , lowercase__ : List[str] = reshaped_hidden_states[0].shape lowercase__ : int = ( reshaped_hidden_states[0].view(_snake_case ,_snake_case ,height * width ).permute(0 ,2 ,1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) ,[num_patches, self.model_tester.embed_dim] ,) def UpperCAmelCase ( self : Tuple ) -> int: """simple docstring""" lowercase__ , lowercase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size ,collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: lowercase__ : List[str] = True self.check_hidden_states_output(_snake_case ,_snake_case ,_snake_case ,_snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : str = True self.check_hidden_states_output(_snake_case ,_snake_case ,_snake_case ,_snake_case ) def UpperCAmelCase ( self : List[Any] ) -> List[Any]: """simple docstring""" lowercase__ , lowercase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : List[Any] = 3 lowercase__ : Tuple = ( self.model_tester.image_size if isinstance(self.model_tester.image_size ,collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) lowercase__ : Optional[int] = ( config.patch_size if isinstance(config.patch_size ,collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ : Dict = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowercase__ : Dict = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: lowercase__ : str = True self.check_hidden_states_output(_snake_case ,_snake_case ,_snake_case ,(padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : Dict = True self.check_hidden_states_output(_snake_case ,_snake_case ,_snake_case ,(padded_height, padded_width) ) def UpperCAmelCase ( self : Tuple ) -> List[Any]: """simple docstring""" lowercase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_snake_case ) def UpperCAmelCase ( self : Dict ) -> Any: """simple docstring""" lowercase__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_snake_case ) @slow def UpperCAmelCase ( self : List[str] ) -> Optional[Any]: """simple docstring""" for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ : Union[str, Any] = SwinvaModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) def UpperCAmelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" lowercase__ , lowercase__ : str = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Tuple = _config_zero_init(_snake_case ) for model_class in self.all_model_classes: lowercase__ : Optional[int] = model_class(config=_snake_case ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: 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""" ,) @require_vision @require_torch class __A ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCAmelCase ( self : Optional[Any] ) -> Tuple: """simple docstring""" return ( AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' ) if is_vision_available() else None ) @slow def UpperCAmelCase ( self : Any ) -> List[str]: """simple docstring""" lowercase__ : str = SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' ).to( _snake_case ) lowercase__ : Union[str, Any] = self.default_image_processor lowercase__ : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) lowercase__ : Dict = image_processor(images=_snake_case ,return_tensors='''pt''' ).to(_snake_case ) # forward pass with torch.no_grad(): lowercase__ : Optional[Any] = model(**_snake_case ) # verify the logits lowercase__ : str = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape ,_snake_case ) lowercase__ : Dict = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(_snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_snake_case ,atol=1e-4 ) )
16
1
from __future__ import annotations import requests A_ : Dict = set( 'approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports'.split() ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ = 1 , UpperCAmelCase__ = "new" , UpperCAmelCase__ = None ) -> dict: UpperCamelCase_: Optional[Any] = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(UpperCAmelCase__ ) - valid_terms ) ): UpperCamelCase_: Optional[int] = F'''Invalid search term: {invalid_search_terms}''' raise ValueError(UpperCAmelCase__ ) UpperCamelCase_: int = requests.get( F'''https://reddit.com/r/{subreddit}/{age}.json?limit={limit}''' , headers={'User-agent': 'A random string'} , ) if response.status_code == 4_2_9: raise requests.HTTPError UpperCamelCase_: Optional[int] = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(UpperCAmelCase__ )} UpperCamelCase_: Dict = {} for id_ in range(UpperCAmelCase__ ): UpperCamelCase_: Optional[int] = { item: data['data']['children'][id_]['data'][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data('learnpython', wanted_data=['title', 'url', 'selftext']))
357
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" @slow def _a ( self ): UpperCamelCase_: Optional[int] = AutoModelForSeqaSeqLM.from_pretrained('google/mt5-small' , return_dict=_lowerCamelCase ).to(_lowerCamelCase ) UpperCamelCase_: Dict = AutoTokenizer.from_pretrained('google/mt5-small' ) UpperCamelCase_: Dict = tokenizer('Hello there' , return_tensors='pt' ).input_ids UpperCamelCase_: Optional[Any] = tokenizer('Hi I am' , return_tensors='pt' ).input_ids UpperCamelCase_: int = model(input_ids.to(_lowerCamelCase ) , labels=labels.to(_lowerCamelCase ) ).loss UpperCamelCase_: Tuple = -(labels.shape[-1] * loss.item()) UpperCamelCase_: Any = -8_4.9_1_2_7 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
292
0
'''simple docstring''' from math import isqrt def _A ( snake_case ) -> str: _lowercase : Tuple = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , snake_case , snake_case ): _lowercase : int = False return [i for i in range(2 , snake_case ) if is_prime[i]] def _A ( snake_case = 10**8 ) -> Optional[Any]: _lowercase : Optional[int] = calculate_prime_numbers(max_number // 2 ) _lowercase : Optional[Any] = 0 _lowercase : Any = 0 _lowercase : Dict = len(snake_case ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(F'''{solution() = }''')
250
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
0
"""simple docstring""" import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class lowerCamelCase__ ( _a ): def __init__( self : Dict , _a : int=0.0_1 , _a : Tuple=1_0_0_0 ): a__: Union[str, Any] =p_stop a__: Dict =max_length def __iter__( self : Union[str, Any] ): a__: int =0 a__: Any =False while not stop and count < self.max_length: yield count count += 1 a__: List[str] =random.random() < self.p_stop class lowerCamelCase__ ( unittest.TestCase ): def _lowerCamelCase ( self : Tuple , _a : Tuple , _a : Union[str, Any] , _a : Optional[int]=False , _a : Optional[int]=True ): a__: Union[str, Any] =[ BatchSamplerShard(_a , 2 , _a , split_batches=_a , even_batches=_a ) for i in range(2 ) ] a__: Union[str, Any] =[list(_a ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(_a ) for shard in batch_sampler_shards] , [len(_a ) for e in expected] ) self.assertListEqual(_a , _a ) def _lowerCamelCase ( self : List[Any] ): # Check the shards when the dataset is a round multiple of total batch size. a__: Optional[int] =BatchSampler(range(2_4 ) , batch_size=3 , drop_last=_a ) a__: int =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1, 2_2, 2_3]], ] self.check_batch_sampler_shards(_a , _a ) a__: Tuple =BatchSampler(range(2_4 ) , batch_size=3 , drop_last=_a ) # Expected shouldn't change self.check_batch_sampler_shards(_a , _a ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. a__: int =BatchSampler(range(2_1 ) , batch_size=3 , drop_last=_a ) a__: int =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [0, 1, 2]], ] self.check_batch_sampler_shards(_a , _a ) a__: List[str] =BatchSampler(range(2_1 ) , batch_size=3 , drop_last=_a ) a__: List[str] =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(_a , _a ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. a__: Dict =BatchSampler(range(2_2 ) , batch_size=3 , drop_last=_a ) a__: str =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1, 0, 1]], ] self.check_batch_sampler_shards(_a , _a ) a__: Optional[int] =BatchSampler(range(2_2 ) , batch_size=3 , drop_last=_a ) a__: int =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(_a , _a ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. a__: List[Any] =BatchSampler(range(2_0 ) , batch_size=3 , drop_last=_a ) a__: str =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [1, 2, 3]], ] self.check_batch_sampler_shards(_a , _a ) a__: Optional[Any] =BatchSampler(range(2_0 ) , batch_size=3 , drop_last=_a ) a__: str =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(_a , _a ) # Check the shards when the dataset is very small. a__: str =BatchSampler(range(2 ) , batch_size=3 , drop_last=_a ) a__: List[str] =[[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(_a , _a ) a__: Any =BatchSampler(range(2 ) , batch_size=3 , drop_last=_a ) a__: Tuple =[[], []] self.check_batch_sampler_shards(_a , _a ) def _lowerCamelCase ( self : Union[str, Any] ): # Check the shards when the dataset is a round multiple of batch size. a__: List[Any] =BatchSampler(range(2_4 ) , batch_size=4 , drop_last=_a ) a__: Optional[Any] =[ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [2_2, 2_3]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) a__: str =BatchSampler(range(2_4 ) , batch_size=4 , drop_last=_a ) # Expected shouldn't change self.check_batch_sampler_shards(_a , _a , split_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size. a__: List[Any] =BatchSampler(range(2_2 ) , batch_size=4 , drop_last=_a ) a__: Optional[Any] =[ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [0, 1]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) a__: str =BatchSampler(range(2_2 ) , batch_size=4 , drop_last=_a ) a__: int =[ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. a__: Any =BatchSampler(range(2_1 ) , batch_size=4 , drop_last=_a ) a__: Any =[ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 0]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [1, 2]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) a__: Tuple =BatchSampler(range(2_1 ) , batch_size=4 , drop_last=_a ) a__: Optional[int] =[ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) # Check the shards when the dataset is very small. a__: Optional[int] =BatchSampler(range(2 ) , batch_size=4 , drop_last=_a ) a__: Dict =[[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) a__: List[str] =BatchSampler(range(2 ) , batch_size=4 , drop_last=_a ) a__: List[Any] =[[], []] self.check_batch_sampler_shards(_a , _a , split_batches=_a ) def _lowerCamelCase ( self : List[str] ): # Check the shards when the dataset is a round multiple of total batch size. a__: str =BatchSampler(range(2_4 ) , batch_size=3 , drop_last=_a ) a__: Optional[int] =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1, 2_2, 2_3]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) a__: Optional[Any] =BatchSampler(range(2_4 ) , batch_size=3 , drop_last=_a ) # Expected shouldn't change self.check_batch_sampler_shards(_a , _a , even_batches=_a ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. a__: Optional[Any] =BatchSampler(range(2_1 ) , batch_size=3 , drop_last=_a ) a__: Tuple =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) a__: Tuple =BatchSampler(range(2_1 ) , batch_size=3 , drop_last=_a ) a__: str =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. a__: List[str] =BatchSampler(range(2_2 ) , batch_size=3 , drop_last=_a ) a__: Tuple =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) a__: Optional[Any] =BatchSampler(range(2_2 ) , batch_size=3 , drop_last=_a ) a__: Optional[Any] =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. a__: Optional[Any] =BatchSampler(range(2_0 ) , batch_size=3 , drop_last=_a ) a__: Tuple =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) a__: List[str] =BatchSampler(range(2_0 ) , batch_size=3 , drop_last=_a ) a__: Dict =[ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) # Check the shards when the dataset is very small. a__: Optional[int] =BatchSampler(range(2 ) , batch_size=3 , drop_last=_a ) a__: Optional[Any] =[[[0, 1]], []] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) a__: Tuple =BatchSampler(range(2 ) , batch_size=3 , drop_last=_a ) a__: Optional[Any] =[[], []] self.check_batch_sampler_shards(_a , _a , even_batches=_a ) def _lowerCamelCase ( self : List[Any] ): # Check the shards when the dataset is a round multiple of batch size. a__: Optional[int] =BatchSampler(range(2_4 ) , batch_size=4 , drop_last=_a ) a__: Optional[int] =[ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [2_2, 2_3]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) a__: Union[str, Any] =BatchSampler(range(2_4 ) , batch_size=4 , drop_last=_a ) # Expected shouldn't change self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size. a__: Dict =BatchSampler(range(2_2 ) , batch_size=4 , drop_last=_a ) a__: Tuple =[ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) a__: Tuple =BatchSampler(range(2_2 ) , batch_size=4 , drop_last=_a ) a__: Dict =[ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. a__: Optional[Any] =BatchSampler(range(2_1 ) , batch_size=4 , drop_last=_a ) a__: List[Any] =[ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) a__: int =BatchSampler(range(2_1 ) , batch_size=4 , drop_last=_a ) a__: List[str] =[ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) # Check the shards when the dataset is very small. a__: int =BatchSampler(range(2 ) , batch_size=4 , drop_last=_a ) a__: List[Any] =[[[0, 1]], []] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) a__: Optional[int] =BatchSampler(range(2 ) , batch_size=4 , drop_last=_a ) a__: int =[[], []] self.check_batch_sampler_shards(_a , _a , split_batches=_a , even_batches=_a ) def _lowerCamelCase ( self : Union[str, Any] ): a__: List[Any] =[[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 1_0, 1_1], [1_2, 1_3]] a__: List[str] =[BatchSamplerShard(_a , 2 , _a , even_batches=_a ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [1_2, 1_3]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 1_0, 1_1]] ) def _lowerCamelCase ( self : List[Any] , _a : Optional[int] , _a : List[Any] , _a : str , _a : Optional[int]=False , _a : List[Any]=2 , _a : Optional[Any]=False ): random.seed(_a ) a__: int =list(_a ) a__: List[str] =[ IterableDatasetShard( _a , batch_size=_a , drop_last=_a , num_processes=_a , process_index=_a , split_batches=_a , ) for i in range(_a ) ] a__: List[str] =[] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(_a ) iterable_dataset_lists.append(list(_a ) ) a__: Optional[int] =batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size a__: Optional[Any] =iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(_a ) , len(_a ) ) self.assertTrue(len(_a ) % shard_batch_size == 0 ) a__: Tuple =[] for idx in range(0 , len(_a ) , _a ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(_a ) < len(_a ): reference += reference self.assertListEqual(_a , reference[: len(_a )] ) def _lowerCamelCase ( self : Optional[Any] ): a__: List[Any] =4_2 a__: int =RandomIterableDataset() self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) # Edge case with a very small dataset a__: str =RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) self.check_iterable_dataset_shards(_a , _a , batch_size=4 , drop_last=_a , split_batches=_a ) def _lowerCamelCase ( self : Union[str, Any] ): a__: List[str] =BatchSampler(range(1_6 ) , batch_size=4 , drop_last=_a ) a__: Any =SkipBatchSampler(_a , 2 ) self.assertListEqual(list(_a ) , [[8, 9, 1_0, 1_1], [1_2, 1_3, 1_4, 1_5]] ) def _lowerCamelCase ( self : Optional[Any] ): a__: Tuple =SkipDataLoader(list(range(1_6 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 1_0, 1_1], [1_2, 1_3, 1_4, 1_5]] ) def _lowerCamelCase ( self : Any ): a__: List[str] =DataLoader(list(range(1_6 ) ) , batch_size=4 ) a__: Any =skip_first_batches(_a , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 1_0, 1_1], [1_2, 1_3, 1_4, 1_5]] ) def _lowerCamelCase ( self : Any ): a__: str =DataLoaderShard(list(range(1_6 ) ) , batch_size=4 ) for idx, _ in enumerate(_a ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(_a ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def _lowerCamelCase ( self : List[Any] ): Accelerator() a__: List[Any] =DataLoaderDispatcher(range(1_6 ) , batch_size=4 ) for idx, _ in enumerate(_a ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(_a ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
371
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class lowerCamelCase__ ( unittest.TestCase ): def _lowerCamelCase ( self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowerCamelCase ( self : List[Any] ): a__: Any =StableDiffusionKDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4" ) a__: List[str] =sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) sd_pipe.set_scheduler("sample_euler" ) a__: Dict ="A painting of a squirrel eating a burger" a__: List[Any] =torch.manual_seed(0 ) a__: int =sd_pipe([prompt] , generator=_a , guidance_scale=9.0 , num_inference_steps=2_0 , output_type="np" ) a__: int =output.images a__: Optional[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__: Any =np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def _lowerCamelCase ( self : Optional[Any] ): a__: List[Any] =StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) a__: List[str] =sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) sd_pipe.set_scheduler("sample_euler" ) a__: int ="A painting of a squirrel eating a burger" a__: List[Any] =torch.manual_seed(0 ) a__: Optional[int] =sd_pipe([prompt] , generator=_a , guidance_scale=9.0 , num_inference_steps=2_0 , output_type="np" ) a__: List[str] =output.images a__: List[str] =image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__: Any =np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-1 def _lowerCamelCase ( self : List[str] ): a__: Optional[Any] =StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) a__: Optional[Any] =sd_pipe.to(_a ) sd_pipe.set_progress_bar_config(disable=_a ) sd_pipe.set_scheduler("sample_dpmpp_2m" ) a__: Tuple ="A painting of a squirrel eating a burger" a__: Tuple =torch.manual_seed(0 ) a__: Optional[int] =sd_pipe( [prompt] , generator=_a , guidance_scale=7.5 , num_inference_steps=1_5 , output_type="np" , use_karras_sigmas=_a , ) a__: str =output.images a__: str =image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) a__: List[Any] =np.array( [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
42
0
from PIL import Image def a__ ( _UpperCamelCase : Image ,_UpperCamelCase : float ): def brightness(_UpperCamelCase : int ) -> float: return 1_28 + level + (c - 1_28) if not -255.0 <= level <= 255.0: raise ValueError('''level must be between -255.0 (black) and 255.0 (white)''' ) return img.point(_UpperCamelCase ) if __name__ == "__main__": # Load image with Image.open("""image_data/lena.jpg""") as img: # Change brightness to 100 a_ = change_brightness(img, 100) brigt_img.save("""image_data/lena_brightness.png""", format="""png""")
330
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING a_ = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase__ ) class __lowerCAmelCase ( lowerCAmelCase__ ): def __init__( self , *__UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' super().__init__(*__UpperCAmelCase , **__UpperCAmelCase ) requires_backends(self , '''vision''' ) self.check_model_type(__UpperCAmelCase ) def __call__( self , __UpperCAmelCase , **__UpperCAmelCase ): '''simple docstring''' return super().__call__(__UpperCAmelCase , **__UpperCAmelCase ) def lowerCamelCase ( self , **__UpperCAmelCase ): '''simple docstring''' return {}, {}, {} def lowerCamelCase ( self , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = load_image(__UpperCAmelCase ) __lowerCamelCase = image.size __lowerCamelCase = self.image_processor(images=__UpperCAmelCase , return_tensors=self.framework ) return model_inputs def lowerCamelCase ( self , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = self.model(**__UpperCAmelCase ) return model_outputs def lowerCamelCase ( self , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = model_outputs.predicted_depth __lowerCamelCase = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='''bicubic''' , align_corners=__UpperCAmelCase ) __lowerCamelCase = prediction.squeeze().cpu().numpy() __lowerCamelCase = (output * 255 / np.max(__UpperCAmelCase )).astype('''uint8''' ) __lowerCamelCase = Image.fromarray(__UpperCAmelCase ) __lowerCamelCase = {} __lowerCamelCase = predicted_depth __lowerCamelCase = depth return output_dict
330
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) snake_case : List[str] = {'''configuration_encoder_decoder''': ['''EncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : Optional[int] = ['''EncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : Any = ['''TFEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : Union[str, Any] = ['''FlaxEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys snake_case : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
360
import gc import math import unittest import torch from diffusers import UNetaDModel from diffusers.utils import floats_tensor, logging, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin snake_case : Tuple = logging.get_logger(__name__) enable_full_determinism() class snake_case_ (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): UpperCAmelCase__ : str = UNetaDModel UpperCAmelCase__ : str = '''sample''' @property def lowerCamelCase__( self :Optional[int] ) -> List[str]: a__ = 4 a__ = 3 a__ = (32, 32) a__ = floats_tensor((batch_size, num_channels) + sizes ).to(__snake_case ) a__ = torch.tensor([10] ).to(__snake_case ) return {"sample": noise, "timestep": time_step} @property def lowerCamelCase__( self :Tuple ) -> Tuple: return (3, 32, 32) @property def lowerCamelCase__( self :List[str] ) -> Optional[Any]: return (3, 32, 32) def lowerCamelCase__( self :str ) -> Tuple: a__ = { 'block_out_channels': (32, 64), 'down_block_types': ('DownBlock2D', 'AttnDownBlock2D'), 'up_block_types': ('AttnUpBlock2D', 'UpBlock2D'), 'attention_head_dim': 3, 'out_channels': 3, 'in_channels': 3, 'layers_per_block': 2, 'sample_size': 32, } a__ = self.dummy_input return init_dict, inputs_dict class snake_case_ (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): UpperCAmelCase__ : int = UNetaDModel UpperCAmelCase__ : Any = '''sample''' @property def lowerCamelCase__( self :Dict ) -> List[str]: a__ = 4 a__ = 4 a__ = (32, 32) a__ = floats_tensor((batch_size, num_channels) + sizes ).to(__snake_case ) a__ = torch.tensor([10] ).to(__snake_case ) return {"sample": noise, "timestep": time_step} @property def lowerCamelCase__( self :Any ) -> str: return (4, 32, 32) @property def lowerCamelCase__( self :Any ) -> Dict: return (4, 32, 32) def lowerCamelCase__( self :int ) -> int: a__ = { 'sample_size': 32, 'in_channels': 4, 'out_channels': 4, 'layers_per_block': 2, 'block_out_channels': (32, 64), 'attention_head_dim': 32, 'down_block_types': ('DownBlock2D', 'DownBlock2D'), 'up_block_types': ('UpBlock2D', 'UpBlock2D'), } a__ = self.dummy_input return init_dict, inputs_dict def lowerCamelCase__( self :str ) -> Any: a__ , a__ = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' ,output_loading_info=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertEqual(len(loading_info['missing_keys'] ) ,0 ) model.to(__snake_case ) a__ = model(**self.dummy_input ).sample assert image is not None, "Make sure output is not None" @unittest.skipIf(torch_device != 'cuda' ,'This test is supposed to run on GPU' ) def lowerCamelCase__( self :Tuple ) -> Optional[int]: a__ , a__ = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' ,output_loading_info=__snake_case ) model.to(__snake_case ) a__ = model(**self.dummy_input ).sample assert image is not None, "Make sure output is not None" @unittest.skipIf(torch_device != 'cuda' ,'This test is supposed to run on GPU' ) def lowerCamelCase__( self :Union[str, Any] ) -> int: # by defautl model loading will use accelerate as `low_cpu_mem_usage=True` a__ , a__ = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' ,output_loading_info=__snake_case ) model_accelerate.to(__snake_case ) model_accelerate.eval() a__ = torch.randn( 1 ,model_accelerate.config.in_channels ,model_accelerate.config.sample_size ,model_accelerate.config.sample_size ,generator=torch.manual_seed(0 ) ,) a__ = noise.to(__snake_case ) a__ = torch.tensor([10] * noise.shape[0] ).to(__snake_case ) a__ = model_accelerate(__snake_case ,__snake_case )['sample'] # two models don't need to stay in the device at the same time del model_accelerate torch.cuda.empty_cache() gc.collect() a__ , a__ = UNetaDModel.from_pretrained( 'fusing/unet-ldm-dummy-update' ,output_loading_info=__snake_case ,low_cpu_mem_usage=__snake_case ) model_normal_load.to(__snake_case ) model_normal_load.eval() a__ = model_normal_load(__snake_case ,__snake_case )['sample'] assert torch_all_close(__snake_case ,__snake_case ,rtol=1E-3 ) def lowerCamelCase__( self :str ) -> Union[str, Any]: a__ = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' ) model.eval() model.to(__snake_case ) a__ = torch.randn( 1 ,model.config.in_channels ,model.config.sample_size ,model.config.sample_size ,generator=torch.manual_seed(0 ) ,) a__ = noise.to(__snake_case ) a__ = torch.tensor([10] * noise.shape[0] ).to(__snake_case ) with torch.no_grad(): a__ = model(__snake_case ,__snake_case ).sample a__ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off a__ = torch.tensor([-13.32_58, -20.11_00, -15.98_73, -17.66_17, -23.05_96, -17.94_19, -13.36_75, -16.18_89, -12.38_00] ) # fmt: on self.assertTrue(torch_all_close(__snake_case ,__snake_case ,rtol=1E-3 ) ) class snake_case_ (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): UpperCAmelCase__ : Dict = UNetaDModel UpperCAmelCase__ : Optional[Any] = '''sample''' @property def lowerCamelCase__( self :Optional[Any] ,__snake_case :List[Any]=(32, 32) ) -> Optional[int]: a__ = 4 a__ = 3 a__ = floats_tensor((batch_size, num_channels) + sizes ).to(__snake_case ) a__ = torch.tensor(batch_size * [10] ).to(dtype=torch.intaa ,device=__snake_case ) return {"sample": noise, "timestep": time_step} @property def lowerCamelCase__( self :Tuple ) -> Optional[int]: return (3, 32, 32) @property def lowerCamelCase__( self :Optional[Any] ) -> Optional[int]: return (3, 32, 32) def lowerCamelCase__( self :Optional[Any] ) -> List[str]: a__ = { 'block_out_channels': [32, 64, 64, 64], 'in_channels': 3, 'layers_per_block': 1, 'out_channels': 3, 'time_embedding_type': 'fourier', 'norm_eps': 1E-6, 'mid_block_scale_factor': math.sqrt(2.0 ), 'norm_num_groups': None, 'down_block_types': [ 'SkipDownBlock2D', 'AttnSkipDownBlock2D', 'SkipDownBlock2D', 'SkipDownBlock2D', ], 'up_block_types': [ 'SkipUpBlock2D', 'SkipUpBlock2D', 'AttnSkipUpBlock2D', 'SkipUpBlock2D', ], } a__ = self.dummy_input return init_dict, inputs_dict @slow def lowerCamelCase__( self :str ) -> Tuple: a__ , a__ = UNetaDModel.from_pretrained('google/ncsnpp-celebahq-256' ,output_loading_info=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertEqual(len(loading_info['missing_keys'] ) ,0 ) model.to(__snake_case ) a__ = self.dummy_input a__ = floats_tensor((4, 3) + (2_56, 2_56) ).to(__snake_case ) a__ = noise a__ = model(**__snake_case ) assert image is not None, "Make sure output is not None" @slow def lowerCamelCase__( self :Union[str, Any] ) -> Dict: a__ = UNetaDModel.from_pretrained('google/ncsnpp-celebahq-256' ) model.to(__snake_case ) a__ = 4 a__ = 3 a__ = (2_56, 2_56) a__ = torch.ones((batch_size, num_channels) + sizes ).to(__snake_case ) a__ = torch.tensor(batch_size * [1E-4] ).to(__snake_case ) with torch.no_grad(): a__ = model(__snake_case ,__snake_case ).sample a__ = output[0, -3:, -3:, -1].flatten().cpu() # fmt: off a__ = torch.tensor([-48_42.86_91, -64_99.66_31, -38_00.19_53, -79_78.26_86, -1_09_80.71_29, -2_00_28.85_35, 81_48.28_22, 23_42.29_05, 5_67.76_08] ) # fmt: on self.assertTrue(torch_all_close(__snake_case ,__snake_case ,rtol=1E-2 ) ) def lowerCamelCase__( self :Dict ) -> int: a__ = UNetaDModel.from_pretrained('fusing/ncsnpp-ffhq-ve-dummy-update' ) model.to(__snake_case ) a__ = 4 a__ = 3 a__ = (32, 32) a__ = torch.ones((batch_size, num_channels) + sizes ).to(__snake_case ) a__ = torch.tensor(batch_size * [1E-4] ).to(__snake_case ) with torch.no_grad(): a__ = model(__snake_case ,__snake_case ).sample a__ = output[0, -3:, -3:, -1].flatten().cpu() # fmt: off a__ = torch.tensor([-0.03_25, -0.09_00, -0.08_69, -0.03_32, -0.07_25, -0.02_70, -0.01_01, 0.02_27, 0.02_56] ) # fmt: on self.assertTrue(torch_all_close(__snake_case ,__snake_case ,rtol=1E-2 ) ) def lowerCamelCase__( self :int ) -> str: # not required for this model pass
109
0
'''simple docstring''' def _A ( _lowerCAmelCase , _lowerCAmelCase = False ): """simple docstring""" if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): __lowercase =f"""Expected string as input, found {type(UpperCAmelCase_ )}""" raise ValueError(UpperCAmelCase_ ) if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): __lowercase =f"""Expected boolean as use_pascal parameter, found {type(UpperCAmelCase_ )}""" raise ValueError(UpperCAmelCase_ ) __lowercase =input_str.split('_' ) __lowercase =0 if use_pascal else 1 __lowercase =words[start_index:] __lowercase =[word[0].upper() + word[1:] for word in words_to_capitalize] __lowercase ='' if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
166
"""simple docstring""" import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase : def __init__(self : Optional[Any] , _A : Optional[Any] , _A : str=13 , _A : List[Any]=3 , _A : Tuple=True , _A : List[str]=True , _A : Any=0.1 , _A : str=0.1 , _A : Union[str, Any]=2_24 , _A : Dict=10_00 , _A : Optional[int]=[3, 3, 6, 4] , _A : Optional[Any]=[48, 56, 1_12, 2_20] , ) -> List[str]: __snake_case : int = parent __snake_case : str = batch_size __snake_case : int = num_channels __snake_case : Optional[Any] = is_training __snake_case : Tuple = use_labels __snake_case : Optional[Any] = hidden_dropout_prob __snake_case : Optional[int] = attention_probs_dropout_prob __snake_case : Dict = num_labels __snake_case : Union[str, Any] = image_size __snake_case : int = layer_depths __snake_case : List[str] = embed_dims def _lowercase (self : List[Any]) -> Dict: __snake_case : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __snake_case : int = None if self.use_labels: __snake_case : Tuple = ids_tensor([self.batch_size] , self.num_labels) __snake_case : Optional[int] = self.get_config() return config, pixel_values, labels def _lowercase (self : Union[str, Any]) -> List[Any]: return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act='gelu' , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=_A , layer_scale_init_value=1E-5 , ) def _lowercase (self : int , _A : Union[str, Any] , _A : Tuple , _A : List[str]) -> Optional[int]: __snake_case : str = SwiftFormerModel(config=_A) model.to(_A) model.eval() __snake_case : Union[str, Any] = model(_A) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7)) def _lowercase (self : Optional[int] , _A : List[str] , _A : Union[str, Any] , _A : Union[str, Any]) -> int: __snake_case : Optional[int] = self.num_labels __snake_case : Dict = SwiftFormerForImageClassification(_A) model.to(_A) model.eval() __snake_case : List[Any] = model(_A , labels=_A) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) __snake_case : List[str] = SwiftFormerForImageClassification(_A) model.to(_A) model.eval() __snake_case : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __snake_case : Union[str, Any] = model(_A) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _lowercase (self : Optional[int]) -> int: ((__snake_case) , (__snake_case) , (__snake_case)) : List[Any] = self.prepare_config_and_inputs() __snake_case : str = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCamelCase ( lowercase , lowercase , unittest.TestCase ): UpperCAmelCase : Union[str, Any] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () UpperCAmelCase : Union[str, Any] = ( {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification} if is_torch_available() else {} ) UpperCAmelCase : Any = False UpperCAmelCase : Any = False UpperCAmelCase : Tuple = False UpperCAmelCase : Tuple = False UpperCAmelCase : Tuple = False def _lowercase (self : int) -> Optional[int]: __snake_case : Dict = SwiftFormerModelTester(self) __snake_case : List[Any] = ConfigTester( self , config_class=_A , has_text_modality=_A , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def _lowercase (self : Dict) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason='SwiftFormer does not use inputs_embeds') def _lowercase (self : Optional[int]) -> Optional[int]: pass def _lowercase (self : Dict) -> Optional[int]: __snake_case , __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : str = model_class(_A) __snake_case : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_A , nn.Linear)) def _lowercase (self : str) -> Any: __snake_case , __snake_case : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : str = model_class(_A) __snake_case : str = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : int = [*signature.parameters.keys()] __snake_case : List[str] = ['pixel_values'] self.assertListEqual(arg_names[:1] , _A) def _lowercase (self : List[Any]) -> List[str]: __snake_case : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A) def _lowercase (self : Optional[int]) -> int: __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A) @slow def _lowercase (self : Union[str, Any]) -> Dict: for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Dict = SwiftFormerModel.from_pretrained(_A) self.assertIsNotNone(_A) @unittest.skip(reason='SwiftFormer does not output attentions') def _lowercase (self : Dict) -> int: pass def _lowercase (self : Union[str, Any]) -> List[Any]: def check_hidden_states_output(_A : str , _A : int , _A : str): __snake_case : Optional[int] = model_class(_A) model.to(_A) model.eval() with torch.no_grad(): __snake_case : Optional[int] = model(**self._prepare_for_class(_A , _A)) __snake_case : Optional[int] = outputs.hidden_states __snake_case : Any = 8 self.assertEqual(len(_A) , _A) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(_A)): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ]) , ) __snake_case , __snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Union[str, Any] = True check_hidden_states_output(_A , _A , _A) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : Any = True check_hidden_states_output(_A , _A , _A) def _lowercase (self : List[Any]) -> int: def _config_zero_init(_A : Union[str, Any]): __snake_case : Optional[int] = copy.deepcopy(_A) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(_A , _A , 1E-10) if isinstance(getattr(_A , _A , _A) , _A): __snake_case : Optional[int] = _config_zero_init(getattr(_A , _A)) setattr(_A , _A , _A) return configs_no_init __snake_case , __snake_case : Tuple = self.model_tester.prepare_config_and_inputs_for_common() __snake_case : int = _config_zero_init(_A) for model_class in self.all_model_classes: __snake_case : Tuple = model_class(config=_A) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().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 : List[str]) -> List[Any]: pass def __UpperCAmelCase ( ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class UpperCamelCase ( unittest.TestCase ): @cached_property def _lowercase (self : Dict) -> List[str]: return ViTImageProcessor.from_pretrained('MBZUAI/swiftformer-xs') if is_vision_available() else None @slow def _lowercase (self : Any) -> List[Any]: __snake_case : Any = SwiftFormerForImageClassification.from_pretrained('MBZUAI/swiftformer-xs').to(_A) __snake_case : Any = self.default_image_processor __snake_case : Optional[int] = prepare_img() __snake_case : Optional[int] = image_processor(images=_A , return_tensors='pt').to(_A) # forward pass with torch.no_grad(): __snake_case : Tuple = model(**_A) # verify the logits __snake_case : Optional[Any] = torch.Size((1, 10_00)) self.assertEqual(outputs.logits.shape , _A) __snake_case : Optional[int] = torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]]).to(_A) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1E-4))
172
0
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json', 'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json', 'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json', } class snake_case_ ( __lowercase ): A_ = 'owlvit_text_model' def __init__( self : Optional[Any] , _snake_case : List[Any]=49408 , _snake_case : Optional[int]=512 , _snake_case : Union[str, Any]=2048 , _snake_case : Any=12 , _snake_case : Union[str, Any]=8 , _snake_case : int=16 , _snake_case : Dict="quick_gelu" , _snake_case : Optional[int]=1E-5 , _snake_case : Any=0.0 , _snake_case : Dict=0.02 , _snake_case : Optional[Any]=1.0 , _snake_case : str=0 , _snake_case : str=49406 , _snake_case : Optional[int]=49407 , **_snake_case : Any , )->Optional[int]: '''simple docstring''' super().__init__(pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case ) __lowerCAmelCase : Union[str, Any] = vocab_size __lowerCAmelCase : Tuple = hidden_size __lowerCAmelCase : Optional[int] = intermediate_size __lowerCAmelCase : Optional[int] = num_hidden_layers __lowerCAmelCase : Tuple = num_attention_heads __lowerCAmelCase : Dict = max_position_embeddings __lowerCAmelCase : Optional[int] = hidden_act __lowerCAmelCase : List[Any] = layer_norm_eps __lowerCAmelCase : Dict = attention_dropout __lowerCAmelCase : Any = initializer_range __lowerCAmelCase : List[Any] = initializer_factor @classmethod def UpperCAmelCase__ ( cls : str , _snake_case : Union[str, os.PathLike] , **_snake_case : List[str] )->"PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_snake_case ) __lowerCAmelCase , __lowerCAmelCase : Dict = cls.get_config_dict(_snake_case , **_snake_case ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get("""model_type""" ) == "owlvit": __lowerCAmelCase : int = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_snake_case , **_snake_case ) class snake_case_ ( __lowercase ): A_ = 'owlvit_vision_model' def __init__( self : Optional[int] , _snake_case : List[Any]=768 , _snake_case : str=3072 , _snake_case : str=12 , _snake_case : List[str]=12 , _snake_case : int=3 , _snake_case : Optional[int]=768 , _snake_case : Dict=32 , _snake_case : Dict="quick_gelu" , _snake_case : List[str]=1E-5 , _snake_case : Any=0.0 , _snake_case : List[Any]=0.02 , _snake_case : Dict=1.0 , **_snake_case : Union[str, Any] , )->Optional[Any]: '''simple docstring''' super().__init__(**_snake_case ) __lowerCAmelCase : str = hidden_size __lowerCAmelCase : Any = intermediate_size __lowerCAmelCase : str = num_hidden_layers __lowerCAmelCase : int = num_attention_heads __lowerCAmelCase : Union[str, Any] = num_channels __lowerCAmelCase : Dict = image_size __lowerCAmelCase : int = patch_size __lowerCAmelCase : List[str] = hidden_act __lowerCAmelCase : List[str] = layer_norm_eps __lowerCAmelCase : Union[str, Any] = attention_dropout __lowerCAmelCase : Tuple = initializer_range __lowerCAmelCase : str = initializer_factor @classmethod def UpperCAmelCase__ ( cls : List[str] , _snake_case : Union[str, os.PathLike] , **_snake_case : Any )->"PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_snake_case ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = cls.get_config_dict(_snake_case , **_snake_case ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get("""model_type""" ) == "owlvit": __lowerCAmelCase : Tuple = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_snake_case , **_snake_case ) class snake_case_ ( __lowercase ): A_ = 'owlvit' A_ = True def __init__( self : Any , _snake_case : Any=None , _snake_case : int=None , _snake_case : Tuple=512 , _snake_case : Union[str, Any]=2.6_592 , _snake_case : Optional[Any]=True , **_snake_case : Union[str, Any] , )->Dict: '''simple docstring''' super().__init__(**_snake_case ) if text_config is None: __lowerCAmelCase : List[str] = {} logger.info("""text_config is None. Initializing the OwlViTTextConfig with default values.""" ) if vision_config is None: __lowerCAmelCase : int = {} logger.info("""vision_config is None. initializing the OwlViTVisionConfig with default values.""" ) __lowerCAmelCase : List[str] = OwlViTTextConfig(**_snake_case ) __lowerCAmelCase : Optional[Any] = OwlViTVisionConfig(**_snake_case ) __lowerCAmelCase : List[Any] = projection_dim __lowerCAmelCase : Any = logit_scale_init_value __lowerCAmelCase : str = return_dict __lowerCAmelCase : Union[str, Any] = 1.0 @classmethod def UpperCAmelCase__ ( cls : List[str] , _snake_case : Union[str, os.PathLike] , **_snake_case : Tuple )->"PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(_snake_case ) __lowerCAmelCase , __lowerCAmelCase : List[Any] = cls.get_config_dict(_snake_case , **_snake_case ) if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(_snake_case , **_snake_case ) @classmethod def UpperCAmelCase__ ( cls : Union[str, Any] , _snake_case : Dict , _snake_case : Dict , **_snake_case : Tuple )->Dict: '''simple docstring''' __lowerCAmelCase : Dict = {} __lowerCAmelCase : Union[str, Any] = text_config __lowerCAmelCase : int = vision_config return cls.from_dict(_snake_case , **_snake_case ) def UpperCAmelCase__ ( self : Any )->Dict: '''simple docstring''' __lowerCAmelCase : Optional[Any] = copy.deepcopy(self.__dict__ ) __lowerCAmelCase : Optional[int] = self.text_config.to_dict() __lowerCAmelCase : Tuple = self.vision_config.to_dict() __lowerCAmelCase : str = self.__class__.model_type return output class snake_case_ ( __lowercase ): @property def UpperCAmelCase__ ( self : List[str] )->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ] ) @property def UpperCAmelCase__ ( self : Any )->Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("""logits_per_image""", {0: """batch"""}), ("""logits_per_text""", {0: """batch"""}), ("""text_embeds""", {0: """batch"""}), ("""image_embeds""", {0: """batch"""}), ] ) @property def UpperCAmelCase__ ( self : Any )->float: '''simple docstring''' return 1E-4 def UpperCAmelCase__ ( self : List[Any] , _snake_case : "ProcessorMixin" , _snake_case : int = -1 , _snake_case : int = -1 , _snake_case : Optional["TensorType"] = None , )->Mapping[str, Any]: '''simple docstring''' __lowerCAmelCase : Tuple = super().generate_dummy_inputs( processor.tokenizer , batch_size=_snake_case , seq_length=_snake_case , framework=_snake_case ) __lowerCAmelCase : Optional[int] = super().generate_dummy_inputs( processor.image_processor , batch_size=_snake_case , framework=_snake_case ) return {**text_input_dict, **image_input_dict} @property def UpperCAmelCase__ ( self : Union[str, Any] )->int: '''simple docstring''' return 14
232
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case_ ( __lowercase ): A_ = ['image_processor', 'tokenizer'] A_ = 'ChineseCLIPImageProcessor' A_ = ('BertTokenizer', 'BertTokenizerFast') def __init__( self : Optional[Any] , _snake_case : List[Any]=None , _snake_case : str=None , **_snake_case : int )->List[str]: '''simple docstring''' __lowerCAmelCase : str = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , _snake_case , ) __lowerCAmelCase : List[str] = kwargs.pop("""feature_extractor""" ) __lowerCAmelCase : Union[str, Any] = 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__(_snake_case , _snake_case ) __lowerCAmelCase : Any = self.image_processor def __call__( self : Optional[Any] , _snake_case : Tuple=None , _snake_case : Tuple=None , _snake_case : List[str]=None , **_snake_case : Any )->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: __lowerCAmelCase : List[Any] = self.tokenizer(_snake_case , return_tensors=_snake_case , **_snake_case ) if images is not None: __lowerCAmelCase : Tuple = self.image_processor(_snake_case , return_tensors=_snake_case , **_snake_case ) if text is not None and images is not None: __lowerCAmelCase : Optional[Any] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_snake_case ) , tensor_type=_snake_case ) def UpperCAmelCase__ ( self : Optional[int] , *_snake_case : Union[str, Any] , **_snake_case : int )->Optional[Any]: '''simple docstring''' return self.tokenizer.batch_decode(*_snake_case , **_snake_case ) def UpperCAmelCase__ ( self : Dict , *_snake_case : Dict , **_snake_case : Any )->Dict: '''simple docstring''' return self.tokenizer.decode(*_snake_case , **_snake_case ) @property def UpperCAmelCase__ ( self : Optional[int] )->str: '''simple docstring''' __lowerCAmelCase : Tuple = self.tokenizer.model_input_names __lowerCAmelCase : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def UpperCAmelCase__ ( self : Dict )->Union[str, Any]: '''simple docstring''' warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , _snake_case , ) return self.image_processor_class
232
1
'''simple docstring''' import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class _lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def lowercase (self ) -> Any: _snake_case = """ZinengTang/tvlt-base""" _snake_case = tempfile.mkdtemp() def lowercase (self , **UpperCAmelCase ) -> str: return TvltImageProcessor.from_pretrained(self.checkpoint , **UpperCAmelCase ) def lowercase (self , **UpperCAmelCase ) -> List[Any]: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **UpperCAmelCase ) def lowercase (self ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def lowercase (self ) -> Any: _snake_case = self.get_image_processor() _snake_case = self.get_feature_extractor() _snake_case = TvltProcessor(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) _snake_case = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase ) self.assertIsInstance(processor.image_processor , UpperCAmelCase ) def lowercase (self ) -> str: _snake_case = self.get_image_processor() _snake_case = self.get_feature_extractor() _snake_case = TvltProcessor(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) _snake_case = np.ones([12000] ) _snake_case = feature_extractor(UpperCAmelCase , return_tensors="""np""" ) _snake_case = processor(audio=UpperCAmelCase , return_tensors="""np""" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowercase (self ) -> int: _snake_case = self.get_image_processor() _snake_case = self.get_feature_extractor() _snake_case = TvltProcessor(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) _snake_case = np.ones([3, 224, 224] ) _snake_case = image_processor(UpperCAmelCase , return_tensors="""np""" ) _snake_case = processor(images=UpperCAmelCase , return_tensors="""np""" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowercase (self ) -> Union[str, Any]: _snake_case = self.get_image_processor() _snake_case = self.get_feature_extractor() _snake_case = TvltProcessor(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) _snake_case = np.ones([12000] ) _snake_case = np.ones([3, 224, 224] ) _snake_case = processor(audio=UpperCAmelCase , images=UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ["""audio_values""", """audio_mask""", """pixel_values""", """pixel_mask"""] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase ): processor() def lowercase (self ) -> str: _snake_case = self.get_image_processor() _snake_case = self.get_feature_extractor() _snake_case = TvltProcessor(image_processor=UpperCAmelCase , feature_extractor=UpperCAmelCase ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="""`processor` and `image_processor`+`feature_extractor` model input names do not match""" , )
341
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput __lowerCAmelCase = 8 def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=BITS ): _snake_case = x.device _snake_case = (x * 255).int().clamp(0 , 255 ) _snake_case = 2 ** torch.arange(bits - 1 , -1 , -1 , device=_SCREAMING_SNAKE_CASE ) _snake_case = rearrange(_SCREAMING_SNAKE_CASE , """d -> d 1 1""" ) _snake_case = rearrange(_SCREAMING_SNAKE_CASE , """b c h w -> b c 1 h w""" ) _snake_case = ((x & mask) != 0).float() _snake_case = rearrange(_SCREAMING_SNAKE_CASE , """b c d h w -> b (c d) h w""" ) _snake_case = bits * 2 - 1 return bits def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=BITS ): _snake_case = x.device _snake_case = (x > 0).int() _snake_case = 2 ** torch.arange(bits - 1 , -1 , -1 , device=_SCREAMING_SNAKE_CASE , dtype=torch.intaa ) _snake_case = rearrange(_SCREAMING_SNAKE_CASE , """d -> d 1 1""" ) _snake_case = rearrange(_SCREAMING_SNAKE_CASE , """b (c d) h w -> b c d h w""" , d=8 ) _snake_case = reduce(x * mask , """b c d h w -> b c h w""" , """sum""" ) return (dec / 255).clamp(0.0 , 1.0 ) def __SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE = True , ): if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) _snake_case = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas _snake_case = self.alphas_cumprod[timestep] _snake_case = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod _snake_case = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _snake_case = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" _snake_case = self.bit_scale if self.config.clip_sample: _snake_case = torch.clamp(_SCREAMING_SNAKE_CASE , -scale , _SCREAMING_SNAKE_CASE ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) _snake_case = self._get_variance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _snake_case = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide _snake_case = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _snake_case = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _snake_case = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 _snake_case = model_output.device if torch.is_tensor(_SCREAMING_SNAKE_CASE ) else """cpu""" _snake_case = torch.randn(model_output.shape , dtype=model_output.dtype , generator=_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) _snake_case = self._get_variance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ** 0.5 * eta * noise _snake_case = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=_SCREAMING_SNAKE_CASE , pred_original_sample=_SCREAMING_SNAKE_CASE ) def __SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="epsilon" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE = True , ): _snake_case = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: _snake_case, _snake_case = torch.split(_SCREAMING_SNAKE_CASE , sample.shape[1] , dim=1 ) else: _snake_case = None # 1. compute alphas, betas _snake_case = self.alphas_cumprod[t] _snake_case = self.alphas_cumprod[t - 1] if t > 0 else self.one _snake_case = 1 - alpha_prod_t _snake_case = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": _snake_case = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": _snake_case = model_output else: raise ValueError(f"""Unsupported prediction_type {prediction_type}.""" ) # 3. Clip "predicted x_0" _snake_case = self.bit_scale if self.config.clip_sample: _snake_case = torch.clamp(_SCREAMING_SNAKE_CASE , -scale , _SCREAMING_SNAKE_CASE ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _snake_case = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t _snake_case = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _snake_case = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _snake_case = 0 if t > 0: _snake_case = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=_SCREAMING_SNAKE_CASE ).to(model_output.device ) _snake_case = (self._get_variance(_SCREAMING_SNAKE_CASE , predicted_variance=_SCREAMING_SNAKE_CASE ) ** 0.5) * noise _snake_case = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=_SCREAMING_SNAKE_CASE , pred_original_sample=_SCREAMING_SNAKE_CASE ) class _lowerCAmelCase ( __snake_case ): '''simple docstring''' def __init__(self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 1.0 , ) -> Tuple: super().__init__() _snake_case = bit_scale _snake_case = ( ddim_bit_scheduler_step if isinstance(UpperCAmelCase , UpperCAmelCase ) else ddpm_bit_scheduler_step ) self.register_modules(unet=UpperCAmelCase , scheduler=UpperCAmelCase ) @torch.no_grad() def __call__(self , UpperCAmelCase = 256 , UpperCAmelCase = 256 , UpperCAmelCase = 50 , UpperCAmelCase = None , UpperCAmelCase = 1 , UpperCAmelCase = "pil" , UpperCAmelCase = True , **UpperCAmelCase , ) -> Union[Tuple, ImagePipelineOutput]: _snake_case = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=UpperCAmelCase , ) _snake_case = decimal_to_bits(UpperCAmelCase ) * self.bit_scale _snake_case = latents.to(self.device ) self.scheduler.set_timesteps(UpperCAmelCase ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual _snake_case = self.unet(UpperCAmelCase , UpperCAmelCase ).sample # compute the previous noisy sample x_t -> x_t-1 _snake_case = self.scheduler.step(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ).prev_sample _snake_case = bits_to_decimal(UpperCAmelCase ) if output_type == "pil": _snake_case = self.numpy_to_pil(UpperCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase )
341
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __lowerCAmelCase : Tuple ={"""configuration_fnet""": ["""FNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : int =["""FNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : int =["""FNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Optional[int] =[ """FNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """FNetForMaskedLM""", """FNetForMultipleChoice""", """FNetForNextSentencePrediction""", """FNetForPreTraining""", """FNetForQuestionAnswering""", """FNetForSequenceClassification""", """FNetForTokenClassification""", """FNetLayer""", """FNetModel""", """FNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys __lowerCAmelCase : int =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
367
"""simple docstring""" from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake __lowerCAmelCase : List[Any] =numpy.array([0, 0]) __lowerCAmelCase : List[str] =numpy.array([0.5, 0.866_0254]) __lowerCAmelCase : List[Any] =numpy.array([1, 0]) __lowerCAmelCase : int =[VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def UpperCAmelCase__ ( lowerCAmelCase__ :list[numpy.ndarray] , lowerCAmelCase__ :int ) -> list[numpy.ndarray]: '''simple docstring''' lowercase = initial_vectors for _ in range(lowerCAmelCase__ ): lowercase = iteration_step(lowerCAmelCase__ ) return vectors def UpperCAmelCase__ ( lowerCAmelCase__ :list[numpy.ndarray] ) -> list[numpy.ndarray]: '''simple docstring''' lowercase = [] for i, start_vector in enumerate(vectors[:-1] ): lowercase = vectors[i + 1] new_vectors.append(lowerCAmelCase__ ) lowercase = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3 ) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 6_0 ) ) new_vectors.append(start_vector + difference_vector * 2 / 3 ) new_vectors.append(vectors[-1] ) return new_vectors def UpperCAmelCase__ ( lowerCAmelCase__ :numpy.ndarray , lowerCAmelCase__ :float ) -> numpy.ndarray: '''simple docstring''' lowercase = numpy.radians(lowerCAmelCase__ ) lowercase , lowercase = numpy.cos(lowerCAmelCase__ ), numpy.sin(lowerCAmelCase__ ) lowercase = numpy.array(((c, -s), (s, c)) ) return numpy.dot(lowerCAmelCase__ , lowerCAmelCase__ ) def UpperCAmelCase__ ( lowerCAmelCase__ :list[numpy.ndarray] ) -> None: '''simple docstring''' lowercase = plt.gca() axes.set_aspect("""equal""" ) # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() lowercase , lowercase = zip(*lowerCAmelCase__ ) plt.plot(lowerCAmelCase__ , lowerCAmelCase__ ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() __lowerCAmelCase : Optional[int] =iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
32
0
import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class _lowercase ( unittest.TestCase): """simple docstring""" def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' lowerCamelCase__ : str = { "task_specific_params": { "summarization": {"length_penalty": 1.0, "max_length": 128, "min_length": 12, "num_beams": 4}, "summarization_cnn": {"length_penalty": 2.0, "max_length": 142, "min_length": 56, "num_beams": 4}, "summarization_xsum": {"length_penalty": 1.0, "max_length": 62, "min_length": 11, "num_beams": 6}, } } lowerCamelCase__ : int = { "task_specific_params.summarization.length_penalty": 1.0, "task_specific_params.summarization.max_length": 128, "task_specific_params.summarization.min_length": 12, "task_specific_params.summarization.num_beams": 4, "task_specific_params.summarization_cnn.length_penalty": 2.0, "task_specific_params.summarization_cnn.max_length": 142, "task_specific_params.summarization_cnn.min_length": 56, "task_specific_params.summarization_cnn.num_beams": 4, "task_specific_params.summarization_xsum.length_penalty": 1.0, "task_specific_params.summarization_xsum.max_length": 62, "task_specific_params.summarization_xsum.min_length": 11, "task_specific_params.summarization_xsum.num_beams": 6, } self.assertEqual(flatten_dict(__lowerCamelCase ) , __lowerCamelCase ) def lowerCAmelCase ( self : Tuple ): '''simple docstring''' lowerCamelCase__ : Dict = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(__lowerCamelCase ) , x.transpose() ) ) lowerCamelCase__ : List[str] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(__lowerCamelCase , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def lowerCAmelCase ( self : str ): '''simple docstring''' lowerCamelCase__ : Optional[Any] = np.random.randn(3 , 4 ) lowerCamelCase__ : List[Any] = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase ) , transpose(__lowerCamelCase ).numpy() ) ) lowerCamelCase__ : Any = np.random.randn(3 , 4 , 5 ) lowerCamelCase__ : List[str] = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase , axes=(1, 2, 0) ) , transpose(__lowerCamelCase , axes=(1, 2, 0) ).numpy() ) ) @require_tf def lowerCAmelCase ( self : Tuple ): '''simple docstring''' lowerCamelCase__ : List[str] = np.random.randn(3 , 4 ) lowerCamelCase__ : Optional[int] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase ) , transpose(__lowerCamelCase ).numpy() ) ) lowerCamelCase__ : Optional[Any] = np.random.randn(3 , 4 , 5 ) lowerCamelCase__ : Optional[int] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase , axes=(1, 2, 0) ) , transpose(__lowerCamelCase , axes=(1, 2, 0) ).numpy() ) ) @require_flax def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' lowerCamelCase__ : Optional[int] = np.random.randn(3 , 4 ) lowerCamelCase__ : Optional[Any] = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase ) , np.asarray(transpose(__lowerCamelCase ) ) ) ) lowerCamelCase__ : int = np.random.randn(3 , 4 , 5 ) lowerCamelCase__ : str = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(transpose(__lowerCamelCase , axes=(1, 2, 0) ) , np.asarray(transpose(__lowerCamelCase , axes=(1, 2, 0) ) ) ) ) def lowerCAmelCase ( self : Tuple ): '''simple docstring''' lowerCamelCase__ : str = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (4, 3) ) , np.reshape(__lowerCamelCase , (4, 3) ) ) ) lowerCamelCase__ : int = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (12, 5) ) , np.reshape(__lowerCamelCase , (12, 5) ) ) ) @require_torch def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' lowerCamelCase__ : Dict = np.random.randn(3 , 4 ) lowerCamelCase__ : Tuple = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (4, 3) ) , reshape(__lowerCamelCase , (4, 3) ).numpy() ) ) lowerCamelCase__ : Optional[int] = np.random.randn(3 , 4 , 5 ) lowerCamelCase__ : Tuple = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (12, 5) ) , reshape(__lowerCamelCase , (12, 5) ).numpy() ) ) @require_tf def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' lowerCamelCase__ : Union[str, Any] = np.random.randn(3 , 4 ) lowerCamelCase__ : List[Any] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (4, 3) ) , reshape(__lowerCamelCase , (4, 3) ).numpy() ) ) lowerCamelCase__ : int = np.random.randn(3 , 4 , 5 ) lowerCamelCase__ : List[str] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (12, 5) ) , reshape(__lowerCamelCase , (12, 5) ).numpy() ) ) @require_flax def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' lowerCamelCase__ : Tuple = np.random.randn(3 , 4 ) lowerCamelCase__ : List[str] = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (4, 3) ) , np.asarray(reshape(__lowerCamelCase , (4, 3) ) ) ) ) lowerCamelCase__ : Union[str, Any] = np.random.randn(3 , 4 , 5 ) lowerCamelCase__ : Tuple = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(reshape(__lowerCamelCase , (12, 5) ) , np.asarray(reshape(__lowerCamelCase , (12, 5) ) ) ) ) def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' lowerCamelCase__ : int = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase ) , np.squeeze(__lowerCamelCase ) ) ) lowerCamelCase__ : List[str] = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase , axis=2 ) , np.squeeze(__lowerCamelCase , axis=2 ) ) ) @require_torch def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' lowerCamelCase__ : Optional[Any] = np.random.randn(1 , 3 , 4 ) lowerCamelCase__ : str = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase ) , squeeze(__lowerCamelCase ).numpy() ) ) lowerCamelCase__ : Tuple = np.random.randn(1 , 4 , 1 , 5 ) lowerCamelCase__ : List[Any] = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase , axis=2 ) , squeeze(__lowerCamelCase , axis=2 ).numpy() ) ) @require_tf def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' lowerCamelCase__ : str = np.random.randn(1 , 3 , 4 ) lowerCamelCase__ : List[Any] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase ) , squeeze(__lowerCamelCase ).numpy() ) ) lowerCamelCase__ : Dict = np.random.randn(1 , 4 , 1 , 5 ) lowerCamelCase__ : str = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase , axis=2 ) , squeeze(__lowerCamelCase , axis=2 ).numpy() ) ) @require_flax def lowerCAmelCase ( self : List[str] ): '''simple docstring''' lowerCamelCase__ : Any = np.random.randn(1 , 3 , 4 ) lowerCamelCase__ : str = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase ) , np.asarray(squeeze(__lowerCamelCase ) ) ) ) lowerCamelCase__ : Dict = np.random.randn(1 , 4 , 1 , 5 ) lowerCamelCase__ : Tuple = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(squeeze(__lowerCamelCase , axis=2 ) , np.asarray(squeeze(__lowerCamelCase , axis=2 ) ) ) ) def lowerCAmelCase ( self : Dict ): '''simple docstring''' lowerCamelCase__ : int = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(__lowerCamelCase , axis=1 ) , np.expand_dims(__lowerCamelCase , axis=1 ) ) ) @require_torch def lowerCAmelCase ( self : Dict ): '''simple docstring''' lowerCamelCase__ : int = np.random.randn(3 , 4 ) lowerCamelCase__ : Union[str, Any] = torch.tensor(__lowerCamelCase ) self.assertTrue(np.allclose(expand_dims(__lowerCamelCase , axis=1 ) , expand_dims(__lowerCamelCase , axis=1 ).numpy() ) ) @require_tf def lowerCAmelCase ( self : Dict ): '''simple docstring''' lowerCamelCase__ : List[Any] = np.random.randn(3 , 4 ) lowerCamelCase__ : List[Any] = tf.constant(__lowerCamelCase ) self.assertTrue(np.allclose(expand_dims(__lowerCamelCase , axis=1 ) , expand_dims(__lowerCamelCase , axis=1 ).numpy() ) ) @require_flax def lowerCAmelCase ( self : Any ): '''simple docstring''' lowerCamelCase__ : Dict = np.random.randn(3 , 4 ) lowerCamelCase__ : Any = jnp.array(__lowerCamelCase ) self.assertTrue(np.allclose(expand_dims(__lowerCamelCase , axis=1 ) , np.asarray(expand_dims(__lowerCamelCase , axis=1 ) ) ) )
184
from __future__ import annotations A : Union[str, Any] = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class _lowercase : """simple docstring""" def __init__( self : Tuple , __lowerCamelCase : dict[str, list[str]] , __lowerCamelCase : str ): '''simple docstring''' lowerCamelCase__ : Union[str, Any] = graph # mapping node to its parent in resulting breadth first tree lowerCamelCase__ : dict[str, str | None] = {} lowerCamelCase__ : Dict = source_vertex def lowerCAmelCase ( self : Any ): '''simple docstring''' lowerCamelCase__ : int = {self.source_vertex} lowerCamelCase__ : Optional[int] = None lowerCamelCase__ : Dict = [self.source_vertex] # first in first out queue while queue: lowerCamelCase__ : Optional[int] = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__lowerCamelCase ) lowerCamelCase__ : List[str] = vertex queue.append(__lowerCamelCase ) def lowerCAmelCase ( self : Optional[Any] , __lowerCamelCase : str ): '''simple docstring''' if target_vertex == self.source_vertex: return self.source_vertex lowerCamelCase__ : Tuple = self.parent.get(__lowerCamelCase ) if target_vertex_parent is None: lowerCamelCase__ : Tuple = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__lowerCamelCase ) return self.shortest_path(__lowerCamelCase ) + f"->{target_vertex}" if __name__ == "__main__": A : List[str] = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D")) print(g.shortest_path("G")) print(g.shortest_path("Foo"))
184
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _snake_case = { "configuration_blenderbot_small": [ "BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotSmallConfig", "BlenderbotSmallOnnxConfig", ], "tokenization_blenderbot_small": ["BlenderbotSmallTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ["BlenderbotSmallTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotSmallForCausalLM", "BlenderbotSmallForConditionalGeneration", "BlenderbotSmallModel", "BlenderbotSmallPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "TFBlenderbotSmallForConditionalGeneration", "TFBlenderbotSmallModel", "TFBlenderbotSmallPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ "FlaxBlenderbotSmallForConditionalGeneration", "FlaxBlenderbotSmallModel", "FlaxBlenderbotSmallPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallOnnxConfig, ) from .tokenization_blenderbot_small import BlenderbotSmallTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) else: import sys _snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
366
from __future__ import annotations from typing import Any class UpperCAmelCase_ : def __init__( self, __a, __a, __a = 0): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase : int = row, column _lowerCAmelCase : str = [[default_value for c in range(__a)] for r in range(__a)] def __str__( self): '''simple docstring''' _lowerCAmelCase : Tuple = f"Matrix consist of {self.row} rows and {self.column} columns\n" # Make string identifier _lowerCAmelCase : str = 0 for row_vector in self.array: for obj in row_vector: _lowerCAmelCase : List[str] = max(__a, len(str(__a))) _lowerCAmelCase : Union[str, Any] = f"%{max_element_length}s" # Make string and return def single_line(__a) -> str: nonlocal string_format_identifier _lowerCAmelCase : Dict = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(__a) for row_vector in self.array) return s def __repr__( self): '''simple docstring''' return str(self) def snake_case__ ( self, __a): '''simple docstring''' if not (isinstance(__a, (list, tuple)) and len(__a) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self, __a): '''simple docstring''' assert self.validate_indicies(__a) return self.array[loc[0]][loc[1]] def __setitem__( self, __a, __a): '''simple docstring''' assert self.validate_indicies(__a) _lowerCAmelCase : Union[str, Any] = value def __add__( self, __a): '''simple docstring''' assert isinstance(__a, __a) assert self.row == another.row and self.column == another.column # Add _lowerCAmelCase : Any = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): _lowerCAmelCase : Any = self[r, c] + another[r, c] return result def __neg__( self): '''simple docstring''' _lowerCAmelCase : List[str] = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): _lowerCAmelCase : str = -self[r, c] return result def __sub__( self, __a): '''simple docstring''' return self + (-another) def __mul__( self, __a): '''simple docstring''' if isinstance(__a, (int, float)): # Scalar multiplication _lowerCAmelCase : Dict = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): _lowerCAmelCase : Optional[Any] = self[r, c] * another return result elif isinstance(__a, __a): # Matrix multiplication assert self.column == another.row _lowerCAmelCase : List[str] = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: _lowerCAmelCase : Optional[Any] = f"Unsupported type given for another ({type(__a)})" raise TypeError(__a) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Optional[Any] = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): _lowerCAmelCase : Any = self[r, c] return result def snake_case__ ( self, __a, __a): '''simple docstring''' assert isinstance(__a, __a) and isinstance(__a, __a) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate _lowerCAmelCase : int = v.transpose() _lowerCAmelCase : str = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def A ( ): '''simple docstring''' _lowerCAmelCase : List[Any] = Matrix(3 , 3 , 0 ) for i in range(3 ): _lowerCAmelCase : Union[str, Any] = 1 print(F"a^(-1) is {ainv}" ) # u, v _lowerCAmelCase : Any = Matrix(3 , 1 , 0 ) _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : Optional[int] = 1, 2, -3 _lowerCAmelCase : List[Any] = Matrix(3 , 1 , 0 ) _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : str = 4, -2, 5 print(F"u is {u}" ) print(F"v is {v}" ) print(F"uv^T is {u * v.transpose()}" ) # Sherman Morrison print(F"(a + uv^T)^(-1) is {ainv.sherman_morrison(_lowerCamelCase , _lowerCamelCase )}" ) def A ( ): '''simple docstring''' import doctest doctest.testmod() testa()
300
0
'''simple docstring''' def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): if b == 0: return 1 if (b % 2) == 0: return actual_power(_SCREAMING_SNAKE_CASE , int(b / 2 ) ) * actual_power(_SCREAMING_SNAKE_CASE , int(b / 2 ) ) else: return a * actual_power(_SCREAMING_SNAKE_CASE , int(b / 2 ) ) * actual_power(_SCREAMING_SNAKE_CASE , int(b / 2 ) ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): if b < 0: return 1 / actual_power(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return actual_power(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(power(-2, -3))
27
'''simple docstring''' 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 __UpperCamelCase ( lowerCAmelCase_ ): def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__a , 'embed_dim' ) ) self.parent.assertTrue(hasattr(__a , 'num_heads' ) ) class __UpperCamelCase : def __init__( self , __a , __a=13 , __a=64 , __a=3 , __a=[16, 48, 96] , __a=[1, 3, 6] , __a=[1, 2, 10] , __a=[7, 3, 3] , __a=[4, 2, 2] , __a=[2, 1, 1] , __a=[2, 2, 2] , __a=[False, False, True] , __a=[0.0, 0.0, 0.0] , __a=0.02 , __a=1E-1_2 , __a=True , __a=True , __a=2 , ): '''simple docstring''' __a : str = parent __a : List[Any] = batch_size __a : Optional[int] = image_size __a : List[str] = patch_sizes __a : str = patch_stride __a : Any = patch_padding __a : Dict = is_training __a : Union[str, Any] = use_labels __a : Dict = num_labels __a : List[Any] = num_channels __a : Any = embed_dim __a : int = num_heads __a : Optional[int] = stride_kv __a : Dict = depth __a : List[str] = cls_token __a : List[Any] = attention_drop_rate __a : Tuple = initializer_range __a : int = layer_norm_eps def __UpperCAmelCase ( self ): '''simple docstring''' __a : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a : Dict = None if self.use_labels: # create a random int32 tensor of given shape __a : str = ids_tensor([self.batch_size] , self.num_labels ) __a : str = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ): '''simple docstring''' 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 , __a , __a , __a ): '''simple docstring''' __a : Optional[int] = TFCvtModel(config=__a ) __a : Dict = model(__a , training=__a ) __a : Any = (self.image_size, self.image_size) __a , __a : Dict = image_size[0], image_size[1] for i in range(len(self.depth ) ): __a : Tuple = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) __a : str = 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 , __a , __a , __a ): '''simple docstring''' __a : List[Any] = self.num_labels __a : Optional[int] = TFCvtForImageClassification(__a ) __a : Dict = model(__a , labels=__a , training=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[Any] = self.prepare_config_and_inputs() __a , __a , __a : Tuple = config_and_inputs __a : str = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class __UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): A_ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () A_ = ( {"feature-extraction": TFCvtModel, "image-classification": TFCvtForImageClassification} if is_tf_available() else {} ) A_ = False A_ = False A_ = False A_ = False A_ = False def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCvtModelTester(self ) __a : List[Any] = TFCvtConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def __UpperCAmelCase ( self ): '''simple docstring''' 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 ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not use inputs_embeds' ) def __UpperCAmelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='Cvt does not support input and output embeddings' ) def __UpperCAmelCase ( self ): '''simple docstring''' 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 ): '''simple docstring''' 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 ): '''simple docstring''' 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 ): '''simple docstring''' __a : Any = tf.keras.mixed_precision.Policy('mixed_float16' ) tf.keras.mixed_precision.set_global_policy(__a ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy('float32' ) def __UpperCAmelCase ( self ): '''simple docstring''' __a , __a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : Dict = model_class(__a ) __a : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a : Optional[Any] = [*signature.parameters.keys()] __a : Optional[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' def check_hidden_states_output(__a , __a , __a ): __a : List[str] = model_class(__a ) __a : Union[str, Any] = model(**self._prepare_for_class(__a , __a ) ) __a : Any = outputs.hidden_states __a : Union[str, Any] = len(self.model_tester.depth ) self.assertEqual(len(__a ) , __a ) # 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, ] , ) __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a : List[str] = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a : Optional[Any] = True check_hidden_states_output(__a , __a , __a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Optional[Any] = TFCvtModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCamelCase (): __a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class __UpperCamelCase ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ): '''simple docstring''' return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __a : Tuple = self.default_image_processor __a : Any = prepare_img() __a : int = image_processor(images=__a , return_tensors='tf' ) # forward pass __a : Any = model(**__a ) # verify the logits __a : Any = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __a : Optional[Any] = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __a , atol=1E-4 ) )
27
1
import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class lowercase_ : @staticmethod def UpperCamelCase_ ( *A__ : Union[str, Any] , **A__ : List[str] ) -> Dict: pass def snake_case_(_UpperCamelCase ) -> str: """simple docstring""" _snake_case = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class lowercase_ ( unittest.TestCase ): UpperCamelCase_ : Any = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def UpperCamelCase_ ( self : Any , A__ : Union[str, Any] , A__ : Optional[Any] , A__ : Tuple ) -> Dict: _snake_case = DepthEstimationPipeline(model=A__ , image_processor=A__ ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCamelCase_ ( self : int , A__ : Any , A__ : Any ) -> Tuple: _snake_case = depth_estimator('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) self.assertEqual({'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )} , A__ ) import datasets _snake_case = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) _snake_case = depth_estimator( [ Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ] ) self.assertEqual( [ {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, ] , A__ , ) @require_tf @unittest.skip('''Depth estimation is not implemented in TF''' ) def UpperCamelCase_ ( self : int ) -> List[Any]: pass @slow @require_torch def UpperCamelCase_ ( self : Optional[int] ) -> Dict: _snake_case = '''Intel/dpt-large''' _snake_case = pipeline('''depth-estimation''' , model=A__ ) _snake_case = depth_estimator('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) _snake_case = hashimage(outputs['''depth'''] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['''predicted_depth'''].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs['''predicted_depth'''].min().item() ) , 2.662 ) @require_torch def UpperCamelCase_ ( self : Dict ) -> List[Any]: # This is highly irregular to have no small tests. self.skipTest('''There is not hf-internal-testing tiny model for either GLPN nor DPT''' )
278
__A = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/''' def snake_case_(_UpperCamelCase ) -> bytes: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): _snake_case = F"""a bytes-like object is required, not '{data.__class__.__name__}'""" raise TypeError(_UpperCamelCase ) _snake_case = ''''''.join(bin(_UpperCamelCase )[2:].zfill(8 ) for byte in data ) _snake_case = len(_UpperCamelCase ) % 6 != 0 if padding_needed: # The padding that will be added later _snake_case = b'''=''' * ((6 - len(_UpperCamelCase ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_UpperCamelCase ) % 6) else: _snake_case = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(_UpperCamelCase ) , 6 ) ).encode() + padding ) def snake_case_(_UpperCamelCase ) -> bytes: """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ) and not isinstance(_UpperCamelCase , _UpperCamelCase ): _snake_case = ( '''argument should be a bytes-like object or ASCII string, ''' F"""not '{encoded_data.__class__.__name__}'""" ) raise TypeError(_UpperCamelCase ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_UpperCamelCase , _UpperCamelCase ): try: _snake_case = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) _snake_case = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_UpperCamelCase ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one _snake_case = encoded_data[:-padding] _snake_case = ''''''.join( bin(B64_CHARSET.index(_UpperCamelCase ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: _snake_case = ''''''.join( bin(B64_CHARSET.index(_UpperCamelCase ) )[2:].zfill(6 ) for char in encoded_data ) _snake_case = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(_UpperCamelCase ) , 8 ) ] return bytes(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
278
1
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType lowerCAmelCase = logging.get_logger(__name__) lowerCAmelCase = { '''microsoft/layoutlmv3-base''': '''https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json''', } class A_ ( A__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = """layoutlmv3""" def __init__( self :List[Any] , lowerCamelCase_ :Optional[int]=50_265 , lowerCamelCase_ :Dict=768 , lowerCamelCase_ :Optional[Any]=12 , lowerCamelCase_ :str=12 , lowerCamelCase_ :Any=3_072 , lowerCamelCase_ :Any="gelu" , lowerCamelCase_ :Optional[Any]=0.1 , lowerCamelCase_ :Tuple=0.1 , lowerCamelCase_ :Optional[Any]=512 , lowerCamelCase_ :Tuple=2 , lowerCamelCase_ :str=0.02 , lowerCamelCase_ :Optional[int]=1e-5 , lowerCamelCase_ :List[Any]=1 , lowerCamelCase_ :Dict=0 , lowerCamelCase_ :Any=2 , lowerCamelCase_ :int=1_024 , lowerCamelCase_ :Union[str, Any]=128 , lowerCamelCase_ :Tuple=128 , lowerCamelCase_ :str=True , lowerCamelCase_ :List[str]=32 , lowerCamelCase_ :List[Any]=128 , lowerCamelCase_ :List[Any]=64 , lowerCamelCase_ :Optional[Any]=256 , lowerCamelCase_ :Union[str, Any]=True , lowerCamelCase_ :int=True , lowerCamelCase_ :Dict=True , lowerCamelCase_ :Tuple=224 , lowerCamelCase_ :List[str]=3 , lowerCamelCase_ :Optional[Any]=16 , lowerCamelCase_ :List[Any]=None , **lowerCamelCase_ :List[str] , ): """simple docstring""" super().__init__( vocab_size=_lowerCAmelCase , hidden_size=_lowerCAmelCase , num_hidden_layers=_lowerCAmelCase , num_attention_heads=_lowerCAmelCase , intermediate_size=_lowerCAmelCase , hidden_act=_lowerCAmelCase , hidden_dropout_prob=_lowerCAmelCase , attention_probs_dropout_prob=_lowerCAmelCase , max_position_embeddings=_lowerCAmelCase , type_vocab_size=_lowerCAmelCase , initializer_range=_lowerCAmelCase , layer_norm_eps=_lowerCAmelCase , pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase , ) lowerCamelCase__ : str =max_ad_position_embeddings lowerCamelCase__ : Union[str, Any] =coordinate_size lowerCamelCase__ : Optional[int] =shape_size lowerCamelCase__ : Optional[int] =has_relative_attention_bias lowerCamelCase__ : List[Any] =rel_pos_bins lowerCamelCase__ : List[str] =max_rel_pos lowerCamelCase__ : List[str] =has_spatial_attention_bias lowerCamelCase__ : List[str] =rel_ad_pos_bins lowerCamelCase__ : Optional[Any] =max_rel_ad_pos lowerCamelCase__ : Optional[Any] =text_embed lowerCamelCase__ : List[str] =visual_embed lowerCamelCase__ : Optional[Any] =input_size lowerCamelCase__ : str =num_channels lowerCamelCase__ : List[str] =patch_size lowerCamelCase__ : Optional[int] =classifier_dropout class A_ ( A__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = version.parse("""1.12""" ) @property def UpperCAmelCase__ ( self :Dict ): """simple docstring""" if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) else: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels'}), ] ) @property def UpperCAmelCase__ ( self :Dict ): """simple docstring""" return 1e-5 @property def UpperCAmelCase__ ( self :Union[str, Any] ): """simple docstring""" return 12 def UpperCAmelCase__ ( self :Union[str, Any] , lowerCamelCase_ :"ProcessorMixin" , lowerCamelCase_ :int = -1 , lowerCamelCase_ :int = -1 , lowerCamelCase_ :bool = False , lowerCamelCase_ :Optional["TensorType"] = None , lowerCamelCase_ :int = 3 , lowerCamelCase_ :int = 40 , lowerCamelCase_ :int = 40 , ): """simple docstring""" setattr(processor.image_processor , 'apply_ocr' , _lowerCAmelCase ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX lowerCamelCase__ : List[str] =compute_effective_axis_dimension( _lowerCAmelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX lowerCamelCase__ : Optional[Any] =processor.tokenizer.num_special_tokens_to_add(_lowerCAmelCase ) lowerCamelCase__ : Union[str, Any] =compute_effective_axis_dimension( _lowerCAmelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_lowerCAmelCase ) # Generate dummy inputs according to compute batch and sequence lowerCamelCase__ : List[str] =[[' '.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes lowerCamelCase__ : Dict =[[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) lowerCamelCase__ : int =self._generate_dummy_images(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) lowerCamelCase__ : Optional[int] =dict( processor( _lowerCAmelCase , text=_lowerCAmelCase , boxes=_lowerCAmelCase , return_tensors=_lowerCAmelCase , ) ) return inputs
126
from typing import Union import fire import torch from tqdm import tqdm def _lowerCAmelCase ( lowerCAmelCase_ :str , lowerCAmelCase_ :str = "cpu" , lowerCAmelCase_ :Union[str, None] = None )->None: '''simple docstring''' snake_case_ = torch.load(lowerCAmelCase_ , map_location=lowerCAmelCase_ ) for k, v in tqdm(state_dict.items() ): if not isinstance(lowerCAmelCase_ , torch.Tensor ): raise TypeError("FP16 conversion only works on paths that are saved state dicts, like pytorch_model.bin" ) snake_case_ = v.half() if save_path is None: # overwrite src_path snake_case_ = src_path torch.save(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": fire.Fire(convert)
159
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase : Dict = logging.get_logger(__name__) lowerCAmelCase : str = { 'microsoft/swin-tiny-patch4-window7-224': ( 'https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json' ), # See all Swin models at https://huggingface.co/models?filter=swin } class SCREAMING_SNAKE_CASE__ ( snake_case_ , snake_case_): lowerCAmelCase_ = """swin""" lowerCAmelCase_ = { """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , A_=224 , A_=4 , A_=3 , A_=96 , A_=[2, 2, 6, 2] , A_=[3, 6, 12, 24] , A_=7 , A_=4.0 , A_=True , A_=0.0 , A_=0.0 , A_=0.1 , A_="gelu" , A_=False , A_=0.02 , A_=1e-5 , A_=32 , A_=None , A_=None , **A_ , )-> Tuple: '''simple docstring''' super().__init__(**A_ ) UpperCamelCase = image_size UpperCamelCase = patch_size UpperCamelCase = num_channels UpperCamelCase = embed_dim UpperCamelCase = depths UpperCamelCase = len(A_ ) UpperCamelCase = num_heads UpperCamelCase = window_size UpperCamelCase = mlp_ratio UpperCamelCase = qkv_bias UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = drop_path_rate UpperCamelCase = hidden_act UpperCamelCase = use_absolute_embeddings UpperCamelCase = layer_norm_eps UpperCamelCase = initializer_range UpperCamelCase = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model UpperCamelCase = int(embed_dim * 2 ** (len(A_ ) - 1) ) UpperCamelCase = ['stem'] + [F'''stage{idx}''' for idx in range(1 , len(A_ ) + 1 )] UpperCamelCase , UpperCamelCase = get_aligned_output_features_output_indices( out_features=A_ , out_indices=A_ , stage_names=self.stage_names ) class SCREAMING_SNAKE_CASE__ ( snake_case_): lowerCAmelCase_ = version.parse("""1.11""") @property def UpperCAmelCase_ ( self )-> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def UpperCAmelCase_ ( self )-> float: '''simple docstring''' return 1e-4
251
'''simple docstring''' lowerCAmelCase : List[Any] = {str(digit): digit**5 for digit in range(10)} def A_( A : int): return sum(DIGITS_FIFTH_POWER[digit] for digit in str(A)) def A_( ): return sum( number for number in range(1000 , 100_0000) if number == digits_fifth_powers_sum(A)) if __name__ == "__main__": print(solution())
251
1
"""simple docstring""" from __future__ import annotations import math def _snake_case ( _snake_case : int , _snake_case : int , _snake_case : bool , _snake_case : list[int] , _snake_case : float ): if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) if not scores: raise ValueError('''Scores cannot be empty''' ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , _snake_case , _snake_case , _snake_case ) , minimax(depth + 1 , node_index * 2 + 1 , _snake_case , _snake_case , _snake_case ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , _snake_case , _snake_case , _snake_case ) , minimax(depth + 1 , node_index * 2 + 1 , _snake_case , _snake_case , _snake_case ) , ) ) def _snake_case ( ): lowerCAmelCase : Optional[int] = [90, 23, 6, 33, 21, 65, 123, 34423] lowerCAmelCase : Union[str, Any] = math.log(len(_snake_case ) , 2 ) print(f'''Optimal value : {minimax(0 , 0 , _snake_case , _snake_case , _snake_case )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
60
'''simple docstring''' import requests from bsa import BeautifulSoup def lowerCamelCase (_SCREAMING_SNAKE_CASE : str = "https://www.worldometers.info/coronavirus" ): __a : List[Any] = BeautifulSoup(requests.get(_SCREAMING_SNAKE_CASE ).text , 'html.parser' ) __a : Union[str, Any] = soup.findAll('h1' ) __a : int = soup.findAll('div' , {'class': 'maincounter-number'} ) keys += soup.findAll('span' , {'class': 'panel-title'} ) values += soup.findAll('div' , {'class': 'number-table-main'} ) return {key.text.strip(): value.text.strip() for key, value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(f'''{key}\n{value}\n''')
27
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCAmelCase__ = { 'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'], 'configuration_maskformer_swin': ['MaskFormerSwinConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['MaskFormerFeatureExtractor'] lowerCAmelCase__ = ['MaskFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ 'MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'MaskFormerForInstanceSegmentation', 'MaskFormerModel', 'MaskFormerPreTrainedModel', ] lowerCAmelCase__ = [ 'MaskFormerSwinBackbone', 'MaskFormerSwinModel', 'MaskFormerSwinPreTrainedModel', ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
356
"""simple docstring""" import math def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = len(_SCREAMING_SNAKE_CASE ) UpperCamelCase = int(math.floor(math.sqrt(_SCREAMING_SNAKE_CASE ) ) ) UpperCamelCase = 0 while arr[min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) - 1] < x: UpperCamelCase = step step += int(math.floor(math.sqrt(_SCREAMING_SNAKE_CASE ) ) ) if prev >= n: return -1 while arr[prev] < x: UpperCamelCase = prev + 1 if prev == min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowerCAmelCase__ = input('''Enter numbers separated by a comma:\n''').strip() lowerCAmelCase__ = [int(item) for item in user_input.split(''',''')] lowerCAmelCase__ = int(input('''Enter the number to be searched:\n''')) lowerCAmelCase__ = jump_search(arr, x) if res == -1: print('''Number not found!''') else: print(f'''Number {x} is at index {res}''')
244
0
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def lowerCAmelCase_ (lowerCAmelCase__: Any ): """simple docstring""" if "img_encoder.pos_embed" in name: UpperCAmelCase_: Optional[Any] = name.replace("""img_encoder.pos_embed""" , """vision_model.embeddings.position_embeddings""" ) if "img_encoder.patch_embed.proj" in name: UpperCAmelCase_: Tuple = name.replace("""img_encoder.patch_embed.proj""" , """vision_model.embeddings.patch_embeddings.projection""" ) if "img_encoder.patch_embed.norm" in name: UpperCAmelCase_: Union[str, Any] = name.replace("""img_encoder.patch_embed.norm""" , """vision_model.embeddings.layernorm""" ) if "img_encoder.layers" in name: UpperCAmelCase_: Union[str, Any] = name.replace("""img_encoder.layers""" , """vision_model.encoder.stages""" ) if "blocks" in name and "res" not in name: UpperCAmelCase_: Any = name.replace("""blocks""" , """layers""" ) if "attn" in name and "pre_assign" not in name: UpperCAmelCase_: Tuple = name.replace("""attn""" , """self_attn""" ) if "proj" in name and "self_attn" in name and "text" not in name: UpperCAmelCase_: Union[str, Any] = name.replace("""proj""" , """out_proj""" ) if "pre_assign_attn.attn.proj" in name: UpperCAmelCase_: Tuple = name.replace("""pre_assign_attn.attn.proj""" , """pre_assign_attn.attn.out_proj""" ) if "norm1" in name: UpperCAmelCase_: Dict = name.replace("""norm1""" , """layer_norm1""" ) if "norm2" in name and "pre_assign" not in name: UpperCAmelCase_: Any = name.replace("""norm2""" , """layer_norm2""" ) if "img_encoder.norm" in name: UpperCAmelCase_: List[Any] = name.replace("""img_encoder.norm""" , """vision_model.layernorm""" ) # text encoder if "text_encoder.token_embedding" in name: UpperCAmelCase_: Any = name.replace("""text_encoder.token_embedding""" , """text_model.embeddings.token_embedding""" ) if "text_encoder.positional_embedding" in name: UpperCAmelCase_: Any = name.replace("""text_encoder.positional_embedding""" , """text_model.embeddings.position_embedding.weight""" ) if "text_encoder.transformer.resblocks." in name: UpperCAmelCase_: str = name.replace("""text_encoder.transformer.resblocks.""" , """text_model.encoder.layers.""" ) if "ln_1" in name: UpperCAmelCase_: Any = name.replace("""ln_1""" , """layer_norm1""" ) if "ln_2" in name: UpperCAmelCase_: List[Any] = name.replace("""ln_2""" , """layer_norm2""" ) if "c_fc" in name: UpperCAmelCase_: int = name.replace("""c_fc""" , """fc1""" ) if "c_proj" in name: UpperCAmelCase_: List[str] = name.replace("""c_proj""" , """fc2""" ) if "text_encoder" in name: UpperCAmelCase_: Any = name.replace("""text_encoder""" , """text_model""" ) if "ln_final" in name: UpperCAmelCase_: Union[str, Any] = name.replace("""ln_final""" , """final_layer_norm""" ) # projection layers if "img_projector.linear_hidden." in name: UpperCAmelCase_: int = name.replace("""img_projector.linear_hidden.""" , """visual_projection.""" ) if "img_projector.linear_out." in name: UpperCAmelCase_: List[str] = name.replace("""img_projector.linear_out.""" , """visual_projection.3.""" ) if "text_projector.linear_hidden" in name: UpperCAmelCase_: Optional[int] = name.replace("""text_projector.linear_hidden""" , """text_projection""" ) if "text_projector.linear_out" in name: UpperCAmelCase_: str = name.replace("""text_projector.linear_out""" , """text_projection.3""" ) return name def lowerCAmelCase_ (lowerCAmelCase__: int , lowerCAmelCase__: Tuple ): """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCAmelCase_: Tuple = orig_state_dict.pop(lowerCAmelCase__ ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors UpperCAmelCase_: Tuple = key.split(""".""" ) UpperCAmelCase_ , UpperCAmelCase_: Any = int(key_split[2] ), int(key_split[4] ) UpperCAmelCase_: Union[str, Any] = config.vision_config.hidden_size if "weight" in key: UpperCAmelCase_: Optional[int] = val[:dim, :] UpperCAmelCase_: str = val[dim : dim * 2, :] UpperCAmelCase_: List[Any] = val[-dim:, :] else: UpperCAmelCase_: str = val[:dim] UpperCAmelCase_: Optional[int] = val[dim : dim * 2] UpperCAmelCase_: List[str] = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors UpperCAmelCase_: Any = key.split(""".""" ) UpperCAmelCase_: Dict = int(key_split[3] ) UpperCAmelCase_: Any = config.text_config.hidden_size if "weight" in key: UpperCAmelCase_: Any = val[:dim, :] UpperCAmelCase_: Tuple = val[ dim : dim * 2, : ] UpperCAmelCase_: str = val[-dim:, :] else: UpperCAmelCase_: Dict = val[:dim] UpperCAmelCase_: Optional[Any] = val[dim : dim * 2] UpperCAmelCase_: Optional[int] = val[-dim:] else: UpperCAmelCase_: str = rename_key(lowerCAmelCase__ ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): UpperCAmelCase_: str = val.squeeze_() else: UpperCAmelCase_: Tuple = val return orig_state_dict def lowerCAmelCase_ (): """simple docstring""" UpperCAmelCase_: Optional[Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" UpperCAmelCase_: Dict = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ (lowerCAmelCase__: Optional[int] , lowerCAmelCase__: Optional[int] , lowerCAmelCase__: str="groupvit-gcc-yfcc" , lowerCAmelCase__: Optional[int]=False ): """simple docstring""" UpperCAmelCase_: Dict = GroupViTConfig() UpperCAmelCase_: Union[str, Any] = GroupViTModel(lowerCAmelCase__ ).eval() UpperCAmelCase_: Optional[int] = torch.load(lowerCAmelCase__ , map_location="""cpu""" )["""model"""] UpperCAmelCase_: List[Any] = convert_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_: Dict = model.load_state_dict(lowerCAmelCase__ , strict=lowerCAmelCase__ ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(lowerCAmelCase__ ) == 0) # verify result UpperCAmelCase_: List[str] = CLIPProcessor.from_pretrained("""openai/clip-vit-base-patch32""" ) UpperCAmelCase_: Any = prepare_img() UpperCAmelCase_: int = processor(text=["""a photo of a cat""", """a photo of a dog"""] , images=lowerCAmelCase__ , padding=lowerCAmelCase__ , return_tensors="""pt""" ) with torch.no_grad(): UpperCAmelCase_: List[Any] = model(**lowerCAmelCase__ ) if model_name == "groupvit-gcc-yfcc": UpperCAmelCase_: int = torch.tensor([[13.3523, 6.3629]] ) elif model_name == "groupvit-gcc-redcaps": UpperCAmelCase_: str = torch.tensor([[16.1873, 8.6230]] ) else: raise ValueError(F'Model name {model_name} not supported.' ) assert torch.allclose(outputs.logits_per_image , lowerCAmelCase__ , atol=1e-3 ) processor.save_pretrained(lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) print("""Successfully saved processor and model to""" , lowerCAmelCase__ ) if push_to_hub: print("""Pushing to the hub...""" ) processor.push_to_hub(lowerCAmelCase__ , organization="""nielsr""" ) model.push_to_hub(lowerCAmelCase__ , organization="""nielsr""" ) if __name__ == "__main__": a : Optional[int] = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to dump the processor and PyTorch model.' ) parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to GroupViT checkpoint') parser.add_argument( '--model_name', default='groupvit-gccy-fcc', type=str, help='Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.', ) a : Optional[Any] = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
147
from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class _a : def __init__(self, SCREAMING_SNAKE_CASE_, ) -> Optional[Any]: UpperCAmelCase_: Optional[int] = parent UpperCAmelCase_: List[Any] = 13 UpperCAmelCase_: Union[str, Any] = 7 UpperCAmelCase_: Optional[Any] = True UpperCAmelCase_: Tuple = True UpperCAmelCase_: Dict = True UpperCAmelCase_: str = 99 UpperCAmelCase_: Tuple = 32 UpperCAmelCase_: Optional[int] = 2 UpperCAmelCase_: Union[str, Any] = 4 UpperCAmelCase_: List[Any] = 37 UpperCAmelCase_: str = """gelu""" UpperCAmelCase_: Dict = 0.1 UpperCAmelCase_: Optional[Any] = 0.1 UpperCAmelCase_: Optional[Any] = 512 UpperCAmelCase_: List[str] = 16 UpperCAmelCase_: Any = 2 UpperCAmelCase_: Union[str, Any] = 0.0_2 UpperCAmelCase_: List[str] = 3 UpperCAmelCase_: Tuple = 4 UpperCAmelCase_: Any = None def __snake_case (self ) -> str: UpperCAmelCase_: List[Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) UpperCAmelCase_: Optional[int] = None if self.use_input_mask: UpperCAmelCase_: Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_: List[Any] = None UpperCAmelCase_: Optional[int] = None UpperCAmelCase_: Tuple = None if self.use_labels: UpperCAmelCase_: List[Any] = ids_tensor([self.batch_size], self.type_sequence_label_size ) UpperCAmelCase_: int = ids_tensor([self.batch_size, self.seq_length], self.num_labels ) UpperCAmelCase_: List[Any] = ids_tensor([self.batch_size], self.num_choices ) UpperCAmelCase_: List[str] = EsmConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, pad_token_id=1, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, initializer_range=self.initializer_range, ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __snake_case (self ) -> Optional[int]: ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ): Optional[Any] = self.prepare_config_and_inputs() UpperCAmelCase_: Dict = True UpperCAmelCase_: Dict = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCAmelCase_: Dict = ids_tensor([self.batch_size, self.seq_length], vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Tuple: UpperCAmelCase_: Optional[int] = TFEsmModel(config=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: str = {"""input_ids""": input_ids, """attention_mask""": input_mask} UpperCAmelCase_: Dict = model(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Dict = [input_ids, input_mask] UpperCAmelCase_: Dict = model(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: List[Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def __snake_case (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_, ) -> List[str]: UpperCAmelCase_: Tuple = True UpperCAmelCase_: List[Any] = TFEsmModel(config=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Optional[int] = { """input_ids""": input_ids, """attention_mask""": input_mask, """encoder_hidden_states""": encoder_hidden_states, """encoder_attention_mask""": encoder_attention_mask, } UpperCAmelCase_: Optional[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Tuple = [input_ids, input_mask] UpperCAmelCase_: List[Any] = model(SCREAMING_SNAKE_CASE_, encoder_hidden_states=SCREAMING_SNAKE_CASE_ ) # Also check the case where encoder outputs are not passed UpperCAmelCase_: Tuple = model(SCREAMING_SNAKE_CASE_, attention_mask=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCAmelCase_: List[Any] = TFEsmForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: Optional[int] = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: UpperCAmelCase_: int = self.num_labels UpperCAmelCase_: Dict = TFEsmForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCAmelCase_: List[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} UpperCAmelCase_: Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels) ) def __snake_case (self ) -> Any: UpperCAmelCase_: Dict = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ): str = config_and_inputs UpperCAmelCase_: int = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class _a ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): A = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) A = ( { '''feature-extraction''': TFEsmModel, '''fill-mask''': TFEsmForMaskedLM, '''text-classification''': TFEsmForSequenceClassification, '''token-classification''': TFEsmForTokenClassification, '''zero-shot''': TFEsmForSequenceClassification, } if is_tf_available() else {} ) A = False A = False def __snake_case (self ) -> Tuple: UpperCAmelCase_: List[Any] = TFEsmModelTester(self ) UpperCAmelCase_: Union[str, Any] = ConfigTester(self, config_class=SCREAMING_SNAKE_CASE_, hidden_size=37 ) def __snake_case (self ) -> Any: self.config_tester.run_common_tests() def __snake_case (self ) -> List[str]: UpperCAmelCase_: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def __snake_case (self ) -> List[Any]: UpperCAmelCase_: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*SCREAMING_SNAKE_CASE_ ) def __snake_case (self ) -> Tuple: UpperCAmelCase_: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def __snake_case (self ) -> List[str]: UpperCAmelCase_: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def __snake_case (self ) -> str: for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_: Dict = TFEsmModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @unittest.skip("""Protein models do not support embedding resizing.""" ) def __snake_case (self ) -> Tuple: pass @unittest.skip("""Protein models do not support embedding resizing.""" ) def __snake_case (self ) -> Optional[Any]: pass def __snake_case (self ) -> List[Any]: UpperCAmelCase_ , UpperCAmelCase_: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_: List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) assert isinstance(model.get_input_embeddings(), tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer UpperCAmelCase_: Any = model.get_bias() assert isinstance(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) for k, v in name.items(): assert isinstance(SCREAMING_SNAKE_CASE_, tf.Variable ) else: UpperCAmelCase_: Union[str, Any] = model.get_output_embeddings() assert x is None UpperCAmelCase_: Optional[int] = model.get_bias() assert name is None @require_tf class _a ( unittest.TestCase ): @slow def __snake_case (self ) -> str: UpperCAmelCase_: str = TFEsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) UpperCAmelCase_: Tuple = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCAmelCase_: int = model(SCREAMING_SNAKE_CASE_ )[0] UpperCAmelCase_: Optional[int] = [1, 6, 33] self.assertEqual(list(output.numpy().shape ), SCREAMING_SNAKE_CASE_ ) # compare the actual values for a slice. UpperCAmelCase_: List[str] = tf.constant( [ [ [8.9_2_1_5_1_8, -1_0.5_8_9_8_1_4, -6.4_6_7_1_3_0_7], [-6.3_9_6_7_1_5_6, -1_3.9_1_1_3_7_7, -1.1_2_1_1_9_1_5], [-7.7_8_1_2_4_7, -1_3.9_5_1_5_5_7, -3.7_4_0_5_9_2], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1E-2 ) ) @slow def __snake_case (self ) -> Optional[int]: UpperCAmelCase_: List[Any] = TFEsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) UpperCAmelCase_: Any = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) UpperCAmelCase_: Optional[int] = model(SCREAMING_SNAKE_CASE_ )[0] # compare the actual values for a slice. UpperCAmelCase_: str = tf.constant( [ [ [0.1_4_4_4_3_0_9_2, 0.5_4_1_2_5_3_2_7, 0.3_2_4_7_7_3_9], [0.3_0_3_4_0_4_8_4, 0.0_0_5_2_6_6_7_6, 0.3_1_0_7_7_7_2_2], [0.3_2_2_7_8_0_4_3, -0.2_4_9_8_7_0_9_6, 0.3_4_1_4_6_2_8], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1E-4 ) )
147
1
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() A : Any = logging.get_logger(__name__) A : List[str] = { """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""", """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""": """ctc_proj""", """mask_emb""": """masked_spec_embed""", } A : Optional[int] = [ """ctc_proj""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", ] def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' for attribute in key.split("." ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models __lowerCAmelCase = 'lm_head' __lowerCAmelCase = getattr(_UpperCAmelCase , _UpperCAmelCase ) if weight_type is not None: __lowerCAmelCase = getattr(_UpperCAmelCase , _UpperCAmelCase ).shape else: __lowerCAmelCase = hf_pointer.shape assert hf_shape == value.shape, ( f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" f" {value.shape} for {full_name}" ) if weight_type == "weight": __lowerCAmelCase = value elif weight_type == "weight_g": __lowerCAmelCase = value elif weight_type == "weight_v": __lowerCAmelCase = value elif weight_type == "bias": __lowerCAmelCase = value else: __lowerCAmelCase = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = [] __lowerCAmelCase = fairseq_model.state_dict() __lowerCAmelCase = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): __lowerCAmelCase = False if "conv_layers" in name: load_conv_layer( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , hf_model.config.feat_extract_norm == "group" , ) __lowerCAmelCase = True else: for key, mapped_key in MAPPING.items(): __lowerCAmelCase = 'unispeech.' + 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]: __lowerCAmelCase = True if "*" in mapped_key: __lowerCAmelCase = name.split(_UpperCAmelCase )[0].split("." )[-2] __lowerCAmelCase = mapped_key.replace("*" , _UpperCAmelCase ) if "weight_g" in name: __lowerCAmelCase = 'weight_g' elif "weight_v" in name: __lowerCAmelCase = 'weight_v' elif "bias" in name: __lowerCAmelCase = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCAmelCase = 'weight' else: __lowerCAmelCase = None set_recursively(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) continue if not is_used: unused_weights.append(_UpperCAmelCase ) logger.warning(f"Unused weights: {unused_weights}" ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowerCAmelCase = full_name.split("conv_layers." )[-1] __lowerCAmelCase = name.split("." ) __lowerCAmelCase = int(items[0] ) __lowerCAmelCase = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __lowerCAmelCase = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __lowerCAmelCase = value logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) __lowerCAmelCase = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"{full_name} has size {value.shape}, but" f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __lowerCAmelCase = 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 _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=None , _UpperCamelCase=None , _UpperCamelCase=True ): '''simple docstring''' if config_path is not None: __lowerCAmelCase = UniSpeechConfig.from_pretrained(_UpperCAmelCase ) else: __lowerCAmelCase = UniSpeechConfig() if is_finetuned: if dict_path: __lowerCAmelCase = Dictionary.load_from_json(_UpperCAmelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __lowerCAmelCase = target_dict.pad_index __lowerCAmelCase = target_dict.bos_index __lowerCAmelCase = target_dict.eos_index __lowerCAmelCase = len(target_dict.symbols ) __lowerCAmelCase = os.path.join(_UpperCAmelCase , "vocab.json" ) if not os.path.isdir(_UpperCAmelCase ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(_UpperCAmelCase ) ) return os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase ) __lowerCAmelCase = target_dict.indices # fairseq has the <pad> and <s> switched __lowerCAmelCase = 42 __lowerCAmelCase = 43 with open(_UpperCAmelCase , "w" , encoding="utf-8" ) as vocab_handle: json.dump(_UpperCAmelCase , _UpperCAmelCase ) __lowerCAmelCase = WavaVecaPhonemeCTCTokenizer( _UpperCAmelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="|" , do_lower_case=_UpperCAmelCase , ) __lowerCAmelCase = True if config.feat_extract_norm == 'layer' else False __lowerCAmelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , ) __lowerCAmelCase = WavaVecaProcessor(feature_extractor=_UpperCAmelCase , tokenizer=_UpperCAmelCase ) processor.save_pretrained(_UpperCAmelCase ) __lowerCAmelCase = UniSpeechForCTC(_UpperCAmelCase ) else: __lowerCAmelCase = UniSpeechForPreTraining(_UpperCAmelCase ) if is_finetuned: __lowerCAmelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] ), "w2v_path": checkpoint_path} ) else: __lowerCAmelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) __lowerCAmelCase = model[0].eval() recursively_load_weights(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) hf_unispeech.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": A : Optional[Any] = 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" ) A : List[str] = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
351
"""simple docstring""" import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=() , _UpperCamelCase=None , _UpperCamelCase="no" , _UpperCamelCase="29500" ): '''simple docstring''' __lowerCAmelCase = False __lowerCAmelCase = False if any(key.startswith("KAGGLE" ) for key in os.environ.keys() ): __lowerCAmelCase = True elif "IPython" in sys.modules: __lowerCAmelCase = "google.colab" in str(sys.modules["IPython"].get_ipython() ) try: __lowerCAmelCase = PrecisionType(mixed_precision.lower() ) except ValueError: raise ValueError( f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." ) if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME" , _UpperCamelCase ) is not None): # TPU launch import torch_xla.distributed.xla_multiprocessing as xmp if len(AcceleratorState._shared_state ) > 0: raise ValueError( "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside " "your training function. Restart your notebook and make sure no cells initializes an " "`Accelerator`." ) if num_processes is None: __lowerCAmelCase = 8 __lowerCAmelCase = PrepareForLaunch(_UpperCamelCase , distributed_type="TPU" ) print(f"Launching a training on {num_processes} TPU cores." ) xmp.spawn(_UpperCamelCase , args=_UpperCamelCase , nprocs=_UpperCamelCase , start_method="fork" ) elif in_colab: # No need for a distributed launch otherwise as it's either CPU or one GPU. if torch.cuda.is_available(): print("Launching training on one GPU." ) else: print("Launching training on one CPU." ) function(*_UpperCamelCase ) else: if num_processes is None: raise ValueError( "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call." ) if num_processes > 1: # Multi-GPU launch from torch.multiprocessing import start_processes from torch.multiprocessing.spawn import ProcessRaisedException if len(AcceleratorState._shared_state ) > 0: raise ValueError( "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized " "inside your training function. Restart your notebook and make sure no cells initializes an " "`Accelerator`." ) if torch.cuda.is_initialized(): raise ValueError( "To launch a multi-GPU training from your notebook, you need to avoid running any instruction " "using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA " "function." ) # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=_UpperCamelCase , master_addr="127.0.01" , master_port=_UpperCamelCase , mixed_precision=_UpperCamelCase ): __lowerCAmelCase = PrepareForLaunch(_UpperCamelCase , distributed_type="MULTI_GPU" ) print(f"Launching training on {num_processes} GPUs." ) try: start_processes(_UpperCamelCase , args=_UpperCamelCase , nprocs=_UpperCamelCase , start_method="fork" ) except ProcessRaisedException as e: if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: raise RuntimeError( "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. " "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. " "Please review your imports and test them when running the `notebook_launcher()` to identify " "which one is problematic." ) from e else: # No need for a distributed launch otherwise as it's either CPU, GPU or MPS. if is_mps_available(): __lowerCAmelCase = "1" print("Launching training on MPS." ) elif torch.cuda.is_available(): print("Launching training on one GPU." ) else: print("Launching training on CPU." ) function(*_UpperCamelCase ) def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase=() , _UpperCamelCase=2 ): '''simple docstring''' from torch.multiprocessing import start_processes with tempfile.NamedTemporaryFile() as tmp_file: # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=_UpperCamelCase , master_addr="127.0.01" , master_port="29500" , accelerate_mixed_precision="no" , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu="yes" , ): __lowerCAmelCase = PrepareForLaunch(_UpperCamelCase , debug=_UpperCamelCase ) start_processes(_UpperCamelCase , args=_UpperCamelCase , nprocs=_UpperCamelCase , start_method="fork" )
259
0
"""simple docstring""" import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def __UpperCAmelCase ( UpperCAmelCase_ : Optional[int] ) -> Tuple: '''simple docstring''' __snake_case : Any = [] embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight", F"stage{idx}.patch_embed.proj.weight", ) ) embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias", F"stage{idx}.patch_embed.proj.bias", ) ) embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight", F"stage{idx}.patch_embed.norm.weight", ) ) embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias", F"stage{idx}.patch_embed.norm.bias", ) ) return embed def __UpperCAmelCase ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any ) -> Dict: '''simple docstring''' __snake_case : Optional[Any] = [] attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight", F"stage{idx}.blocks.{cnt}.attn.proj_q.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias", F"stage{idx}.blocks.{cnt}.attn.proj_q.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight", F"stage{idx}.blocks.{cnt}.attn.proj_k.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias", F"stage{idx}.blocks.{cnt}.attn.proj_k.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight", F"stage{idx}.blocks.{cnt}.attn.proj_v.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias", F"stage{idx}.blocks.{cnt}.attn.proj_v.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight", F"stage{idx}.blocks.{cnt}.attn.proj.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias", F"stage{idx}.blocks.{cnt}.attn.proj.bias", ) ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight", F"stage{idx}.blocks.{cnt}.mlp.fc1.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias", F"stage{idx}.blocks.{cnt}.mlp.fc1.bias") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight", F"stage{idx}.blocks.{cnt}.mlp.fc2.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias", F"stage{idx}.blocks.{cnt}.mlp.fc2.bias") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight", F"stage{idx}.blocks.{cnt}.norm1.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias", F"stage{idx}.blocks.{cnt}.norm1.bias") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight", F"stage{idx}.blocks.{cnt}.norm2.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias", F"stage{idx}.blocks.{cnt}.norm2.bias") ) return attention_weights def __UpperCAmelCase ( UpperCAmelCase_ : int ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[Any] = [] token.append((F"cvt.encoder.stages.{idx}.cls_token", 'stage2.cls_token') ) return token def __UpperCAmelCase ( ) -> Optional[Any]: '''simple docstring''' __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def __UpperCAmelCase ( UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : List[Any] = 'imagenet-1k-id2label.json' __snake_case : Tuple = 10_00 __snake_case : int = 'huggingface/label-files' __snake_case : int = num_labels __snake_case : List[str] = json.load(open(cached_download(hf_hub_url(UpperCAmelCase_ , UpperCAmelCase_ , repo_type='dataset' ) ) , 'r' ) ) __snake_case : Any = {int(UpperCAmelCase_ ): v for k, v in idalabel.items()} __snake_case : Union[str, Any] = idalabel __snake_case : Optional[Any] = {v: k for k, v in idalabel.items()} __snake_case : List[Any] = CvtConfig(num_labels=UpperCAmelCase_ , idalabel=UpperCAmelCase_ , labelaid=UpperCAmelCase_ ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' , 1 )[-1][4:6] == "13": __snake_case : Optional[int] = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' , 1 )[-1][4:6] == "21": __snake_case : List[Any] = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Optional[Any] = [2, 2, 20] __snake_case : List[Any] = [3, 12, 16] __snake_case : str = [1_92, 7_68, 10_24] __snake_case : Any = CvtForImageClassification(UpperCAmelCase_ ) __snake_case : Optional[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : Dict = image_size __snake_case : Optional[Any] = torch.load(UpperCAmelCase_ , map_location=torch.device('cpu' ) ) __snake_case : Tuple = OrderedDict() __snake_case : Tuple = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : str = list_of_state_dict + cls_token(UpperCAmelCase_ ) __snake_case : str = list_of_state_dict + embeddings(UpperCAmelCase_ ) for cnt in range(config.depth[idx] ): __snake_case : str = list_of_state_dict + attention(UpperCAmelCase_ , UpperCAmelCase_ ) __snake_case : Union[str, Any] = list_of_state_dict + final() for gg in list_of_state_dict: print(UpperCAmelCase_ ) for i in range(len(UpperCAmelCase_ ) ): __snake_case : Optional[Any] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(UpperCAmelCase_ ) model.save_pretrained(UpperCAmelCase_ ) image_processor.save_pretrained(UpperCAmelCase_ ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": _a : Dict= argparse.ArgumentParser() parser.add_argument( "--cvt_model", default="cvt-w24", type=str, help="Name of the cvt model you'd like to convert.", ) parser.add_argument( "--image_size", default=384, type=int, help="Input Image Size", ) parser.add_argument( "--cvt_file_name", default=R"cvtmodels\CvT-w24-384x384-IN-22k.pth", type=str, help="Input Image Size", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) _a : int= parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
172
"""simple docstring""" _a : Tuple= 8.3_1_4_4_5_9_8 def __UpperCAmelCase ( UpperCAmelCase_ : float , UpperCAmelCase_ : float ) -> float: '''simple docstring''' if temperature < 0: raise Exception('Temperature cannot be less than 0 K' ) if molar_mass <= 0: raise Exception('Molar mass cannot be less than or equal to 0 kg/mol' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example _a : Any= 300 _a : Optional[Any]= 28 _a : Optional[int]= rms_speed_of_molecule(temperature, molar_mass) print(f'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
172
1
'''simple docstring''' import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class A_ ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase_ ( self : str ) -> List[Any]: UpperCAmelCase : Union[str, Any] = 'hf-internal-testing/tiny-random-t5' UpperCAmelCase : str = AutoTokenizer.from_pretrained(lowercase_ ) UpperCAmelCase : Union[str, Any] = AutoModelForSeqaSeqLM.from_pretrained(lowercase_ ) UpperCAmelCase : Dict = tokenizer('This is me' , return_tensors='pt' ) UpperCAmelCase : Dict = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) UpperCAmelCase : List[Any] = model.generate(**lowercase_ ) UpperCAmelCase : Dict = model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowercase_ ) UpperCAmelCase : int = AutoModelForSeqaSeqLM.from_pretrained(lowercase_ ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) UpperCAmelCase : List[str] = model_reloaded.generate(**lowercase_ ) self.assertTrue(torch.allclose(lowercase_ , lowercase_ ) ) def UpperCAmelCase_ ( self : str ) -> Optional[Any]: UpperCAmelCase : Tuple = 'hf-internal-testing/tiny-random-t5' UpperCAmelCase : List[str] = AutoModelForSeqaSeqLM.from_pretrained(lowercase_ ) UpperCAmelCase : Union[str, Any] = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(lowercase_ ): model.save_pretrained(lowercase_ ) UpperCAmelCase : Dict = model.reverse_bettertransformer() model.save_pretrained(lowercase_ )
280
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase__ = { "configuration_xlm": ["XLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMConfig", "XLMOnnxConfig"], "tokenization_xlm": ["XLMTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "XLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMForMultipleChoice", "XLMForQuestionAnswering", "XLMForQuestionAnsweringSimple", "XLMForSequenceClassification", "XLMForTokenClassification", "XLMModel", "XLMPreTrainedModel", "XLMWithLMHeadModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLMForMultipleChoice", "TFXLMForQuestionAnsweringSimple", "TFXLMForSequenceClassification", "TFXLMForTokenClassification", "TFXLMMainLayer", "TFXLMModel", "TFXLMPreTrainedModel", "TFXLMWithLMHeadModel", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys lowercase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
280
1
def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], }, { 0: [6], 1: [9], 2: [4, 5], 3: [4], 4: [2, 3], 5: [2], 6: [0, 7], 7: [6], 8: [], 9: [1], }, { 0: [4], 1: [6], 2: [], 3: [5, 6, 7], 4: [0, 6], 5: [3, 8, 9], 6: [1, 3, 4, 7], 7: [3, 6, 8, 9], 8: [5, 7], 9: [5, 7], }, { 0: [1, 3], 1: [0, 2, 4], 2: [1, 3, 4], 3: [0, 2, 4], 4: [1, 2, 3], }, ][index] def __lowercase ( _SCREAMING_SNAKE_CASE ) -> list[tuple[int, int]]: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_SCREAMING_SNAKE_CASE ) # No of vertices in graph SCREAMING_SNAKE_CASE = [0] * n SCREAMING_SNAKE_CASE = [False] * n def dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = id_ id_ += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , id_ ) SCREAMING_SNAKE_CASE = min(low[at] , low[to] ) if id_ <= low[to]: bridges.append((at, to) if at < to else (to, at) ) else: # This edge is a back edge and cannot be a bridge SCREAMING_SNAKE_CASE = min(low[at] , low[to] ) SCREAMING_SNAKE_CASE = [] for i in range(_SCREAMING_SNAKE_CASE ): if not visited[i]: dfs(_SCREAMING_SNAKE_CASE , -1 , _SCREAMING_SNAKE_CASE , id_ ) return bridges if __name__ == "__main__": import doctest doctest.testmod()
296
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE_ = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
296
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _UpperCamelCase = logging.get_logger(__name__) _UpperCamelCase = { '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''', } class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : str = "blip_2_vision_model" def __init__( self , __UpperCAmelCase=1_408 , __UpperCAmelCase=6_144 , __UpperCAmelCase=39 , __UpperCAmelCase=16 , __UpperCAmelCase=224 , __UpperCAmelCase=14 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.0_0001 , __UpperCAmelCase=0.0 , __UpperCAmelCase=1E-10 , __UpperCAmelCase=True , **__UpperCAmelCase , ) -> Dict: '''simple docstring''' super().__init__(**__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = hidden_size __UpperCAmelCase : Any = intermediate_size __UpperCAmelCase : Optional[int] = num_hidden_layers __UpperCAmelCase : Union[str, Any] = num_attention_heads __UpperCAmelCase : List[Any] = patch_size __UpperCAmelCase : Tuple = image_size __UpperCAmelCase : Tuple = initializer_range __UpperCAmelCase : Optional[int] = attention_dropout __UpperCAmelCase : Any = layer_norm_eps __UpperCAmelCase : Dict = hidden_act __UpperCAmelCase : List[Any] = qkv_bias @classmethod def __A ( cls , __UpperCAmelCase , **__UpperCAmelCase ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__UpperCAmelCase ) __UpperCAmelCase , __UpperCAmelCase : int = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase ) # get the vision config dict if we are loading from Blip2Config if config_dict.get("""model_type""" ) == "blip-2": __UpperCAmelCase : List[str] = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Dict = "blip_2_qformer" def __init__( self , __UpperCAmelCase=30_522 , __UpperCAmelCase=768 , __UpperCAmelCase=12 , __UpperCAmelCase=12 , __UpperCAmelCase=3_072 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=512 , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-12 , __UpperCAmelCase=0 , __UpperCAmelCase="absolute" , __UpperCAmelCase=2 , __UpperCAmelCase=1_408 , **__UpperCAmelCase , ) -> int: '''simple docstring''' super().__init__(pad_token_id=__UpperCAmelCase , **__UpperCAmelCase ) __UpperCAmelCase : Dict = vocab_size __UpperCAmelCase : int = hidden_size __UpperCAmelCase : Tuple = num_hidden_layers __UpperCAmelCase : Optional[int] = num_attention_heads __UpperCAmelCase : Any = hidden_act __UpperCAmelCase : Dict = intermediate_size __UpperCAmelCase : Union[str, Any] = hidden_dropout_prob __UpperCAmelCase : Optional[Any] = attention_probs_dropout_prob __UpperCAmelCase : Optional[int] = max_position_embeddings __UpperCAmelCase : Optional[int] = initializer_range __UpperCAmelCase : Dict = layer_norm_eps __UpperCAmelCase : Tuple = position_embedding_type __UpperCAmelCase : List[str] = cross_attention_frequency __UpperCAmelCase : Tuple = encoder_hidden_size @classmethod def __A ( cls , __UpperCAmelCase , **__UpperCAmelCase ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(__UpperCAmelCase ) __UpperCAmelCase , __UpperCAmelCase : Any = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get("""model_type""" ) == "blip-2": __UpperCAmelCase : int = config_dict["""qformer_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = "blip-2" _SCREAMING_SNAKE_CASE : str = True def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=32 , **__UpperCAmelCase ) -> List[str]: '''simple docstring''' super().__init__(**__UpperCAmelCase ) if vision_config is None: __UpperCAmelCase : Dict = {} logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values.""" ) if qformer_config is None: __UpperCAmelCase : Dict = {} logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values.""" ) if text_config is None: __UpperCAmelCase : Tuple = {} logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" ) __UpperCAmelCase : Dict = BlipaVisionConfig(**__UpperCAmelCase ) __UpperCAmelCase : str = BlipaQFormerConfig(**__UpperCAmelCase ) __UpperCAmelCase : Tuple = text_config["""model_type"""] if """model_type""" in text_config else """opt""" __UpperCAmelCase : str = CONFIG_MAPPING[text_model_type](**__UpperCAmelCase ) __UpperCAmelCase : str = self.text_config.tie_word_embeddings __UpperCAmelCase : Any = self.text_config.is_encoder_decoder __UpperCAmelCase : Dict = num_query_tokens __UpperCAmelCase : str = self.vision_config.hidden_size __UpperCAmelCase : Optional[int] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCAmelCase : List[Any] = 1.0 __UpperCAmelCase : Optional[Any] = 0.02 @classmethod def __A ( cls , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase , ) -> Optional[int]: '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **__UpperCAmelCase , ) def __A ( self ) -> Tuple: '''simple docstring''' __UpperCAmelCase : str = copy.deepcopy(self.__dict__ ) __UpperCAmelCase : str = self.vision_config.to_dict() __UpperCAmelCase : Tuple = self.qformer_config.to_dict() __UpperCAmelCase : str = self.text_config.to_dict() __UpperCAmelCase : Tuple = self.__class__.model_type return output
16
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL _UpperCamelCase = logging.get_logger(__name__) def lowercase_ ( lowerCAmelCase__ : List[str] ): """simple docstring""" if isinstance(lowerCAmelCase__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowerCAmelCase__ , (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowerCAmelCase__ ): return [[videos]] raise ValueError(f'Could not make batched video from {videos}' ) class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Optional[int] = ["pixel_values"] def __init__( self , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = True , __UpperCAmelCase = 1 / 255 , __UpperCAmelCase = True , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> None: '''simple docstring''' super().__init__(**__UpperCAmelCase ) __UpperCAmelCase : int = size if size is not None else {"""shortest_edge""": 256} __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) __UpperCAmelCase : Any = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , param_name="""crop_size""" ) __UpperCAmelCase : int = do_resize __UpperCAmelCase : List[str] = size __UpperCAmelCase : Any = do_center_crop __UpperCAmelCase : Any = crop_size __UpperCAmelCase : Optional[Any] = resample __UpperCAmelCase : Dict = do_rescale __UpperCAmelCase : List[str] = rescale_factor __UpperCAmelCase : Dict = offset __UpperCAmelCase : List[str] = do_normalize __UpperCAmelCase : List[str] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __UpperCAmelCase : str = image_std if image_std is not None else IMAGENET_STANDARD_STD def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = PILImageResampling.BILINEAR , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' __UpperCAmelCase : List[str] = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) if "shortest_edge" in size: __UpperCAmelCase : Union[str, Any] = get_resize_output_image_size(__UpperCAmelCase , size["""shortest_edge"""] , default_to_square=__UpperCAmelCase ) elif "height" in size and "width" in size: __UpperCAmelCase : Any = (size["""height"""], size["""width"""]) else: raise ValueError(f'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}' ) return resize(__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' __UpperCAmelCase : Any = get_size_dict(__UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'Size must have \'height\' and \'width\' as keys. Got {size.keys()}' ) return center_crop(__UpperCAmelCase , size=(size["""height"""], size["""width"""]) , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = True , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> str: '''simple docstring''' __UpperCAmelCase : Tuple = image.astype(np.floataa ) if offset: __UpperCAmelCase : Tuple = image - (scale / 2) return rescale(__UpperCAmelCase , scale=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> np.ndarray: '''simple docstring''' return normalize(__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase , data_format=__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , ) -> np.ndarray: '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) if offset and not do_rescale: raise ValueError("""For offset, do_rescale must also be set to True.""" ) # All transformations expect numpy arrays. __UpperCAmelCase : Optional[Any] = to_numpy_array(__UpperCAmelCase ) if do_resize: __UpperCAmelCase : Optional[int] = self.resize(image=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase ) if do_center_crop: __UpperCAmelCase : Optional[int] = self.center_crop(__UpperCAmelCase , size=__UpperCAmelCase ) if do_rescale: __UpperCAmelCase : int = self.rescale(image=__UpperCAmelCase , scale=__UpperCAmelCase , offset=__UpperCAmelCase ) if do_normalize: __UpperCAmelCase : List[str] = self.normalize(image=__UpperCAmelCase , mean=__UpperCAmelCase , std=__UpperCAmelCase ) __UpperCAmelCase : List[Any] = to_channel_dimension_format(__UpperCAmelCase , __UpperCAmelCase ) return image def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = ChannelDimension.FIRST , **__UpperCAmelCase , ) -> PIL.Image.Image: '''simple docstring''' __UpperCAmelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize __UpperCAmelCase : List[Any] = resample if resample is not None else self.resample __UpperCAmelCase : str = do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCAmelCase : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale __UpperCAmelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCAmelCase : List[Any] = offset if offset is not None else self.offset __UpperCAmelCase : Tuple = do_normalize if do_normalize is not None else self.do_normalize __UpperCAmelCase : Optional[Any] = image_mean if image_mean is not None else self.image_mean __UpperCAmelCase : int = image_std if image_std is not None else self.image_std __UpperCAmelCase : Any = size if size is not None else self.size __UpperCAmelCase : Tuple = get_size_dict(__UpperCAmelCase , default_to_square=__UpperCAmelCase ) __UpperCAmelCase : Optional[Any] = crop_size if crop_size is not None else self.crop_size __UpperCAmelCase : str = get_size_dict(__UpperCAmelCase , param_name="""crop_size""" ) if not valid_images(__UpperCAmelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) __UpperCAmelCase : int = make_batched(__UpperCAmelCase ) __UpperCAmelCase : Tuple = [ [ self._preprocess_image( image=__UpperCAmelCase , do_resize=__UpperCAmelCase , size=__UpperCAmelCase , resample=__UpperCAmelCase , do_center_crop=__UpperCAmelCase , crop_size=__UpperCAmelCase , do_rescale=__UpperCAmelCase , rescale_factor=__UpperCAmelCase , offset=__UpperCAmelCase , do_normalize=__UpperCAmelCase , image_mean=__UpperCAmelCase , image_std=__UpperCAmelCase , data_format=__UpperCAmelCase , ) for img in video ] for video in videos ] __UpperCAmelCase : Tuple = {"""pixel_values""": videos} return BatchFeature(data=__UpperCAmelCase , tensor_type=__UpperCAmelCase )
16
1
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : List[str] = prime_factors(_a) if is_square_free(_a): return -1 if len(_a) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
76
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = tokenizer(example["content"] , truncation=_a)["input_ids"] SCREAMING_SNAKE_CASE : Dict = len(example["content"]) / len(output["input_ids"]) return output a_ = HfArgumentParser(PretokenizationArguments) a_ = parser.parse_args() if args.num_workers is None: a_ = multiprocessing.cpu_count() a_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) a_ = time.time() a_ = load_dataset(args.dataset_name, split='train') print(F'''Dataset loaded in {time.time()-t_start:.2f}s''') a_ = time.time() a_ = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ 'repo_name', 'path', 'copies', 'size', 'content', 'license', 'hash', 'line_mean', 'line_max', 'alpha_frac', 'autogenerated', ], ) print(F'''Dataset tokenized in {time.time()-t_start:.2f}s''') a_ = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
76
1
import unittest from typing import Dict, List, Optional, Union 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 BridgeTowerImageProcessor class _snake_case ( unittest.TestCase ): def __init__( self , a , a = True , a = None , a = 32 , a = True , a = 1 / 255 , a = True , a = True , a = [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] , a = [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] , a = True , a=7 , a=30 , a=400 , a=3 , ) -> Optional[Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size if size is not None else {'shortest_edge': 288} SCREAMING_SNAKE_CASE = size_divisor SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_normalize SCREAMING_SNAKE_CASE = do_center_crop SCREAMING_SNAKE_CASE = image_mean SCREAMING_SNAKE_CASE = image_std SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = min_resolution SCREAMING_SNAKE_CASE = max_resolution def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def SCREAMING_SNAKE_CASE__ ( self , a , a=False) -> Optional[int]: if not batched: SCREAMING_SNAKE_CASE = self.size['shortest_edge'] SCREAMING_SNAKE_CASE = image_inputs[0] if isinstance(a , Image.Image): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image.size else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image.shape[1], image.shape[2] SCREAMING_SNAKE_CASE = size / min(a , a) if h < w: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = size, scale * w else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = scale * h, size SCREAMING_SNAKE_CASE = int((1333 / 800) * size) if max(a , a) > max_size: SCREAMING_SNAKE_CASE = max_size / max(a , a) SCREAMING_SNAKE_CASE = newh * scale SCREAMING_SNAKE_CASE = neww * scale SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = int(newh + 0.5), int(neww + 0.5) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: SCREAMING_SNAKE_CASE = [] for image in image_inputs: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) SCREAMING_SNAKE_CASE = max(a , key=lambda a: item[0])[0] SCREAMING_SNAKE_CASE = max(a , key=lambda a: item[1])[1] return expected_height, expected_width @require_torch @require_vision class _snake_case ( A__ , unittest.TestCase ): _lowercase : Tuple = BridgeTowerImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = BridgeTowerImageProcessingTester(self) @property def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(a , 'image_mean')) self.assertTrue(hasattr(a , 'image_std')) self.assertTrue(hasattr(a , 'do_normalize')) self.assertTrue(hasattr(a , 'do_resize')) self.assertTrue(hasattr(a , 'size')) self.assertTrue(hasattr(a , 'size_divisor')) def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: # Initialize image processor SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) # create random PIL images SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=a) for image in image_inputs: self.assertIsInstance(a , Image.Image) # Test not batched input SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a , batched=a) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: # Initialize image processor SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=a , numpify=a) for image in image_inputs: self.assertIsInstance(a , np.ndarray) # Test not batched input SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a , batched=a) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: # Initialize image processor SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=a , torchify=a) for image in image_inputs: self.assertIsInstance(a , torch.Tensor) # Test not batched input SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a , batched=a) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
327
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set()) @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): class _snake_case : def __init__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = metric_id class _snake_case : _lowercase : Optional[Any] = [MetricMock(A__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock()) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "tmp_path" in args: SCREAMING_SNAKE_CASE = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args) with pytest.warns(_UpperCAmelCase , match='https://huggingface.co/docs/evaluate'): func(*_UpperCAmelCase)
327
1
"""simple docstring""" class __lowerCAmelCase : def __init__( self , __UpperCAmelCase ): '''simple docstring''' __UpperCamelCase = len(__UpperCAmelCase ) __UpperCamelCase = [0] * len_array if len_array > 0: __UpperCamelCase = array[0] for i in range(1 , __UpperCAmelCase ): __UpperCamelCase = self.prefix_sum[i - 1] + array[i] def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def UpperCAmelCase ( self , __UpperCAmelCase ): '''simple docstring''' __UpperCamelCase = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(__UpperCAmelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
316
"""simple docstring""" import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings UpperCamelCase : str = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): lowercase = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to use SortishSampler or not."} ) lowercase = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": ( "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." ) } , ) lowercase = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": ( "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `num_beams` value of the model configuration." ) } , ) lowercase = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": "Model id, file path or url pointing to a GenerationConfig json file, to use during prediction." } , ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = super().to_dict() for k, v in d.items(): if isinstance(__UpperCAmelCase , __UpperCAmelCase ): __UpperCamelCase = v.to_dict() return d
316
1
def _A ( lowercase = 10_00 ): """simple docstring""" a =3 a =0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(F'{solution() = }')
367
"""simple docstring""" import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __A ( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = IFInpaintingSuperResolutionPipeline __lowerCAmelCase = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} __lowerCAmelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"original_image"} ) __lowerCAmelCase = PipelineTesterMixin.required_optional_params - {"latents"} def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: return self._get_superresolution_dummy_components() def SCREAMING_SNAKE_CASE ( self , __A , __A=0 ) -> Optional[int]: if str(__A ).startswith('''mps''' ): a =torch.manual_seed(__A ) else: a =torch.Generator(device=__A ).manual_seed(__A ) a =floats_tensor((1, 3, 16, 16) , rng=random.Random(__A ) ).to(__A ) a =floats_tensor((1, 3, 32, 32) , rng=random.Random(__A ) ).to(__A ) a =floats_tensor((1, 3, 32, 32) , rng=random.Random(__A ) ).to(__A ) a ={ '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''original_image''': original_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def SCREAMING_SNAKE_CASE ( self ) -> int: # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def SCREAMING_SNAKE_CASE ( self ) -> Any: self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: self._test_save_load_local() def SCREAMING_SNAKE_CASE ( self ) -> Dict: self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
215
0
"""simple docstring""" import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_MAPPING, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerModel, ) from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import SegformerImageProcessor class lowerCAmelCase_ ( lowerCAmelCase ): """simple docstring""" def snake_case ( self ): """simple docstring""" snake_case = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , 'hidden_sizes' ) ) self.parent.assertTrue(hasattr(_a , 'num_attention_heads' ) ) self.parent.assertTrue(hasattr(_a , 'num_encoder_blocks' ) ) class lowerCAmelCase_ : """simple docstring""" def __init__( self , lowerCAmelCase , lowerCAmelCase=13 , lowerCAmelCase=64 , lowerCAmelCase=3 , lowerCAmelCase=4 , lowerCAmelCase=[2, 2, 2, 2] , lowerCAmelCase=[8, 4, 2, 1] , lowerCAmelCase=[16, 32, 64, 1_28] , lowerCAmelCase=[1, 4, 8, 16] , lowerCAmelCase=[1, 2, 4, 8] , lowerCAmelCase=True , lowerCAmelCase=True , lowerCAmelCase="gelu" , lowerCAmelCase=0.1 , lowerCAmelCase=0.1 , lowerCAmelCase=0.02 , lowerCAmelCase=3 , lowerCAmelCase=None , ): """simple docstring""" snake_case = parent snake_case = batch_size snake_case = image_size snake_case = num_channels snake_case = num_encoder_blocks snake_case = sr_ratios snake_case = depths snake_case = hidden_sizes snake_case = downsampling_rates snake_case = num_attention_heads snake_case = is_training snake_case = use_labels snake_case = hidden_act snake_case = hidden_dropout_prob snake_case = attention_probs_dropout_prob snake_case = initializer_range snake_case = num_labels snake_case = scope def snake_case ( self ): """simple docstring""" snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case = None if self.use_labels: snake_case = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case = self.get_config() return config, pixel_values, labels def snake_case ( self ): """simple docstring""" return SegformerConfig( image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" snake_case = SegformerModel(config=_a ) model.to(_a ) model.eval() snake_case = model(_a ) snake_case = self.image_size // (self.downsampling_rates[-1] * 2) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" snake_case = self.num_labels snake_case = SegformerForSemanticSegmentation(_a ) model.to(_a ) model.eval() snake_case = model(_a ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) snake_case = model(_a , labels=_a ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) self.parent.assertGreater(result.loss , 0.0 ) def snake_case ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" snake_case = 1 snake_case = SegformerForSemanticSegmentation(config=_a ) model.to(_a ) model.eval() snake_case = torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size) ).to(_a ) snake_case = model(_a , labels=_a ) self.parent.assertGreater(result.loss , 0.0 ) def snake_case ( self ): """simple docstring""" snake_case = self.prepare_config_and_inputs() snake_case = config_and_inputs snake_case = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase_ ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): """simple docstring""" _lowerCAmelCase : int = ( ( SegformerModel, SegformerForSemanticSegmentation, SegformerForImageClassification, ) if is_torch_available() else () ) _lowerCAmelCase : Dict = ( { """feature-extraction""": SegformerModel, """image-classification""": SegformerForImageClassification, """image-segmentation""": SegformerForSemanticSegmentation, } if is_torch_available() else {} ) _lowerCAmelCase : List[Any] = True _lowerCAmelCase : Tuple = False _lowerCAmelCase : str = False _lowerCAmelCase : List[str] = False def snake_case ( self ): """simple docstring""" snake_case = SegformerModelTester(self ) snake_case = SegformerConfigTester(self , config_class=_a ) def snake_case ( self ): """simple docstring""" self.config_tester.run_common_tests() def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_binary_image_segmentation(*_a ) def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_segmentation(*_a ) @unittest.skip('SegFormer does not use inputs_embeds' ) def snake_case ( self ): """simple docstring""" pass @unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods' ) def snake_case ( self ): """simple docstring""" pass def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case = model_class(_a ) snake_case = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case = [*signature.parameters.keys()] snake_case = ["pixel_values"] self.assertListEqual(arg_names[:1] , _a ) def snake_case ( self ): """simple docstring""" snake_case = self.model_tester.prepare_config_and_inputs_for_common() snake_case = True for model_class in self.all_model_classes: snake_case = True snake_case = False snake_case = True snake_case = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): snake_case = model(**self._prepare_for_class(_a , _a ) ) snake_case = outputs.attentions snake_case = sum(self.model_tester.depths ) self.assertEqual(len(_a ) , _a ) # check that output_attentions also work using config del inputs_dict["output_attentions"] snake_case = True snake_case = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): snake_case = model(**self._prepare_for_class(_a , _a ) ) snake_case = outputs.attentions self.assertEqual(len(_a ) , _a ) # verify the first attentions (first block, first layer) snake_case = (self.model_tester.image_size // 4) ** 2 snake_case = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) # verify the last attentions (last block, last layer) snake_case = (self.model_tester.image_size // 32) ** 2 snake_case = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2 self.assertListEqual( list(attentions[-1].shape[-3:] ) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , ) snake_case = len(_a ) # Check attention is always last and order is fine snake_case = True snake_case = True snake_case = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): snake_case = model(**self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + 1 , len(_a ) ) snake_case = outputs.attentions self.assertEqual(len(_a ) , _a ) # verify the first attentions (first block, first layer) snake_case = (self.model_tester.image_size // 4) ** 2 snake_case = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) def snake_case ( self ): """simple docstring""" def check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): snake_case = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): snake_case = model(**self._prepare_for_class(_a , _a ) ) snake_case = outputs.hidden_states snake_case = self.model_tester.num_encoder_blocks self.assertEqual(len(_a ) , _a ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.hidden_sizes[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case = True check_hidden_states_output(_a , _a , _a ) def snake_case ( self ): """simple docstring""" if not self.model_tester.is_training: return snake_case = self.model_tester.prepare_config_and_inputs_for_common() snake_case = True for model_class in self.all_model_classes: if model_class in get_values(_a ): continue snake_case = model_class(_a ) model.to(_a ) model.train() snake_case = self._prepare_for_class(_a , _a , return_labels=_a ) snake_case = model(**_a ).loss loss.backward() @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def snake_case ( self ): """simple docstring""" pass @slow def snake_case ( self ): """simple docstring""" for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case = SegformerModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def lowerCAmelCase__ ( ) -> Tuple: """simple docstring""" snake_case = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def snake_case ( self ): """simple docstring""" snake_case = SegformerImageProcessor( image_scale=(5_12, 5_12) , keep_ratio=_a , align=_a , do_random_crop=_a ) snake_case = SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512' ).to( _a ) snake_case = prepare_img() snake_case = image_processor(images=_a , return_tensors='pt' ) snake_case = encoded_inputs.pixel_values.to(_a ) with torch.no_grad(): snake_case = model(_a ) snake_case = torch.Size((1, model.config.num_labels, 1_28, 1_28) ) self.assertEqual(outputs.logits.shape , _a ) snake_case = torch.tensor( [ [[-4.63_10, -5.52_32, -6.23_56], [-5.19_21, -6.14_44, -6.59_96], [-5.44_24, -6.27_90, -6.75_74]], [[-12.13_91, -13.31_22, -13.95_54], [-12.87_32, -13.93_52, -14.35_63], [-12.94_38, -13.82_26, -14.25_13]], [[-12.51_34, -13.46_86, -14.49_15], [-12.86_69, -14.43_43, -14.77_58], [-13.25_23, -14.58_19, -15.06_94]], ] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , _a , atol=1E-4 ) ) @slow def snake_case ( self ): """simple docstring""" snake_case = SegformerImageProcessor( image_scale=(5_12, 5_12) , keep_ratio=_a , align=_a , do_random_crop=_a ) snake_case = SegformerForSemanticSegmentation.from_pretrained( 'nvidia/segformer-b1-finetuned-cityscapes-1024-1024' ).to(_a ) snake_case = prepare_img() snake_case = image_processor(images=_a , return_tensors='pt' ) snake_case = encoded_inputs.pixel_values.to(_a ) with torch.no_grad(): snake_case = model(_a ) snake_case = torch.Size((1, model.config.num_labels, 1_28, 1_28) ) self.assertEqual(outputs.logits.shape , _a ) snake_case = torch.tensor( [ [[-13.57_48, -13.91_11, -12.65_00], [-14.35_00, -15.36_83, -14.23_28], [-14.75_32, -16.04_24, -15.60_87]], [[-17.16_51, -15.87_25, -12.96_53], [-17.25_80, -17.37_18, -14.82_23], [-16.60_58, -16.87_83, -16.74_52]], [[-3.64_56, -3.02_09, -1.42_03], [-3.07_97, -3.19_59, -2.00_00], [-1.87_57, -1.92_17, -1.69_97]], ] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , _a , atol=1E-1 ) ) @slow def snake_case ( self ): """simple docstring""" snake_case = SegformerImageProcessor( image_scale=(5_12, 5_12) , keep_ratio=_a , align=_a , do_random_crop=_a ) snake_case = SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512' ).to( _a ) snake_case = prepare_img() snake_case = image_processor(images=_a , return_tensors='pt' ) snake_case = encoded_inputs.pixel_values.to(_a ) with torch.no_grad(): snake_case = model(_a ) snake_case = outputs.logits.detach().cpu() snake_case = image_processor.post_process_semantic_segmentation(outputs=_a , target_sizes=[(5_00, 3_00)] ) snake_case = torch.Size((5_00, 3_00) ) self.assertEqual(segmentation[0].shape , _a ) snake_case = image_processor.post_process_semantic_segmentation(outputs=_a ) snake_case = torch.Size((1_28, 1_28) ) self.assertEqual(segmentation[0].shape , _a )
150
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def lowerCAmelCase_ ( _snake_case : List[Any] ) -> List[Any]: '''simple docstring''' assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ) -> Tuple: '''simple docstring''' assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : Dict = "mock-s3-bucket" __magic_name__ : Any = F'''s3://{mock_bucket}''' __magic_name__ : str = extract_path_from_uri(_snake_case ) assert dataset_path.startswith("s3://" ) is False __magic_name__ : Tuple = "./local/path" __magic_name__ : Optional[Any] = extract_path_from_uri(_snake_case ) assert dataset_path == new_dataset_path def lowerCAmelCase_ ( _snake_case : List[str] ) -> Optional[Any]: '''simple docstring''' __magic_name__ : str = is_remote_filesystem(_snake_case ) assert is_remote is True __magic_name__ : Optional[int] = fsspec.filesystem("file" ) __magic_name__ : int = is_remote_filesystem(_snake_case ) assert is_remote is False @pytest.mark.parametrize("compression_fs_class" , _snake_case ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : Optional[Any] , _snake_case : int , _snake_case : Tuple , _snake_case : Any , _snake_case : Union[str, Any] , _snake_case : Any ) -> int: '''simple docstring''' __magic_name__ : Any = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_file, "bz2": bza_file, "lz4": lza_file} __magic_name__ : str = input_paths[compression_fs_class.protocol] if input_path is None: __magic_name__ : Dict = F'''for \'{compression_fs_class.protocol}\' compression protocol, ''' if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_snake_case ) __magic_name__ : str = fsspec.filesystem(compression_fs_class.protocol , fo=_snake_case ) assert isinstance(_snake_case , _snake_case ) __magic_name__ : int = os.path.basename(_snake_case ) __magic_name__ : Optional[int] = expected_filename[: expected_filename.rindex("." )] assert fs.glob("*" ) == [expected_filename] with fs.open(_snake_case , "r" , encoding="utf-8" ) as f, open(_snake_case , encoding="utf-8" ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize("protocol" , ["zip", "gzip"] ) def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : Optional[Any] , _snake_case : Optional[Any] ) -> str: '''simple docstring''' __magic_name__ : int = {"zip": zip_jsonl_path, "gzip": jsonl_gz_path} __magic_name__ : int = compressed_file_paths[protocol] __magic_name__ : Tuple = "dataset.jsonl" __magic_name__ : List[str] = F'''{protocol}://{member_file_path}::{compressed_file_path}''' __magic_name__ , *__magic_name__ : Optional[Any] = fsspec.get_fs_token_paths(_snake_case ) assert fs.isfile(_snake_case ) assert not fs.isfile("non_existing_" + member_file_path ) @pytest.mark.integration def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Dict , _snake_case : List[str] , _snake_case : Tuple ) -> str: '''simple docstring''' __magic_name__ : int = hf_api.dataset_info(_snake_case , token=_snake_case ) __magic_name__ : Optional[Any] = HfFileSystem(repo_info=_snake_case , token=_snake_case ) assert sorted(hffs.glob("*" ) ) == [".gitattributes", "data"] assert hffs.isdir("data" ) assert hffs.isfile(".gitattributes" ) and hffs.isfile("data/text_data.txt" ) with open(_snake_case ) as f: assert hffs.open("data/text_data.txt" , "r" ).read() == f.read() def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' __magic_name__ : Optional[Any] = "bz2" # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(_snake_case , _snake_case , clobber=_snake_case ) with pytest.warns(_snake_case ) as warning_info: importlib.reload(datasets.filesystems ) assert len(_snake_case ) == 1 assert ( str(warning_info[0].message ) == F'''A filesystem protocol was already set for {protocol} and will be overwritten.''' )
281
0
"""simple docstring""" from __future__ import annotations from collections import namedtuple def _snake_case ( lowerCamelCase__ : float , lowerCamelCase__ : float , lowerCamelCase__ : float ) -> tuple: lowerCamelCase_ : Optional[Any] =namedtuple("result" , "name value" ) if (voltage, current, power).count(0 ) != 1: raise ValueError("Only one argument must be 0" ) elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return result("voltage" , power / current ) elif current == 0: return result("current" , power / voltage ) elif power == 0: return result("power" , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
369
"""simple docstring""" import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline A__ : int = { 'n_samples': 64, 'horizon': 32, 'num_inference_steps': 20, 'n_guide_steps': 2, # can set to 0 for faster sampling, does not use value network 'scale_grad_by_std': True, 'scale': 0.1, 'eta': 0.0, 't_grad_cutoff': 2, 'device': 'cpu', } if __name__ == "__main__": A__ : str = 'hopper-medium-v2' A__ : Dict = gym.make(env_name) A__ : List[Any] = ValueGuidedRLPipeline.from_pretrained( 'bglick13/hopper-medium-v2-value-function-hor32', env=env, ) env.seed(0) A__ : Dict = env.reset() A__ : Optional[int] = 0 A__ : str = 0 A__ : List[Any] = 1_000 A__ : Tuple = [obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy A__ : Union[str, Any] = pipeline(obs, planning_horizon=32) # execute action in environment A__ , A__ , A__ , A__ : Any = env.step(denorm_actions) A__ : List[Any] = env.get_normalized_score(total_reward) # update return total_reward += reward total_score += score print( f'Step: {t}, Reward: {reward}, Total Reward: {total_reward}, Score: {score}, Total Score:' f' {total_score}' ) # save observations for rendering rollout.append(next_observation.copy()) A__ : Optional[Any] = next_observation except KeyboardInterrupt: pass print(f'Total reward: {total_reward}')
209
0
from collections import namedtuple import requests from lxml import html # type: ignore _SCREAMING_SNAKE_CASE = namedtuple("""covid_data""", """cases deaths recovered""") def SCREAMING_SNAKE_CASE__ ( __a = "https://www.worldometers.info/coronavirus/" ): snake_case_ : Union[str, Any] = '//div[@class = "maincounter-number"]/span/text()' return covid_data(*html.fromstring(requests.get(__a ).content ).xpath(__a ) ) _SCREAMING_SNAKE_CASE = """Total COVID-19 cases in the world: {} Total deaths due to COVID-19 in the world: {} Total COVID-19 patients recovered in the world: {}""" print(fmt.format(*covid_stats()))
327
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(""">=""", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType _SCREAMING_SNAKE_CASE = get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( __a , __a , __a , __a , __a=0 ): os.makedirs(__a , exist_ok=__a ) with FSDP.state_dict_type( __a , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): snake_case_ : Dict = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: snake_case_ : Optional[int] = f"""{MODEL_NAME}.bin""" if model_index == 0 else f"""{MODEL_NAME}_{model_index}.bin""" snake_case_ : Dict = os.path.join(__a , __a ) if accelerator.process_index == 0: logger.info(f"""Saving model to {output_model_file}""" ) torch.save(__a , __a ) logger.info(f"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: snake_case_ : Dict = ( f"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else f"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) snake_case_ : Dict = os.path.join(__a , __a ) logger.info(f"""Saving model to {output_model_file}""" ) torch.save(__a , __a ) logger.info(f"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: snake_case_ : Optional[int] = os.path.join(__a , f"""{MODEL_NAME}_{model_index}""" ) os.makedirs(__a , exist_ok=__a ) logger.info(f"""Saving model to {ckpt_dir}""" ) snake_case_ : int = {'model': state_dict} dist_cp.save_state_dict( state_dict=__a , storage_writer=dist_cp.FileSystemWriter(__a ) , planner=DefaultSavePlanner() , ) logger.info(f"""Model saved to {ckpt_dir}""" ) def SCREAMING_SNAKE_CASE__ ( __a , __a , __a , __a , __a=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( __a , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(__a ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( 'Set the `sync_module_states` flag to `True` so that model states are synced across processes when ' 'initializing FSDP object' ) return snake_case_ : Optional[int] = f"""{MODEL_NAME}.bin""" if model_index == 0 else f"""{MODEL_NAME}_{model_index}.bin""" snake_case_ : Optional[Any] = os.path.join(__a , __a ) logger.info(f"""Loading model from {input_model_file}""" ) snake_case_ : Optional[Any] = torch.load(__a ) logger.info(f"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: snake_case_ : Optional[Any] = ( f"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else f"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) snake_case_ : Tuple = os.path.join(__a , __a ) logger.info(f"""Loading model from {input_model_file}""" ) snake_case_ : Optional[int] = torch.load(__a ) logger.info(f"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: snake_case_ : Tuple = ( os.path.join(__a , f"""{MODEL_NAME}_{model_index}""" ) if f"""{MODEL_NAME}""" not in input_dir else input_dir ) logger.info(f"""Loading model from {ckpt_dir}""" ) snake_case_ : List[Any] = {'model': model.state_dict()} dist_cp.load_state_dict( state_dict=__a , storage_reader=dist_cp.FileSystemReader(__a ) , planner=DefaultLoadPlanner() , ) snake_case_ : Any = state_dict['model'] logger.info(f"""Model loaded from {ckpt_dir}""" ) model.load_state_dict(__a ) def SCREAMING_SNAKE_CASE__ ( __a , __a , __a , __a , __a , __a=0 ): os.makedirs(__a , exist_ok=__a ) with FSDP.state_dict_type( __a , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): snake_case_ : List[str] = FSDP.optim_state_dict(__a , __a ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: snake_case_ : str = ( f"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else f"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) snake_case_ : Any = os.path.join(__a , __a ) logger.info(f"""Saving Optimizer state to {output_optimizer_file}""" ) torch.save(__a , __a ) logger.info(f"""Optimizer state saved in {output_optimizer_file}""" ) else: snake_case_ : Optional[int] = os.path.join(__a , f"""{OPTIMIZER_NAME}_{optimizer_index}""" ) os.makedirs(__a , exist_ok=__a ) logger.info(f"""Saving Optimizer state to {ckpt_dir}""" ) dist_cp.save_state_dict( state_dict={'optimizer': optim_state} , storage_writer=dist_cp.FileSystemWriter(__a ) , planner=DefaultSavePlanner() , ) logger.info(f"""Optimizer state saved in {ckpt_dir}""" ) def SCREAMING_SNAKE_CASE__ ( __a , __a , __a , __a , __a , __a=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( __a , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: snake_case_ : Optional[Any] = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: snake_case_ : Union[str, Any] = ( f"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else f"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) snake_case_ : List[Any] = os.path.join(__a , __a ) logger.info(f"""Loading Optimizer state from {input_optimizer_file}""" ) snake_case_ : Optional[int] = torch.load(__a ) logger.info(f"""Optimizer state loaded from {input_optimizer_file}""" ) else: snake_case_ : str = ( os.path.join(__a , f"""{OPTIMIZER_NAME}_{optimizer_index}""" ) if f"""{OPTIMIZER_NAME}""" not in input_dir else input_dir ) logger.info(f"""Loading Optimizer from {ckpt_dir}""" ) snake_case_ : Any = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key='optimizer' , storage_reader=dist_cp.FileSystemReader(__a ) , ) snake_case_ : Optional[int] = optim_state['optimizer'] logger.info(f"""Optimizer loaded from {ckpt_dir}""" ) snake_case_ : Optional[Any] = FSDP.optim_state_dict_to_load(__a , __a , __a ) optimizer.load_state_dict(__a )
327
1
from collections import defaultdict def UpperCAmelCase_ ( _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = True for v in tree[start]: if v not in visited: ret += dfs(lowerCAmelCase__ ) if ret % 2 == 0: cuts.append(lowerCAmelCase__ ) return ret def UpperCAmelCase_ ( ): '''simple docstring''' dfs(1 ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : List[str] = 10, 9 _SCREAMING_SNAKE_CASE : Union[str, Any] = defaultdict(list) _SCREAMING_SNAKE_CASE : dict[int, bool] = {} _SCREAMING_SNAKE_CASE : list[int] = [] _SCREAMING_SNAKE_CASE : Optional[int] = 0 _SCREAMING_SNAKE_CASE : Any = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
360
import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class UpperCAmelCase__ ( A__ ): """simple docstring""" def __init__( self : List[str] , __lowerCamelCase : Tuple=0.01 , __lowerCamelCase : Optional[Any]=1000 ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ = p_stop SCREAMING_SNAKE_CASE__ = max_length def __iter__( self : List[str] ) -> Optional[Any]: SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = False while not stop and count < self.max_length: yield count count += 1 SCREAMING_SNAKE_CASE__ = random.random() < self.p_stop class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def lowercase_ ( self : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : Any=False , __lowerCamelCase : Optional[int]=True ) -> Dict: SCREAMING_SNAKE_CASE__ = [ BatchSamplerShard(__lowerCamelCase , 2 , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) for i in range(2 ) ] SCREAMING_SNAKE_CASE__ = [list(__lowerCamelCase ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(__lowerCamelCase ) for shard in batch_sampler_shards] , [len(__lowerCamelCase ) for e in expected] ) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) def lowercase_ ( self : Any ) -> Optional[Any]: # Check the shards when the dataset is a round multiple of total batch size. SCREAMING_SNAKE_CASE__ = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. SCREAMING_SNAKE_CASE__ = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. SCREAMING_SNAKE_CASE__ = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. SCREAMING_SNAKE_CASE__ = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) # Check the shards when the dataset is very small. SCREAMING_SNAKE_CASE__ = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase ) def lowercase_ ( self : Optional[int] ) -> int: # Check the shards when the dataset is a round multiple of batch size. SCREAMING_SNAKE_CASE__ = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size. SCREAMING_SNAKE_CASE__ = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. SCREAMING_SNAKE_CASE__ = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. SCREAMING_SNAKE_CASE__ = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase ) def lowercase_ ( self : str ) -> Dict: # Check the shards when the dataset is a round multiple of total batch size. SCREAMING_SNAKE_CASE__ = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(24 ) , batch_size=3 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. SCREAMING_SNAKE_CASE__ = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(21 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. SCREAMING_SNAKE_CASE__ = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(22 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. SCREAMING_SNAKE_CASE__ = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(20 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. SCREAMING_SNAKE_CASE__ = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [[[0, 1]], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(2 ) , batch_size=3 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , even_batches=__lowerCamelCase ) def lowercase_ ( self : List[str] ) -> Tuple: # Check the shards when the dataset is a round multiple of batch size. SCREAMING_SNAKE_CASE__ = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(24 ) , batch_size=4 , drop_last=__lowerCamelCase ) # Expected shouldn't change self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size. SCREAMING_SNAKE_CASE__ = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(22 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. SCREAMING_SNAKE_CASE__ = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(21 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) # Check the shards when the dataset is very small. SCREAMING_SNAKE_CASE__ = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [[[0, 1]], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = BatchSampler(range(2 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [[], []] self.check_batch_sampler_shards(__lowerCamelCase , __lowerCamelCase , split_batches=__lowerCamelCase , even_batches=__lowerCamelCase ) def lowercase_ ( self : Optional[int] ) -> List[str]: SCREAMING_SNAKE_CASE__ = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] SCREAMING_SNAKE_CASE__ = [BatchSamplerShard(__lowerCamelCase , 2 , __lowerCamelCase , even_batches=__lowerCamelCase ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [12, 13]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 10, 11]] ) def lowercase_ ( self : Optional[Any] , __lowerCamelCase : Any , __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : Tuple=False , __lowerCamelCase : Optional[int]=2 , __lowerCamelCase : Dict=False ) -> str: random.seed(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = list(__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = [ IterableDatasetShard( __lowerCamelCase , batch_size=__lowerCamelCase , drop_last=__lowerCamelCase , num_processes=__lowerCamelCase , process_index=__lowerCamelCase , split_batches=__lowerCamelCase , ) for i in range(__lowerCamelCase ) ] SCREAMING_SNAKE_CASE__ = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(__lowerCamelCase ) iterable_dataset_lists.append(list(__lowerCamelCase ) ) SCREAMING_SNAKE_CASE__ = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size SCREAMING_SNAKE_CASE__ = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) self.assertTrue(len(__lowerCamelCase ) % shard_batch_size == 0 ) SCREAMING_SNAKE_CASE__ = [] for idx in range(0 , len(__lowerCamelCase ) , __lowerCamelCase ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(__lowerCamelCase ) < len(__lowerCamelCase ): reference += reference self.assertListEqual(__lowerCamelCase , reference[: len(__lowerCamelCase )] ) def lowercase_ ( self : str ) -> Dict: SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = RandomIterableDataset() self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) # Edge case with a very small dataset SCREAMING_SNAKE_CASE__ = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) self.check_iterable_dataset_shards(__lowerCamelCase , __lowerCamelCase , batch_size=4 , drop_last=__lowerCamelCase , split_batches=__lowerCamelCase ) def lowercase_ ( self : Optional[Any] ) -> Any: SCREAMING_SNAKE_CASE__ = BatchSampler(range(16 ) , batch_size=4 , drop_last=__lowerCamelCase ) SCREAMING_SNAKE_CASE__ = SkipBatchSampler(__lowerCamelCase , 2 ) self.assertListEqual(list(__lowerCamelCase ) , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def lowercase_ ( self : Union[str, Any] ) -> str: SCREAMING_SNAKE_CASE__ = SkipDataLoader(list(range(16 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def lowercase_ ( self : Dict ) -> List[Any]: SCREAMING_SNAKE_CASE__ = DataLoader(list(range(16 ) ) , batch_size=4 ) SCREAMING_SNAKE_CASE__ = skip_first_batches(__lowerCamelCase , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def lowercase_ ( self : List[Any] ) -> List[str]: SCREAMING_SNAKE_CASE__ = DataLoaderShard(list(range(16 ) ) , batch_size=4 ) for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def lowercase_ ( self : Union[str, Any] ) -> str: Accelerator() SCREAMING_SNAKE_CASE__ = DataLoaderDispatcher(range(16 ) , batch_size=4 ) for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(__lowerCamelCase ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
218
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 SCREAMING_SNAKE_CASE : int = logging.getLogger(__name__) SCREAMING_SNAKE_CASE : Dict = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) SCREAMING_SNAKE_CASE : Any = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _UpperCAmelCase : '''simple docstring''' lowerCamelCase__ =field( default=__snake_case, metadata={ 'help': ( 'The model checkpoint for weights initialization. Leave None if you want to train a model from' ' scratch.' ) }, ) lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(__snake_case )}, ) lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}, ) @dataclass class _UpperCAmelCase : '''simple docstring''' lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'The input training data file (a text file).'} ) lowerCamelCase__ =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' ) }, ) lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'}, ) lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'An optional input train ref data file for whole word mask in Chinese.'}, ) lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'An optional input eval ref data file for whole word mask in Chinese.'}, ) lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'Whether distinct lines of text in the dataset are to be handled as distinct sequences.'}, ) lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'Train with masked-language modeling loss instead of language modeling.'} ) lowerCamelCase__ =field(default=__snake_case, metadata={'help': 'Whether ot not to use whole word mask.'} ) lowerCamelCase__ =field( default=0.1_5, metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} ) lowerCamelCase__ =field( default=1 / 6, metadata={ 'help': ( 'Ratio of length of a span of masked tokens to surrounding context length for permutation language' ' modeling.' ) }, ) lowerCamelCase__ =field( default=5, metadata={'help': 'Maximum length of a span of masked tokens for permutation language modeling.'} ) lowerCamelCase__ =field( default=-1, metadata={ 'help': ( 'Optional input sequence length after tokenization.' 'The training dataset will be truncated in block of this size for training.' 'Default to the model max input length for single sentence inputs (take into account special tokens).' ) }, ) lowerCamelCase__ =field( default=__snake_case, metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def lowercase ( _snake_case : DataTrainingArguments , _snake_case : PreTrainedTokenizer , _snake_case : bool = False , _snake_case : Optional[str] = None , ) ->Any: """simple docstring""" def _dataset(_snake_case : List[Any] , _snake_case : str=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=_snake_case , file_path=_snake_case , block_size=args.block_size , ref_path=_snake_case , ) return LineByLineTextDataset(tokenizer=_snake_case , file_path=_snake_case , block_size=args.block_size ) else: return TextDataset( tokenizer=_snake_case , file_path=_snake_case , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=_snake_case , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(_snake_case ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def lowercase ( ) ->List[Any]: """simple docstring""" __snake_case : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) __snake_case , __snake_case , __snake_case : Union[str, Any] = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( '''Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file ''' '''or remove the --do_eval argument.''' ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , _snake_case ) # 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: __snake_case : Optional[Any] = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: __snake_case : Optional[Any] = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: __snake_case : Tuple = CONFIG_MAPPING[model_args.model_type]() logger.warning('''You are instantiating a new config instance from scratch.''' ) if model_args.tokenizer_name: __snake_case : Dict = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: __snake_case : List[Any] = 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: __snake_case : int = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=_snake_case , cache_dir=model_args.cache_dir , ) else: logger.info('''Training new model from scratch''' ) __snake_case : List[Any] = AutoModelWithLMHead.from_config(_snake_case ) model.resize_token_embeddings(len(_snake_case ) ) 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: __snake_case : List[str] = tokenizer.max_len # Our input block size will be the max possible for the model else: __snake_case : Optional[int] = min(data_args.block_size , tokenizer.max_len ) # Get datasets __snake_case : Optional[Any] = ( get_dataset(_snake_case , tokenizer=_snake_case , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) __snake_case : Any = ( get_dataset(_snake_case , tokenizer=_snake_case , evaluate=_snake_case , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": __snake_case : List[Any] = DataCollatorForPermutationLanguageModeling( tokenizer=_snake_case , 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: __snake_case : Optional[Any] = DataCollatorForWholeWordMask( tokenizer=_snake_case , mlm_probability=data_args.mlm_probability ) else: __snake_case : Union[str, Any] = DataCollatorForLanguageModeling( tokenizer=_snake_case , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer __snake_case : Optional[int] = Trainer( model=_snake_case , args=_snake_case , data_collator=_snake_case , train_dataset=_snake_case , eval_dataset=_snake_case , prediction_loss_only=_snake_case , ) # Training if training_args.do_train: __snake_case : Dict = ( 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=_snake_case ) 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 __snake_case : int = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __snake_case : Dict = trainer.evaluate() __snake_case : Dict = math.exp(eval_output['''eval_loss'''] ) __snake_case : List[Any] = {'''perplexity''': perplexity} __snake_case : str = os.path.join(training_args.output_dir , '''eval_results_lm.txt''' ) if trainer.is_world_master(): with open(_snake_case , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key in sorted(result.keys() ): logger.info(''' %s = %s''' , _snake_case , str(result[key] ) ) writer.write('''%s = %s\n''' % (key, str(result[key] )) ) results.update(_snake_case ) return results def lowercase ( _snake_case : Optional[int] ) ->Tuple: """simple docstring""" main() if __name__ == "__main__": main()
102
def lowerCAmelCase__( lowercase : int = 100_0000 ) -> int: __snake_case : List[Any] = limit + 1 __snake_case : List[str] = [0] * limit for first_term in range(1 , lowercase ): for n in range(lowercase , lowercase , lowercase ): __snake_case : Union[str, Any] = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a __snake_case : Tuple = sum(1 for x in frequency[1:limit] if x == 10 ) return count if __name__ == "__main__": print(F'''{solution() = }''')
326
0
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class SCREAMING_SNAKE_CASE__ ( _lowercase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' UpperCAmelCase : List[Any] = parent UpperCAmelCase : Optional[int] = config_class UpperCAmelCase : Dict = has_text_modality UpperCAmelCase : Any = kwargs UpperCAmelCase : Tuple = common_properties def SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' UpperCAmelCase : str = self.config_class(**self.inputs_dict ) UpperCAmelCase : Any = ( ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["""vocab_size"""] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(__UpperCamelCase , __UpperCamelCase ) , msg=F"`{prop}` does not exist" ) # Test that config has the common properties as setter for idx, name in enumerate(__UpperCamelCase ): try: setattr(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) self.parent.assertEqual( getattr(__UpperCamelCase , __UpperCamelCase ) , __UpperCamelCase , msg=F"`{name} value {idx} expected, but was {getattr(__UpperCamelCase , __UpperCamelCase )}" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(__UpperCamelCase ): try: UpperCAmelCase : Optional[int] = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(__UpperCamelCase , __UpperCamelCase ) , __UpperCamelCase , msg=F"`{name} value {idx} expected, but was {getattr(__UpperCamelCase , __UpperCamelCase )}" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' UpperCAmelCase : List[str] = self.config_class(**self.inputs_dict ) UpperCAmelCase : List[Any] = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , __UpperCamelCase ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: '''simple docstring''' UpperCAmelCase : int = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase : Optional[int] = os.path.join(__UpperCamelCase , """config.json""" ) config_first.to_json_file(__UpperCamelCase ) UpperCAmelCase : Tuple = self.config_class.from_json_file(__UpperCamelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' UpperCAmelCase : List[str] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(__UpperCamelCase ) UpperCAmelCase : Any = self.config_class.from_pretrained(__UpperCamelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def SCREAMING_SNAKE_CASE ( self ) -> Any: '''simple docstring''' UpperCAmelCase : Union[str, Any] = self.config_class(**self.inputs_dict ) UpperCAmelCase : List[Any] = """test""" with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase : str = os.path.join(__UpperCamelCase , __UpperCamelCase ) config_first.save_pretrained(__UpperCamelCase ) UpperCAmelCase : Any = self.config_class.from_pretrained(__UpperCamelCase , subfolder=__UpperCamelCase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' UpperCAmelCase : Dict = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) UpperCAmelCase : Any = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' if self.config_class.is_composition: return UpperCAmelCase : List[str] = self.config_class() self.parent.assertIsNotNone(__UpperCamelCase ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: '''simple docstring''' UpperCAmelCase : Any = copy.deepcopy(__UpperCamelCase ) UpperCAmelCase : Any = self.config_class(**__UpperCamelCase ) UpperCAmelCase : Tuple = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa) ) elif getattr(__UpperCamelCase , __UpperCamelCase ) != value: wrong_values.append((key, getattr(__UpperCamelCase , __UpperCamelCase ), value) ) if len(__UpperCamelCase ) > 0: UpperCAmelCase : Union[str, Any] = """\n""".join([F"- {v[0]}: got {v[1]} instead of {v[2]}" for v in wrong_values] ) raise ValueError(F"The following keys were not properly set in the config:\n{errors}" ) def SCREAMING_SNAKE_CASE ( self ) -> int: '''simple docstring''' self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
360
"""simple docstring""" from __future__ import annotations from decimal import Decimal from numpy import array def _snake_case ( UpperCamelCase : list[list[float]] ): UpperCAmelCase : int = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(UpperCamelCase ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix UpperCAmelCase : Union[str, Any] = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creates a copy of the matrix with swapped positions of the elements UpperCAmelCase : Dict = [[0.0, 0.0], [0.0, 0.0]] UpperCAmelCase , UpperCAmelCase : Dict = matrix[1][1], matrix[0][0] UpperCAmelCase , UpperCAmelCase : Optional[Any] = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(UpperCamelCase ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(UpperCamelCase ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule UpperCAmelCase : Optional[int] = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creating cofactor matrix UpperCAmelCase : List[Any] = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] UpperCAmelCase : Dict = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) UpperCAmelCase : List[Any] = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) UpperCAmelCase : int = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) UpperCAmelCase : Dict = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) UpperCAmelCase : Optional[int] = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) UpperCAmelCase : Optional[Any] = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) UpperCAmelCase : Optional[Any] = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) UpperCAmelCase : str = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) UpperCAmelCase : Optional[Any] = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) UpperCAmelCase : Any = array(UpperCamelCase ) for i in range(3 ): for j in range(3 ): UpperCAmelCase : Optional[int] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix UpperCAmelCase : int = array(UpperCamelCase ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(UpperCamelCase ) # Calculate the inverse of the matrix return [[float(d(UpperCamelCase ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("""Please provide a matrix of size 2x2 or 3x3.""" )
76
0
from __future__ import annotations import matplotlib.pyplot as plt # type: ignore import numpy # initial triangle of Koch snowflake lowerCAmelCase_ = numpy.array([0, 0]) lowerCAmelCase_ = numpy.array([0.5, 0.8_6_6_0_2_5_4]) lowerCAmelCase_ = numpy.array([1, 0]) lowerCAmelCase_ = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1] def snake_case( __magic_name__ , __magic_name__ ) -> list[numpy.ndarray]: '''simple docstring''' lowercase : List[Any] = initial_vectors for _ in range(__magic_name__ ): lowercase : int = iteration_step(__magic_name__ ) return vectors def snake_case( __magic_name__ ) -> list[numpy.ndarray]: '''simple docstring''' lowercase : List[Any] = [] for i, start_vector in enumerate(vectors[:-1] ): lowercase : List[str] = vectors[i + 1] new_vectors.append(__magic_name__ ) lowercase : Any = end_vector - start_vector new_vectors.append(start_vector + difference_vector / 3 ) new_vectors.append( start_vector + difference_vector / 3 + rotate(difference_vector / 3 , 60 ) ) new_vectors.append(start_vector + difference_vector * 2 / 3 ) new_vectors.append(vectors[-1] ) return new_vectors def snake_case( __magic_name__ , __magic_name__ ) -> numpy.ndarray: '''simple docstring''' lowercase : str = numpy.radians(__magic_name__ ) lowercase , lowercase : Optional[Any] = numpy.cos(__magic_name__ ), numpy.sin(__magic_name__ ) lowercase : Union[str, Any] = numpy.array(((c, -s), (s, c)) ) return numpy.dot(__magic_name__ , __magic_name__ ) def snake_case( __magic_name__ ) -> None: '''simple docstring''' lowercase : Optional[int] = plt.gca() axes.set_aspect('''equal''' ) # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all # y-coordinates as inputs, which are constructed from the vector-list using # zip() lowercase , lowercase : Optional[Any] = zip(*__magic_name__ ) plt.plot(__magic_name__ , __magic_name__ ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase_ = iterate(INITIAL_VECTORS, 5) plot(processed_vectors)
308
from heapq import heappop, heappush import numpy as np def snake_case( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , ) -> tuple[float | int, list[tuple[int, int]]]: '''simple docstring''' lowercase , lowercase : Optional[int] = grid.shape lowercase : Optional[int] = [-1, 1, 0, 0] lowercase : List[str] = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] lowercase , lowercase : Union[str, Any] = [(0, source)], set() lowercase : List[str] = np.full((rows, cols) , np.inf ) lowercase : Dict = 0 lowercase : Dict = np.empty((rows, cols) , dtype=__magic_name__ ) lowercase : Any = None while queue: ((lowercase) , (lowercase)) : Optional[Any] = heappop(__magic_name__ ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: lowercase : Tuple = [] while (x, y) != source: path.append((x, y) ) lowercase , lowercase : Optional[int] = predecessors[x, y] path.append(__magic_name__ ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(__magic_name__ ) ): lowercase , lowercase : Optional[int] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: lowercase : List[Any] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(__magic_name__ , (dist + 1, (nx, ny)) ) lowercase : int = dist + 1 lowercase : Optional[Any] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
308
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowercase : str = {'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTConfig', 'DeiTOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Union[str, Any] = ['DeiTFeatureExtractor'] _lowercase : Any = ['DeiTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[int] = [ 'DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DeiTForImageClassification', 'DeiTForImageClassificationWithTeacher', 'DeiTForMaskedImageModeling', 'DeiTModel', 'DeiTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[Any] = [ 'TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDeiTForImageClassification', 'TFDeiTForImageClassificationWithTeacher', 'TFDeiTForMaskedImageModeling', 'TFDeiTModel', 'TFDeiTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys _lowercase : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
359
"""simple docstring""" def lowercase__ ( snake_case_ :int , snake_case_ :int , snake_case_ :int ): __UpperCAmelCase = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def lowercase__ ( ): print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
def A__ ( __lowerCamelCase ): if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(__lowerCamelCase, __lowerCamelCase ): raise TypeError('''Input value must be a \'int\' type''' ) return bin(__lowerCamelCase ).count('''1''' ) if __name__ == "__main__": import doctest doctest.testmod()
299
import functools def A__ ( __lowerCamelCase, __lowerCamelCase ): # Validation if not isinstance(__lowerCamelCase, __lowerCamelCase ) or not all(isinstance(__lowerCamelCase, __lowerCamelCase ) for day in days ): raise ValueError('''The parameter days should be a list of integers''' ) if len(__lowerCamelCase ) != 3 or not all(isinstance(__lowerCamelCase, __lowerCamelCase ) for cost in costs ): raise ValueError('''The parameter costs should be a list of three integers''' ) if len(__lowerCamelCase ) == 0: return 0 if min(__lowerCamelCase ) <= 0: raise ValueError('''All days elements should be greater than 0''' ) if max(__lowerCamelCase ) >= 3_66: raise ValueError('''All days elements should be less than 366''' ) SCREAMING_SNAKE_CASE_ = set(__lowerCamelCase ) @functools.cache def dynamic_programming(__lowerCamelCase ) -> int: if index > 3_65: return 0 if index not in days_set: return dynamic_programming(index + 1 ) return min( costs[0] + dynamic_programming(index + 1 ), costs[1] + dynamic_programming(index + 7 ), costs[2] + dynamic_programming(index + 30 ), ) return dynamic_programming(1 ) if __name__ == "__main__": import doctest doctest.testmod()
299
1
import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor lowercase_ = logging.get_logger(__name__) class A ( _UpperCAmelCase ): """simple docstring""" def __init__( self : Dict,*lowercase_ : str,**lowercase_ : List[str] )-> None: '''simple docstring''' warnings.warn( 'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use BeitImageProcessor instead.',lowercase_,) super().__init__(*lowercase_,**lowercase_ )
282
import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def _snake_case( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int]="attention" ) -> Union[str, Any]: '''simple docstring''' A__ = params[f'{prefix}/layers_{i}/{layer_name}/key/kernel'] A__ = params[f'{prefix}/layers_{i}/{layer_name}/out/kernel'] A__ = params[f'{prefix}/layers_{i}/{layer_name}/query/kernel'] A__ = params[f'{prefix}/layers_{i}/{layer_name}/value/kernel'] return k, o, q, v def _snake_case( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict=False ) -> str: '''simple docstring''' if split_mlp_wi: A__ = params[f'{prefix}/layers_{i}/mlp/wi_0/kernel'] A__ = params[f'{prefix}/layers_{i}/mlp/wi_1/kernel'] A__ = (wi_a, wi_a) else: A__ = params[f'{prefix}/layers_{i}/mlp/wi/kernel'] A__ = params[f'{prefix}/layers_{i}/mlp/wo/kernel'] return wi, wo def _snake_case( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int ) -> str: '''simple docstring''' return params[f'{prefix}/layers_{i}/{layer_name}/scale'] def _snake_case( SCREAMING_SNAKE_CASE__ : dict , *, SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : bool ) -> int: '''simple docstring''' A__ = traverse_util.flatten_dict(variables['target'] ) A__ = {'/'.join(SCREAMING_SNAKE_CASE__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi A__ = 'encoder/layers_0/mlp/wi_0/kernel' in old print('Split MLP:' , SCREAMING_SNAKE_CASE__ ) A__ = collections.OrderedDict() # Shared embeddings. A__ = old['token_embedder/embedding'] # Encoder. for i in range(SCREAMING_SNAKE_CASE__ ): # Block i, layer 0 (Self Attention). A__ = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'encoder' , 'pre_attention_layer_norm' ) A__ , A__ , A__ , A__ = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'encoder' , 'attention' ) A__ = layer_norm A__ = k.T A__ = o.T A__ = q.T A__ = v.T # Block i, layer 1 (MLP). A__ = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'encoder' , 'pre_mlp_layer_norm' ) A__ , A__ = tax_mlp_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'encoder' , SCREAMING_SNAKE_CASE__ ) A__ = layer_norm if split_mlp_wi: A__ = wi[0].T A__ = wi[1].T else: A__ = wi.T A__ = wo.T A__ = old[ 'encoder/relpos_bias/rel_embedding' ].T A__ = old['encoder/encoder_norm/scale'] if not is_encoder_only: # Decoder. for i in range(SCREAMING_SNAKE_CASE__ ): # Block i, layer 0 (Self Attention). A__ = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , 'pre_self_attention_layer_norm' ) A__ , A__ , A__ , A__ = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , 'self_attention' ) A__ = layer_norm A__ = k.T A__ = o.T A__ = q.T A__ = v.T # Block i, layer 1 (Cross Attention). A__ = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , 'pre_cross_attention_layer_norm' ) A__ , A__ , A__ , A__ = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , 'encoder_decoder_attention' ) A__ = layer_norm A__ = k.T A__ = o.T A__ = q.T A__ = v.T # Block i, layer 2 (MLP). A__ = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , 'pre_mlp_layer_norm' ) A__ , A__ = tax_mlp_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'decoder' , SCREAMING_SNAKE_CASE__ ) A__ = layer_norm if split_mlp_wi: A__ = wi[0].T A__ = wi[1].T else: A__ = wi.T A__ = wo.T A__ = old['decoder/decoder_norm/scale'] A__ = old[ 'decoder/relpos_bias/rel_embedding' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: A__ = old['decoder/logits_dense/kernel'].T return new def _snake_case( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : bool ) -> Dict: '''simple docstring''' A__ = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: A__ = state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: A__ = state_dict['shared.weight'] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('Using shared word embeddings as lm_head.' ) A__ = state_dict['shared.weight'] return state_dict def _snake_case( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple ) -> int: '''simple docstring''' A__ = checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE__ ) A__ = convert_tax_to_pytorch(SCREAMING_SNAKE_CASE__ , num_layers=config.num_layers , is_encoder_only=SCREAMING_SNAKE_CASE__ ) A__ = make_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ ) def _snake_case( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : bool = False ) -> Any: '''simple docstring''' A__ = TaConfig.from_json_file(SCREAMING_SNAKE_CASE__ ) print(f'Building PyTorch model from configuration: {config}' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: A__ = TaEncoderModel(SCREAMING_SNAKE_CASE__ ) else: A__ = TaForConditionalGeneration(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save pytorch-model print(f'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Verify that we can load the checkpoint. model.from_pretrained(SCREAMING_SNAKE_CASE__ ) print('Done' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.") # Required parameters parser.add_argument( "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False ) lowercase_ = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
282
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class snake_case_( a__ ): __UpperCamelCase = '''Salesforce/blip-image-captioning-base''' __UpperCamelCase = ( '''This is a tool that generates a description of an image. It takes an input named `image` which should be the ''' '''image to caption, and returns a text that contains the description in English.''' ) __UpperCamelCase = '''image_captioner''' __UpperCamelCase = AutoModelForVisionaSeq __UpperCamelCase = ['''image'''] __UpperCamelCase = ['''text'''] def __init__( self : Optional[int] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*UpperCamelCase_ , **UpperCamelCase_ ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : "Image" ): return self.pre_processor(images=UpperCamelCase_ , return_tensors='''pt''' ) def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : Tuple ): return self.model.generate(**UpperCamelCase_ ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : str ): return self.pre_processor.batch_decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ )[0].strip()
60
"""simple docstring""" def a_ ( lowerCamelCase ): return str(lowerCamelCase ) == str(lowerCamelCase )[::-1] def a_ ( lowerCamelCase ): return int(lowerCamelCase ) + int(str(lowerCamelCase )[::-1] ) def a_ ( lowerCamelCase = 1_0_0_0_0 ): UpperCAmelCase__ = [] for num in range(1 , lowerCamelCase ): UpperCAmelCase__ = 0 UpperCAmelCase__ = num while iterations < 5_0: UpperCAmelCase__ = sum_reverse(lowerCamelCase ) iterations += 1 if is_palindrome(lowerCamelCase ): break else: lychrel_nums.append(lowerCamelCase ) return len(lowerCamelCase ) if __name__ == "__main__": print(F"""{solution() = }""")
98
0
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black A_ : int = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. A_ : Dict = """ \"\"\" Output class for the scheduler's step function output. Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the denoising loop. pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): The predicted denoised sample (x_{0}) based on the model output from the current timestep. `pred_original_sample` can be used to preview progress or for guidance. \"\"\" prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None """ class lowercase ( unittest.TestCase ): """simple docstring""" def _snake_case ( self ) -> Dict: _UpperCAmelCase : List[str] = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir ,"""schedulers/""" ) ) _UpperCAmelCase : int = self.diffusers_dir shutil.copy( os.path.join(a_ ,"""src/diffusers/schedulers/scheduling_ddpm.py""" ) ,os.path.join(self.diffusers_dir ,"""schedulers/scheduling_ddpm.py""" ) ,) def _snake_case ( self ) -> Optional[int]: _UpperCAmelCase : Tuple = """src/diffusers""" shutil.rmtree(self.diffusers_dir ) def _snake_case ( self ,a_ ,a_ ,a_ ,a_=None ) -> Optional[Any]: _UpperCAmelCase : List[str] = comment + f'''\nclass {class_name}(nn.Module):\n''' + class_code if overwrite_result is not None: _UpperCAmelCase : Union[str, Any] = comment + f'''\nclass {class_name}(nn.Module):\n''' + overwrite_result _UpperCAmelCase : int = black.Mode(target_versions={black.TargetVersion.PYaa} ,line_length=119 ) _UpperCAmelCase : List[str] = black.format_str(a_ ,mode=a_ ) _UpperCAmelCase : Tuple = os.path.join(self.diffusers_dir ,"""new_code.py""" ) with open(a_ ,"""w""" ,newline="""\n""" ) as f: f.write(a_ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(a_ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name ,overwrite=a_ ) with open(a_ ,"""r""" ) as f: self.assertTrue(f.read() ,a_ ) def _snake_case ( self ) -> Optional[Any]: _UpperCAmelCase : Any = check_copies.find_code_in_diffusers("""schedulers.scheduling_ddpm.DDPMSchedulerOutput""" ) self.assertEqual(a_ ,a_ ) def _snake_case ( self ) -> Optional[int]: # Base copy consistency self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" ,"""DDPMSchedulerOutput""" ,REFERENCE_CODE + """\n""" ,) # With no empty line at the end self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" ,"""DDPMSchedulerOutput""" ,a_ ,) # Copy consistency with rename self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" ,"""TestSchedulerOutput""" ,re.sub("""DDPM""" ,"""Test""" ,a_ ) ,) # Copy consistency with a really long name _UpperCAmelCase : List[Any] = """TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( f'''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}''' ,f'''{long_class_name}SchedulerOutput''' ,re.sub("""Bert""" ,a_ ,a_ ) ,) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" ,"""TestSchedulerOutput""" ,a_ ,overwrite_result=re.sub("""DDPM""" ,"""Test""" ,a_ ) ,)
349
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class lowercase : """simple docstring""" UpperCAmelCase = 42 UpperCAmelCase = 42 class lowercase : """simple docstring""" def __init__( self ,a_ ) -> List[str]: _UpperCAmelCase : list[list[Edge]] = [[] for _ in range(a_ )] _UpperCAmelCase : int = size def __getitem__( self ,a_ ) -> Iterator[Edge]: return iter(self._graph[vertex] ) @property def _snake_case ( self ) -> List[Any]: return self._size def _snake_case ( self ,a_ ,a_ ,a_ ) -> Tuple: if weight not in (0, 1): raise ValueError("""Edge weight must be either 0 or 1.""" ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("""Vertex indexes must be in [0; size).""" ) self._graph[from_vertex].append(Edge(a_ ,a_ ) ) def _snake_case ( self ,a_ ,a_ ) -> int | None: _UpperCAmelCase : Union[str, Any] = deque([start_vertex] ) _UpperCAmelCase : list[int | None] = [None] * self.size _UpperCAmelCase : Union[str, Any] = 0 while queue: _UpperCAmelCase : Union[str, Any] = queue.popleft() _UpperCAmelCase : Union[str, Any] = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: _UpperCAmelCase : List[Any] = current_distance + edge.weight _UpperCAmelCase : List[Any] = distances[edge.destination_vertex] if ( isinstance(a_ ,a_ ) and new_distance >= dest_vertex_distance ): continue _UpperCAmelCase : Tuple = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("""No path from start_vertex to finish_vertex.""" ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
349
1
'''simple docstring''' import math from collections.abc import Callable def UpperCAmelCase_ ( __lowerCamelCase : Callable[[float], float] ,__lowerCamelCase : float ,__lowerCamelCase : float ): lowercase_ :float = xa lowercase_ :float = xa while True: if x_n == x_na or function(__lowerCamelCase ) == function(__lowerCamelCase ): raise ZeroDivisionError("float division by zero, could not find root" ) lowercase_ :float = x_na - ( function(__lowerCamelCase ) / ((function(__lowerCamelCase ) - function(__lowerCamelCase )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na lowercase_ :Dict = x_na lowercase_ :List[Any] = x_na def UpperCAmelCase_ ( __lowerCamelCase : float ): return math.pow(__lowerCamelCase ,3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
223
'''simple docstring''' import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def UpperCAmelCase_ ( __lowerCamelCase : List[str] ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" ,set() ) @pytest.fixture def UpperCAmelCase_ ( __lowerCamelCase : Any ): class a_ : def __init__( self : int , lowercase : int ): """simple docstring""" lowercase_ :Optional[Any] = metric_id class a_ : __A = [MetricMock(_lowerCAmelCase ) for metric_id in ["accuracy", "mse", "precision", "codeparrot/apps_metric"]] def lowercase__ ( self : Union[str, Any] ): """simple docstring""" return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" ,HfhMock() ) @pytest.mark.parametrize( "func, args" ,[(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def UpperCAmelCase_ ( __lowerCamelCase : Union[str, Any] ,__lowerCamelCase : int ,__lowerCamelCase : Optional[int] ,__lowerCamelCase : Union[str, Any] ,__lowerCamelCase : Tuple ): if "tmp_path" in args: lowercase_ :Union[str, Any] = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(__lowerCamelCase ,match="https://huggingface.co/docs/evaluate" ): func(*__lowerCamelCase )
223
1
import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCAmelCase : '''simple docstring''' def __init__( self : Optional[int] , __a : str , __a : Optional[Any]=13 , __a : str=30 , __a : Optional[int]=2 , __a : List[Any]=3 , __a : List[str]=True , __a : Optional[int]=True , __a : List[str]=32 , __a : str=5 , __a : Any=4 , __a : List[str]=37 , __a : Tuple="gelu" , __a : Any=0.1 , __a : Optional[Any]=0.1 , __a : Any=10 , __a : int=0.02 , __a : Optional[Any]=None , __a : List[str]=2 , ) -> Optional[int]: """simple docstring""" __lowercase : List[Any] = parent __lowercase : Any = batch_size __lowercase : Optional[int] = image_size __lowercase : str = patch_size __lowercase : str = num_channels __lowercase : str = is_training __lowercase : List[Any] = use_labels __lowercase : int = hidden_size __lowercase : List[Any] = num_hidden_layers __lowercase : Optional[int] = num_attention_heads __lowercase : Any = intermediate_size __lowercase : Dict = hidden_act __lowercase : Tuple = hidden_dropout_prob __lowercase : Dict = attention_probs_dropout_prob __lowercase : List[str] = type_sequence_label_size __lowercase : str = initializer_range __lowercase : Union[str, Any] = scope __lowercase : Any = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __lowercase : str = (image_size // patch_size) ** 2 __lowercase : int = num_patches + 1 def lowerCAmelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" __lowercase : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowercase : Union[str, Any] = None if self.use_labels: __lowercase : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowercase : Union[str, Any] = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def lowerCAmelCase ( self : List[str] , __a : List[Any] , __a : List[str] , __a : Union[str, Any] ) -> str: """simple docstring""" __lowercase : List[str] = ViTModel(config=__a ) model.to(__a ) model.eval() __lowercase : Optional[Any] = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase ( self : Optional[int] , __a : Tuple , __a : Dict , __a : Dict ) -> Any: """simple docstring""" __lowercase : str = ViTForMaskedImageModeling(config=__a ) model.to(__a ) model.eval() __lowercase : Dict = model(__a ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __lowercase : Dict = 1 __lowercase : str = ViTForMaskedImageModeling(__a ) model.to(__a ) model.eval() __lowercase : Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowercase : int = model(__a ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def lowerCAmelCase ( self : Optional[int] , __a : Dict , __a : Optional[Any] , __a : List[Any] ) -> Optional[Any]: """simple docstring""" __lowercase : str = self.type_sequence_label_size __lowercase : Optional[int] = ViTForImageClassification(__a ) model.to(__a ) model.eval() __lowercase : List[str] = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __lowercase : Optional[Any] = 1 __lowercase : Optional[Any] = ViTForImageClassification(__a ) model.to(__a ) model.eval() __lowercase : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowercase : List[Any] = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCAmelCase ( self : str ) -> List[Any]: """simple docstring""" __lowercase : str = self.prepare_config_and_inputs() ( ( __lowercase ) , ( __lowercase ) , ( __lowercase ) , ) : int = config_and_inputs __lowercase : str = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase ( __a , __a , unittest.TestCase ): '''simple docstring''' _A : Optional[Any] = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) _A : Optional[Any] = ( {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification} if is_torch_available() else {} ) _A : Tuple = True _A : Optional[int] = False _A : Optional[int] = False _A : Union[str, Any] = False def lowerCAmelCase ( self : str ) -> int: """simple docstring""" __lowercase : str = ViTModelTester(self ) __lowercase : Tuple = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def lowerCAmelCase ( self : Optional[int] ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" __lowercase , __lowercase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowercase : Tuple = model_class(__a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __lowercase : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , nn.Linear ) ) def lowerCAmelCase ( self : Any ) -> Any: """simple docstring""" __lowercase , __lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowercase : int = model_class(__a ) __lowercase : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowercase : Tuple = [*signature.parameters.keys()] __lowercase : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __a ) def lowerCAmelCase ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" __lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def lowerCAmelCase ( self : List[Any] ) -> int: """simple docstring""" __lowercase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__a ) def lowerCAmelCase ( self : Optional[int] ) -> int: """simple docstring""" __lowercase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def lowerCAmelCase ( self : List[Any] ) -> Any: """simple docstring""" for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase : Optional[int] = ViTModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def snake_case_ ( ): __lowercase : Tuple = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : List[str] ) -> List[Any]: """simple docstring""" __lowercase : int = ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ).to(__a ) __lowercase : Optional[Any] = self.default_image_processor __lowercase : Dict = prepare_img() __lowercase : Dict = image_processor(images=__a , return_tensors="""pt""" ).to(__a ) # forward pass with torch.no_grad(): __lowercase : Any = model(**__a ) # verify the logits __lowercase : str = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __lowercase : Union[str, Any] = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1E-4 ) ) @slow def lowerCAmelCase ( self : Dict ) -> Dict: """simple docstring""" __lowercase : Optional[Any] = ViTModel.from_pretrained("""facebook/dino-vits8""" ).to(__a ) __lowercase : Any = ViTImageProcessor.from_pretrained("""facebook/dino-vits8""" , size=480 ) __lowercase : int = prepare_img() __lowercase : Tuple = image_processor(images=__a , return_tensors="""pt""" ) __lowercase : str = inputs.pixel_values.to(__a ) # forward pass with torch.no_grad(): __lowercase : Optional[Any] = model(__a , interpolate_pos_encoding=__a ) # verify the logits __lowercase : Dict = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , __a ) __lowercase : Tuple = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(__a ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __a , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def lowerCAmelCase ( self : Optional[Any] ) -> Any: """simple docstring""" __lowercase : Union[str, Any] = ViTModel.from_pretrained("""facebook/dino-vits8""" , torch_dtype=torch.floataa , device_map="""auto""" ) __lowercase : int = self.default_image_processor __lowercase : Dict = prepare_img() __lowercase : List[Any] = image_processor(images=__a , return_tensors="""pt""" ) __lowercase : Optional[Any] = inputs.pixel_values.to(__a ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __lowercase : Optional[Any] = model(__a )
306
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class lowerCAmelCase ( __a ): '''simple docstring''' _A : Optional[Any] = (DPMSolverSDEScheduler,) _A : Dict = 10 def lowerCAmelCase ( self : Optional[int] , **__a : Dict ) -> Optional[int]: """simple docstring""" __lowercase : Any = { """num_train_timesteps""": 1100, """beta_start""": 0.0001, """beta_end""": 0.02, """beta_schedule""": """linear""", """noise_sampler_seed""": 0, } config.update(**__a ) return config def lowerCAmelCase ( self : List[Any] ) -> Optional[Any]: """simple docstring""" for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=__a ) def lowerCAmelCase ( self : Any ) -> Optional[int]: """simple docstring""" for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=__a , beta_end=__a ) def lowerCAmelCase ( self : str ) -> Optional[Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=__a ) def lowerCAmelCase ( self : Dict ) -> Tuple: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__a ) def lowerCAmelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" __lowercase : Optional[int] = self.scheduler_classes[0] __lowercase : List[str] = self.get_scheduler_config() __lowercase : Any = scheduler_class(**__a ) scheduler.set_timesteps(self.num_inference_steps ) __lowercase : Optional[Any] = self.dummy_model() __lowercase : str = self.dummy_sample_deter * scheduler.init_noise_sigma __lowercase : Optional[Any] = sample.to(__a ) for i, t in enumerate(scheduler.timesteps ): __lowercase : Union[str, Any] = scheduler.scale_model_input(__a , __a ) __lowercase : Optional[Any] = model(__a , __a ) __lowercase : Optional[Any] = scheduler.step(__a , __a , __a ) __lowercase : str = output.prev_sample __lowercase : Optional[Any] = torch.sum(torch.abs(__a ) ) __lowercase : Union[str, Any] = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47821044921875 ) < 1E-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59352111816406 ) < 1E-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" __lowercase : Tuple = self.scheduler_classes[0] __lowercase : Dict = self.get_scheduler_config(prediction_type="""v_prediction""" ) __lowercase : int = scheduler_class(**__a ) scheduler.set_timesteps(self.num_inference_steps ) __lowercase : Optional[int] = self.dummy_model() __lowercase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma __lowercase : Dict = sample.to(__a ) for i, t in enumerate(scheduler.timesteps ): __lowercase : Dict = scheduler.scale_model_input(__a , __a ) __lowercase : Optional[int] = model(__a , __a ) __lowercase : Optional[int] = scheduler.step(__a , __a , __a ) __lowercase : int = output.prev_sample __lowercase : Optional[Any] = torch.sum(torch.abs(__a ) ) __lowercase : List[str] = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77149200439453 ) < 1E-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1663360595703 ) < 1E-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1E-3 else: assert abs(result_sum.item() - 119.8487548828125 ) < 1E-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1E-3 def lowerCAmelCase ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __lowercase : Tuple = self.scheduler_classes[0] __lowercase : Dict = self.get_scheduler_config() __lowercase : Optional[int] = scheduler_class(**__a ) scheduler.set_timesteps(self.num_inference_steps , device=__a ) __lowercase : int = self.dummy_model() __lowercase : Optional[Any] = self.dummy_sample_deter.to(__a ) * scheduler.init_noise_sigma for t in scheduler.timesteps: __lowercase : int = scheduler.scale_model_input(__a , __a ) __lowercase : List[str] = model(__a , __a ) __lowercase : List[str] = scheduler.step(__a , __a , __a ) __lowercase : int = output.prev_sample __lowercase : List[Any] = torch.sum(torch.abs(__a ) ) __lowercase : Optional[Any] = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46957397460938 ) < 1E-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59353637695312 ) < 1E-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1E-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1E-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1E-3 def lowerCAmelCase ( self : Tuple ) -> Tuple: """simple docstring""" __lowercase : str = self.scheduler_classes[0] __lowercase : List[Any] = self.get_scheduler_config() __lowercase : Tuple = scheduler_class(**__a , use_karras_sigmas=__a ) scheduler.set_timesteps(self.num_inference_steps , device=__a ) __lowercase : List[str] = self.dummy_model() __lowercase : Optional[int] = self.dummy_sample_deter.to(__a ) * scheduler.init_noise_sigma __lowercase : str = sample.to(__a ) for t in scheduler.timesteps: __lowercase : List[Any] = scheduler.scale_model_input(__a , __a ) __lowercase : Optional[Any] = model(__a , __a ) __lowercase : Any = scheduler.step(__a , __a , __a ) __lowercase : Optional[Any] = output.prev_sample __lowercase : Any = torch.sum(torch.abs(__a ) ) __lowercase : Optional[Any] = torch.mean(torch.abs(__a ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66974135742188 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63653564453125 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2 else: assert abs(result_sum.item() - 170.3135223388672 ) < 1E-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1E-2
306
1
def SCREAMING_SNAKE_CASE_ ( __A : int , __A : int ) -> str: """simple docstring""" if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) a_ : Optional[Any] = str(bin(__A ) )[2:] # remove the leading "0b" a_ : List[str] = str(bin(__A ) )[2:] # remove the leading "0b" a_ : int = max(len(__A ) , len(__A ) ) return "0b" + "".join( str(int(char_a != char_b ) ) for char_a, char_b in zip(a_binary.zfill(__A ) , b_binary.zfill(__A ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
32
from __future__ import annotations import json import requests from bsa import BeautifulSoup from fake_useragent import UserAgent UpperCAmelCase_ : Any = {'UserAgent': UserAgent().random} def SCREAMING_SNAKE_CASE_ ( __A : Optional[int] ) -> dict: """simple docstring""" a_ : Tuple = script.contents[0] a_ : int = json.loads(data[data.find('{"config"' ) : -1] ) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: a_ : Tuple = F"""https://www.instagram.com/{username}/""" a_ : Optional[Any] = self.get_json() def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> dict: a_ : Any = requests.get(self.url , headers=SCREAMING_SNAKE_CASE__ ).text a_ : Dict = BeautifulSoup(SCREAMING_SNAKE_CASE__ , 'html.parser' ).find_all('script' ) try: return extract_user_profile(scripts[4] ) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3] ) def __repr__( self : Union[str, Any] ) -> str: return F"""{self.__class__.__name__}('{self.username}')""" def __str__( self : Optional[int] ) -> str: return F"""{self.fullname} ({self.username}) is {self.biography}""" @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: return self.user_data["username"] @property def SCREAMING_SNAKE_CASE ( self : str ) -> str: return self.user_data["full_name"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> str: return self.user_data["biography"] @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: return self.user_data["business_email"] @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str: return self.user_data["external_url"] @property def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: return self.user_data["edge_followed_by"]["count"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> int: return self.user_data["edge_follow"]["count"] @property def SCREAMING_SNAKE_CASE ( self : str ) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> str: return self.user_data["profile_pic_url_hd"] @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> bool: return self.user_data["is_verified"] @property def SCREAMING_SNAKE_CASE ( self : Any ) -> bool: return self.user_data["is_private"] def SCREAMING_SNAKE_CASE_ ( __A : str = "github" ) -> None: """simple docstring""" import os if os.environ.get('CI' ): return # test failing on GitHub Actions a_ : int = InstagramUser(__A ) assert instagram_user.user_data assert isinstance(instagram_user.user_data , __A ) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 1_50 assert instagram_user.number_of_followers > 12_00_00 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "support@github.com" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith('https://instagram.' ) assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase_ : Union[str, Any] = InstagramUser('github') print(instagram_user) print(F'{instagram_user.number_of_posts = }') print(F'{instagram_user.number_of_followers = }') print(F'{instagram_user.number_of_followings = }') print(F'{instagram_user.email = }') print(F'{instagram_user.website = }') print(F'{instagram_user.profile_picture_url = }') print(F'{instagram_user.is_verified = }') print(F'{instagram_user.is_private = }')
32
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __A : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = ['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys __A : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
"""simple docstring""" import json import os import unittest from typing import Tuple from transformers import WavaVecaPhonemeCTCTokenizer from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizerOutput from transformers.testing_utils import require_phonemizer from ...test_tokenization_common import TokenizerTesterMixin @require_phonemizer class __UpperCamelCase ( _A , unittest.TestCase ): SCREAMING_SNAKE_CASE = WavaVecaPhonemeCTCTokenizer SCREAMING_SNAKE_CASE = False def SCREAMING_SNAKE_CASE__ (self : Tuple): super().setUp() A = ( "<s> <pad> </s> <unk> n s t ə l a i k d m ɛ ɾ e ɪ p o ɐ z ð f j v b ɹ ʁ ʊ iː r w ʌ u ɡ æ aɪ ʃ h ɔ ɑː " "ŋ ɚ eɪ β uː y ɑ̃ oʊ ᵻ eː θ aʊ ts oː ɔ̃ ɣ ɜ ɑ dʒ əl x ɜː ç ʒ tʃ ɔː ɑːɹ ɛ̃ ʎ ɔːɹ ʋ aː ɕ œ ø oːɹ ɲ yː " "ʔ iə i5 s. tɕ ?? nʲ ɛː œ̃ ɭ ɔø ʑ tʲ ɨ ɛɹ ts. rʲ ɪɹ ɭʲ i.5 ɔɪ q sʲ u5 ʊɹ iɜ a5 iɛ5 øː ʕ ja əɜ th ɑ5 " "oɪ dʲ ə5 tɕh ts.h mʲ ɯ dʑ vʲ e̞ tʃʲ ei5 o5 onɡ5 ɑu5 iɑ5 ai5 aɪɚ kh ə1 ʐ i2 ʉ ħ t[ aɪə ʲ ju ə2 u2 oɜ " "pː iɛɜ ou5 y5 uɜ tː uo5 d[ uoɜ tsh ɑɜ ɵ i̪5 uei5 ɟ aɜ ɑɨ i.ɜ eʊ o2 ɐ̃ ä pʲ kʲ n̩ ɒ ph ɑu2 uɨ əɪ ɫ ɬ " "yɜ bʲ ɑ2 s̪ aiɜ χ ɐ̃ʊ̃ 1 ə4 yæɜ a2 ɨː t̪ iouɜ ũ onɡɜ aɨ iɛ2 ɔɨ ɑuɜ o̞ ei2 iou2 c kː y2 ɖ oe dˤ yɛɜ " "əʊ S ɡʲ onɡ2 u\" eiɜ ʈ ɯᵝ iou5 dZ r̝̊ i.2 tS s^ ʝ yə5 iɑɜ uə5 pf ɨu iɑ2 ou2 ər2 fʲ ai2 r̝ uəɜ ɳ əɨ " "ua5 uɪ ɽ bː yu5 uo2 yɛ5 l̩ ɻ ərɜ ʂ i̪2 ouɜ uaɜ a. a.ː yæ5 dː r̩ ee ɪu ər5 i̪ ɜ æi u: i.ː t^ o1 ɪ^ " "ai ueiɜ æː ɛɪ eə i. ɴ ie ua2 ɑ1 o4 tʃː o: ɑ: u1 N i̪1 au yæ2 u. qː yəɜ y: kʰ tʃʰ iʊ sx õ uo tʰ " "uai5 bʰ u.ː uə2 ʊə d^ s̪ː yiɜ dʰ r. oe: i1 ɟː yu2 nʲʲ i̪4 uei2 tsʲ ɸ ĩ ɑ4 t̪ː eɑ u4 e: tsː ʈʰ ɡʰ " "ɯɯ dʒʲ ʂʲ X ɵː uaiɜ tɕʲ ã t^ː ẽː yɛ2 cː i.1 ɛʊ dˤdˤ dʒː i4 ɡː yi ɕʲ ɟʰ pʰ dʑʲ yuɜ ua1 ua4 æiː ɐɐ " "ui iou1 ʊː a1 iou4 cʰ iɛ1 yə2 ɖʰ ẽ ʒʲ ää ər4 iːː ɪː iɑ1 ər1 œː øi ɪuː cʰcʰ əː1 iː1 ũ kʰː o̞o̞ xʲ " "ou1 iɛ4 e̞e̞ y1 dzː dʲʲ dʰː ɯᵝɯᵝ lː uo1 i.4 i: yɛ5ʲ a4" ).split(" ") A = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE)))) A = {"pad_token": "<pad>", "unk_token": "<unk>", "bos_token": "<s>", "eos_token": "</s>"} A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"]) with open(self.vocab_file , "w" , encoding="utf-8") as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE) + "\n") def SCREAMING_SNAKE_CASE__ (self : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Optional[Any]=2_0 , __SCREAMING_SNAKE_CASE : Any=5): A = [(i, tokenizer.decode([i] , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE)) for i in range(len(__SCREAMING_SNAKE_CASE))] A = list(filter(lambda __SCREAMING_SNAKE_CASE: [t[0]] == tokenizer.encode(t[1] , do_phonemize=__SCREAMING_SNAKE_CASE) , __SCREAMING_SNAKE_CASE)) if max_length is not None and len(__SCREAMING_SNAKE_CASE) > max_length: A = toks[:max_length] if min_length is not None and len(__SCREAMING_SNAKE_CASE) < min_length and len(__SCREAMING_SNAKE_CASE) > 0: while len(__SCREAMING_SNAKE_CASE) < min_length: A = toks + toks # toks_str = [t[1] for t in toks] A = [t[0] for t in toks] # Ensure consistency A = tokenizer.decode(__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE) if " " not in output_txt and len(__SCREAMING_SNAKE_CASE) > 1: A = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE) + " " + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE) ) if with_prefix_space: A = " " + output_txt A = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE) return output_txt, output_ids def SCREAMING_SNAKE_CASE__ (self : List[Any] , **__SCREAMING_SNAKE_CASE : Any): kwargs.update(self.special_tokens_map) return WavaVecaPhonemeCTCTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Optional[Any]): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") # check adding a single token tokenizer.add_tokens("xxx") A = tokenizer("m xxx ɪ" , do_phonemize=__SCREAMING_SNAKE_CASE).input_ids self.assertEqual(__SCREAMING_SNAKE_CASE , [1_3, 3_9_2, 1_7]) # xxx should be last token tokenizer.add_tokens(["aaa", "bbb", "ccc"]) A = tokenizer("m aaa ɪ ccc" , do_phonemize=__SCREAMING_SNAKE_CASE).input_ids self.assertEqual(__SCREAMING_SNAKE_CASE , [1_3, 3_9_3, 1_7, 3_9_5]) # aaa and ccc should be after xxx and 2 after aaa A = tokenizer("maɪ c" , do_phonemize=__SCREAMING_SNAKE_CASE).input_ids self.assertEqual(__SCREAMING_SNAKE_CASE , [3, 2_0_0]) # mai should be <unk> (=3) def SCREAMING_SNAKE_CASE__ (self : Tuple): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") self.assertEqual(__SCREAMING_SNAKE_CASE , "h ə l oʊ h aʊ ɑːɹ j uː") def SCREAMING_SNAKE_CASE__ (self : List[str]): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") self.assertEqual(tokenizer(__SCREAMING_SNAKE_CASE).input_ids , tokenizer(__SCREAMING_SNAKE_CASE , do_phonemize=__SCREAMING_SNAKE_CASE).input_ids) def SCREAMING_SNAKE_CASE__ (self : Any): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") A = tokenizer.decode(tokenizer(__SCREAMING_SNAKE_CASE).input_ids) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : str): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") A = [ [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 8, 9_8], [2_4, 2_2, 5, 2_4, 2_2, 5, 7_7], ] A = tokenizer.decode(sample_ids[0]) A = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , batch_tokens[0]) self.assertEqual(__SCREAMING_SNAKE_CASE , ["k s ɾ ɾ l ɭʲ", "j ð s j ð s oːɹ"]) def SCREAMING_SNAKE_CASE__ (self : List[str]): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|") tokenizer.add_tokens("|") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") self.assertEqual(__SCREAMING_SNAKE_CASE , "h ə l oʊ | h aʊ | ɑːɹ | j uː |") def SCREAMING_SNAKE_CASE__ (self : str): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|") tokenizer.add_tokens("|") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") self.assertEqual(tokenizer(__SCREAMING_SNAKE_CASE).input_ids , tokenizer(__SCREAMING_SNAKE_CASE , do_phonemize=__SCREAMING_SNAKE_CASE).input_ids) def SCREAMING_SNAKE_CASE__ (self : Optional[int]): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|") tokenizer.add_tokens("|") # fmt: off A = [ [1_1, 5, 1_5, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 1_5, 8, tokenizer.word_delimiter_token_id, 9_8], [tokenizer.word_delimiter_token_id, 2_4, 2_2, tokenizer.word_delimiter_token_id, 5, 2_4, 2_2, 5, 7_7], ] # fmt: on # decode with word_del_token filter A = tokenizer.decode(sample_ids[0]) A = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , batch_tokens[0]) self.assertEqual(__SCREAMING_SNAKE_CASE , ["k s ɾ ɾ l ɭʲ", "j ð s j ð s oːɹ"]) # decode with no word_del_token filter A = tokenizer.decode(sample_ids[0] , filter_word_delimiter_token=__SCREAMING_SNAKE_CASE) A = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , filter_word_delimiter_token=__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , batch_tokens[0]) self.assertEqual(__SCREAMING_SNAKE_CASE , ["k s ɾ | ɾ l | ɭʲ", "| j ð | s j ð s oːɹ"]) def SCREAMING_SNAKE_CASE__ (self : Dict): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|") tokenizer.add_tokens("|") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") A = tokenizer.decode(tokenizer(__SCREAMING_SNAKE_CASE).input_ids , filter_word_delimiter_token=__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : List[Any]): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token="|") tokenizer.add_tokens("|") A = "Hello how are you" A = tokenizer.phonemize(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us") A = tokenizer.decode(tokenizer(__SCREAMING_SNAKE_CASE).input_ids , filter_word_delimiter_token=__SCREAMING_SNAKE_CASE) self.assertEqual(" ".join([p.strip() for p in phonemes.split(" |")]).strip() , __SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Dict): A = self.tokenizer_class.from_pretrained( "facebook/wav2vec2-lv-60-espeak-cv-ft" , word_delimiter_token=__SCREAMING_SNAKE_CASE) A = "Hello how are you" A = tokenizer(__SCREAMING_SNAKE_CASE , phonemizer_lang="en-us").input_ids A = tokenizer(__SCREAMING_SNAKE_CASE , phonemizer_lang="fr-fr").input_ids self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) A = tokenizer.decode(__SCREAMING_SNAKE_CASE) A = tokenizer.decode(__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , "h ə l oʊ h aʊ ɑːɹ j uː") self.assertEqual(__SCREAMING_SNAKE_CASE , "ɛ l o h aʊ a ʁ j u") def SCREAMING_SNAKE_CASE__ (self : Union[str, Any]): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") A = "Hello how Are you" A = "hello how are you" A = tokenizer(__SCREAMING_SNAKE_CASE).input_ids A = tokenizer(__SCREAMING_SNAKE_CASE).input_ids self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) def SCREAMING_SNAKE_CASE__ (self : Union[str, Any]): A = self.tokenizer_class.from_pretrained("facebook/wav2vec2-lv-60-espeak-cv-ft") tokenizer.add_tokens(["!", "?"]) tokenizer.add_special_tokens({"cls_token": "$$$"}) # fmt: off A = [ [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 8, 9_8, 3_9_2, 3_9_2, 3_9_3, 3_9_2, 3_9_2, 3_9_3, 3_9_4, 3_9_4], [2_4, 2_2, 5, 2_4, 2_2, 5, 7_7, tokenizer.pad_token_id, 3_9_4, 3_9_4], ] # fmt: on A = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , ["k s ɾ ɾ l ɭʲ!?!? $$$", "j ð s j ð s oːɹ $$$"]) @staticmethod def SCREAMING_SNAKE_CASE__ (__SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Union[str, Any]): A = [d[key] for d in offsets] return retrieved_list def SCREAMING_SNAKE_CASE__ (self : Optional[Any]): A = self.get_tokenizer(word_delimiter_token="|") tokenizer.add_tokens("|") # fmt: off # ksssɾɾ|ɾɾ<pad>ɾɾ|<pad>ɾlll|ɭʲ -> k s ɾ ɾ | ɾ l | ɭʲ" A = [1_1, 5, 5, 5, 1_5, 1_5, tokenizer.pad_token_id, 1_5, 1_5, tokenizer.word_delimiter_token_id, tokenizer.pad_token_id, 1_5, 8, 8, 8, tokenizer.word_delimiter_token_id, 9_8] # fmt: on A = tokenizer.decode(__SCREAMING_SNAKE_CASE , output_char_offsets=__SCREAMING_SNAKE_CASE , filter_word_delimiter_token=__SCREAMING_SNAKE_CASE) # check Wav2Vec2CTCTokenizerOutput keys for char self.assertEqual(len(outputs.keys()) , 2) self.assertTrue("text" in outputs) self.assertTrue("char_offsets" in outputs) self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)) # check that order of chars is correct and identical for both outputs self.assertEqual(" ".join(self.get_from_offsets(outputs["char_offsets"] , "char")) , outputs.text) self.assertListEqual( self.get_from_offsets(outputs["char_offsets"] , "char") , ["k", "s", "ɾ", "ɾ", "|", "ɾ", "l", "|", "ɭʲ"]) # check that offsets are actually correct for char # 0-1 is 11, 1-4 is 5, 4-6 is first 15, 6-7 is <pad> (thus not shown), 7-9 is second 15, 9-10 is word_delimiter_token, # 10-11 is <pad> (thus not shown), 11-12 is third 15, 12-15 is 8, 15-16 is word_delimiter_token, 16-17 is 98 self.assertListEqual( self.get_from_offsets(outputs["char_offsets"] , "start_offset") , [0, 1, 4, 7, 9, 1_1, 1_2, 1_5, 1_6]) self.assertListEqual( self.get_from_offsets(outputs["char_offsets"] , "end_offset") , [1, 4, 6, 9, 1_0, 1_2, 1_5, 1_6, 1_7]) def SCREAMING_SNAKE_CASE__ (self : Any): A = self.get_tokenizer(word_delimiter_token="|") def check_list_tuples_equal(__SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : List[Any]): self.assertTrue(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)) self.assertTrue(isinstance(outputs_list[0] , __SCREAMING_SNAKE_CASE)) # transform list to ModelOutput A = WavaVecaPhonemeCTCTokenizerOutput( {k: [d[k] for d in outputs_list] for k in outputs_list[0]}) self.assertListEqual(outputs_batch["text"] , outputs_batch_a["text"]) def recursive_check(__SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any]): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): [recursive_check(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) for la, la in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) if "char_offsets" in outputs_batch: recursive_check(outputs_batch["char_offsets"] , outputs_batch_a["char_offsets"]) # fmt: off A = [ [1_1, 5, 1_5, tokenizer.pad_token_id, 1_5, 4, 8, 9_8, 3_2, 3_2, 3_2, 3_2, 4, 3_3, tokenizer.word_delimiter_token_id, 3_2, 3_2, 3_3, 3_4, 3_4], [2_4, 2_2, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 2_4, 2_2, 2_2, 2_2, 4, 5, 7_7, tokenizer.pad_token_id, 2_2, 2_2, 4, 3_4, 3_4, 3_4, 3_4], ] # fmt: on # We assume that `decode` works as expected. All we will check now is # the output type is correct and the output is identical to `decode` # char A = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE , output_char_offsets=__SCREAMING_SNAKE_CASE) A = [tokenizer.decode(__SCREAMING_SNAKE_CASE , output_char_offsets=__SCREAMING_SNAKE_CASE) for ids in sample_ids] check_list_tuples_equal(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) @unittest.skip("Wav2Vec2PhonemeTokenizer always lower cases letters to correctly map to phonemes") def SCREAMING_SNAKE_CASE__ (self : Optional[int]): pass @unittest.skip("Wav2Vec2PhonemeTokenizer always puts spaces between phonemes") def SCREAMING_SNAKE_CASE__ (self : Dict): pass @unittest.skip("encodes to text to ids, but decodes ids to phonemes -> not possible to have internal consistency") def SCREAMING_SNAKE_CASE__ (self : str): pass @unittest.skip("Wav2Vec2PhonemeModel has no max model length => no testing") def SCREAMING_SNAKE_CASE__ (self : Optional[int]): pass def SCREAMING_SNAKE_CASE__ (self : List[str]): A = self.get_tokenizers(do_lower_case=__SCREAMING_SNAKE_CASE) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}"""): A = tokenizer.vocab_size A = len(__SCREAMING_SNAKE_CASE) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) A = ["aaaaa bbbbbb", "cccccccccdddddddd"] A = tokenizer.add_tokens(__SCREAMING_SNAKE_CASE) A = tokenizer.vocab_size A = len(__SCREAMING_SNAKE_CASE) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE)) self.assertEqual(__SCREAMING_SNAKE_CASE , all_size + len(__SCREAMING_SNAKE_CASE)) A = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=__SCREAMING_SNAKE_CASE) self.assertGreaterEqual(len(__SCREAMING_SNAKE_CASE) , 4) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1) A = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} A = tokenizer.add_special_tokens(__SCREAMING_SNAKE_CASE) A = tokenizer.vocab_size A = len(__SCREAMING_SNAKE_CASE) self.assertNotEqual(__SCREAMING_SNAKE_CASE , 0) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) self.assertEqual(__SCREAMING_SNAKE_CASE , len(__SCREAMING_SNAKE_CASE)) self.assertEqual(__SCREAMING_SNAKE_CASE , all_size_a + len(__SCREAMING_SNAKE_CASE)) A = tokenizer.encode( ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=__SCREAMING_SNAKE_CASE) self.assertGreaterEqual(len(__SCREAMING_SNAKE_CASE) , 6) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1) self.assertGreater(tokens[0] , tokens[1]) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1) self.assertGreater(tokens[-3] , tokens[-4]) self.assertEqual(tokens[0] , tokenizer.eos_token_id) self.assertEqual(tokens[-3] , tokenizer.pad_token_id) @unittest.skip("The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode.") def SCREAMING_SNAKE_CASE__ (self : List[str]): pass @unittest.skip("The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode.") def SCREAMING_SNAKE_CASE__ (self : List[Any]): pass def SCREAMING_SNAKE_CASE__ (self : Optional[int]): # The default common tokenizer tests assumes that the output of `convert_tokens_to_string` is a string which # is not the case for Wav2Vec2PhonemeCTCTokenizer. A = self.get_tokenizers(fast=__SCREAMING_SNAKE_CASE , do_lower_case=__SCREAMING_SNAKE_CASE) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}"""): A = ["ð", "ɪ", "s", "ɪ", "z", "ɐ", "t", "ɛ", "k", "s", "t"] A = tokenizer.convert_tokens_to_string(__SCREAMING_SNAKE_CASE) self.assertIsInstance(output["text"] , __SCREAMING_SNAKE_CASE)
57
1