code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' import string from math import logaa def lowerCAmelCase_ ( __A : str , __A : str ): '''simple docstring''' snake_case: List[str] = document.translate( str.maketrans('' , '' , string.punctuation ) ).replace('\n' , '' ) snake_case: List[str] = document_without_punctuation.split(' ' ) # word tokenization return len([word for word in tokenize_document if word.lower() == term.lower()] ) def lowerCAmelCase_ ( __A : str , __A : str ): '''simple docstring''' snake_case: List[Any] = corpus.lower().translate( str.maketrans('' , '' , string.punctuation ) ) # strip all punctuation and replace it with '' snake_case: Optional[int] = corpus_without_punctuation.split('\n' ) snake_case: Union[str, Any] = term.lower() return (len([doc for doc in docs if term in doc] ), len(__A )) def lowerCAmelCase_ ( __A : int , __A : int , __A : Any=False ): '''simple docstring''' if smoothing: if n == 0: raise ValueError('log10(0) is undefined.' ) return round(1 + logaa(n / (1 + df) ) , 3 ) if df == 0: raise ZeroDivisionError('df must be > 0' ) elif n == 0: raise ValueError('log10(0) is undefined.' ) return round(logaa(n / df ) , 3 ) def lowerCAmelCase_ ( __A : int , __A : int ): '''simple docstring''' return round(tf * idf , 3 )
692
'''simple docstring''' import math def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCAmelCase_ ( __A : float = 0.1 ): '''simple docstring''' snake_case: Optional[int] = 3 snake_case: int = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(__A ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''simple docstring''' __UpperCAmelCase = 256 # Modulus to hash a string __UpperCAmelCase = 1_000_003 def lowerCAmelCase_ ( __A : str , __A : str ): '''simple docstring''' snake_case: List[Any] = len(__A ) snake_case: Dict = len(__A ) if p_len > t_len: return False snake_case: Dict = 0 snake_case: int = 0 snake_case: int = 1 # Calculating the hash of pattern and substring of text for i in range(__A ): snake_case: List[Any] = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus snake_case: Union[str, Any] = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue snake_case: Any = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash snake_case: Any = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Dict = 'abc1abc12' snake_case: Any = 'alskfjaldsabc1abc1abc12k23adsfabcabc' snake_case: Union[str, Any] = 'alskfjaldsk23adsfabcabc' assert rabin_karp(__A , __A ) and not rabin_karp(__A , __A ) # Test 2) snake_case: List[Any] = 'ABABX' snake_case: Optional[int] = 'ABABZABABYABABX' assert rabin_karp(__A , __A ) # Test 3) snake_case: Tuple = 'AAAB' snake_case: Any = 'ABAAAAAB' assert rabin_karp(__A , __A ) # Test 4) snake_case: str = 'abcdabcy' snake_case: Optional[Any] = 'abcxabcdabxabcdabcdabcy' assert rabin_karp(__A , __A ) # Test 5) snake_case: Any = 'Lü' snake_case: Optional[int] = 'Lüsai' assert rabin_karp(__A , __A ) snake_case: Optional[Any] = 'Lue' assert not rabin_karp(__A , __A ) print('Success.' ) if __name__ == "__main__": test_rabin_karp()
692
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): __UpperCAmelCase = "pt" elif is_tf_available(): __UpperCAmelCase = "tf" else: __UpperCAmelCase = "jax" class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ByTaTokenizer __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: int = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _UpperCamelCase ( self ): '''simple docstring''' return ByTaTokenizer.from_pretrained('google/byt5-small' ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=20 , SCREAMING_SNAKE_CASE__=5 ): '''simple docstring''' snake_case: Optional[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): try: snake_case: Optional[Any] = tokenizer.decode([i] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) except UnicodeDecodeError: pass toks.append((i, tok) ) snake_case: List[str] = list(filter(lambda SCREAMING_SNAKE_CASE__ : re.match(r'^[ a-zA-Z]+$' , t[1] ) , SCREAMING_SNAKE_CASE__ ) ) snake_case: str = list(filter(lambda SCREAMING_SNAKE_CASE__ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) ) if max_length is not None and len(SCREAMING_SNAKE_CASE__ ) > max_length: snake_case: Union[str, Any] = 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: snake_case: Tuple = toks + toks # toks_str = [t[1] for t in toks] snake_case: Dict = [t[0] for t in toks] # Ensure consistency snake_case: int = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) if " " not in output_txt and len(SCREAMING_SNAKE_CASE__ ) > 1: snake_case: str = ( 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: snake_case: Tuple = ' ' + output_txt snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) return output_txt, output_ids def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: str = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) snake_case: List[Any] = tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: Union[str, Any] = 'Unicode €.' snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = [88, 1_13, 1_08, 1_02, 1_14, 1_03, 1_04, 35, 2_29, 1_33, 1_75, 49, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[str] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'Unicode €.</s>' ) snake_case: List[Any] = tokenizer('e è é ê ë' ) snake_case: Optional[Any] = [1_04, 35, 1_98, 1_71, 35, 1_98, 1_72, 35, 1_98, 1_73, 35, 1_98, 1_74, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.ta_base_tokenizer snake_case: Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off snake_case: Optional[int] = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 1, 0] # fmt: on snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if FRAMEWORK != "jax": snake_case: Optional[Any] = list(batch.input_ids.numpy()[0] ) else: snake_case: Dict = list(batch.input_ids.tolist()[0] ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.ta_base_tokenizer snake_case: List[str] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] snake_case: Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertIn('attention_mask' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_attention_mask' , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.ta_base_tokenizer snake_case: str = [ 'Summary of the text.', 'Another summary.', ] snake_case: Dict = tokenizer( text_target=SCREAMING_SNAKE_CASE__ , max_length=32 , padding='max_length' , truncation=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.ta_base_tokenizer snake_case: Optional[int] = ['A long paragraph for summarization. </s>'] snake_case: str = ['Summary of the text. </s>'] # fmt: off snake_case: str = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 35, 1] snake_case: Optional[int] = [86, 1_20, 1_12, 1_12, 1_00, 1_17, 1_24, 35, 1_14, 1_05, 35, 1_19, 1_07, 1_04, 35, 1_19, 1_04, 1_23, 1_19, 49, 35, 1] # fmt: on snake_case: List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ , text_target=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['input_ids'][0] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['labels'][0] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test snake_case: Optional[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: Union[str, Any] = tempfile.mkdtemp() snake_case: Dict = ' He is very happy, UNwant\u00E9d,running' snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Any = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: List[str] = tempfile.mkdtemp() snake_case: str = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) snake_case: List[str] = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) snake_case: int = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) snake_case: Union[str, Any] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: snake_case: Any = json.load(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: snake_case: str = json.load(SCREAMING_SNAKE_CASE__ ) snake_case: int = [F"""<extra_id_{i}>""" for i in range(1_25 )] snake_case: Optional[int] = added_tokens_extra_ids + [ 'an_additional_special_token' ] snake_case: str = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files snake_case: Dict = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained snake_case: Union[str, Any] = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=SCREAMING_SNAKE_CASE__ )] snake_case: Union[str, Any] = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.decode([2_55] ) == '' ) def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_tokenizers(fast=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Union[str, Any] = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] snake_case: List[str] = tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Optional[Any] = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] snake_case: Dict = 0 snake_case: List[Any] = tokenizer.convert_ids_to_tokens( SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) for attr in attributes_list: setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [] ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
692
1
'''simple docstring''' from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass __UpperCAmelCase = (3, 9, -11, 0, 7, 5, 1, -1) __UpperCAmelCase = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = 42 __UpperCamelCase = 42 class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Node | None = None for i in sorted(SCREAMING_SNAKE_CASE__ , reverse=SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = Node(SCREAMING_SNAKE_CASE__ , self.head ) def __iter__( self ): '''simple docstring''' snake_case: str = self.head while node: yield node.data snake_case: Dict = node.next_node def __len__( self ): '''simple docstring''' return sum(1 for _ in self ) def __str__( self ): '''simple docstring''' return " -> ".join([str(SCREAMING_SNAKE_CASE__ ) for node in self] ) def lowerCAmelCase_ ( __A : SortedLinkedList , __A : SortedLinkedList ): '''simple docstring''' return SortedLinkedList(list(__A ) + list(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
692
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = "layer_norm" , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__() snake_case: List[str] = only_cross_attention snake_case: Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero' snake_case: Tuple = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to""" F""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""" ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: snake_case: List[str] = AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: snake_case: str = AdaLayerNormZero(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: snake_case: int = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = Attention( query_dim=SCREAMING_SNAKE_CASE__ , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. snake_case: Tuple = ( AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) ) snake_case: Any = Attention( query_dim=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # is self-attn if encoder_hidden_states is none else: snake_case: int = None snake_case: Tuple = None # 3. Feed-forward snake_case: Union[str, Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = FeedForward(SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , activation_fn=SCREAMING_SNAKE_CASE__ , final_dropout=SCREAMING_SNAKE_CASE__ ) # let chunk size default to None snake_case: Any = None snake_case: Any = 0 def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = chunk_size snake_case: str = dim def _UpperCamelCase ( 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 , ): '''simple docstring''' if self.use_ada_layer_norm: snake_case: Optional[int] = self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: snake_case , snake_case , snake_case , snake_case , snake_case: int = self.norma( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=hidden_states.dtype ) else: snake_case: List[str] = self.norma(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = cross_attention_kwargs if cross_attention_kwargs is not None else {} snake_case: List[str] = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if self.use_ada_layer_norm_zero: snake_case: Tuple = gate_msa.unsqueeze(1 ) * attn_output snake_case: List[str] = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: snake_case: Dict = ( self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else self.norma(SCREAMING_SNAKE_CASE__ ) ) snake_case: Any = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case: List[str] = attn_output + hidden_states # 3. Feed-forward snake_case: str = self.norma(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: snake_case: str = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""" ) snake_case: List[str] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size snake_case: Optional[Any] = torch.cat( [self.ff(SCREAMING_SNAKE_CASE__ ) for hid_slice in norm_hidden_states.chunk(SCREAMING_SNAKE_CASE__ , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: snake_case: int = self.ff(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: snake_case: Union[str, Any] = gate_mlp.unsqueeze(1 ) * ff_output snake_case: Tuple = ff_output + hidden_states return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 4 , SCREAMING_SNAKE_CASE__ = 0.0 , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__() snake_case: int = int(dim * mult ) snake_case: Optional[Any] = dim_out if dim_out is not None else dim if activation_fn == "gelu": snake_case: int = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if activation_fn == "gelu-approximate": snake_case: Optional[Any] = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , approximate='tanh' ) elif activation_fn == "geglu": snake_case: List[Any] = GEGLU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif activation_fn == "geglu-approximate": snake_case: Optional[int] = ApproximateGELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Any = nn.ModuleList([] ) # project in self.net.append(SCREAMING_SNAKE_CASE__ ) # project dropout self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) # project out self.net.append(nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' for module in self.net: snake_case: Optional[int] = module(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "none" ): '''simple docstring''' super().__init__() snake_case: Optional[int] = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = approximate def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.proj(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = self.gelu(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = nn.Linear(SCREAMING_SNAKE_CASE__ , dim_out * 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case , snake_case: int = self.proj(SCREAMING_SNAKE_CASE__ ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = self.proj(SCREAMING_SNAKE_CASE__ ) return x * torch.sigmoid(1.7_02 * x ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Optional[Any] = nn.Embedding(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = nn.SiLU() snake_case: Union[str, Any] = nn.Linear(SCREAMING_SNAKE_CASE__ , embedding_dim * 2 ) snake_case: int = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ ) ) ) snake_case , snake_case: Dict = torch.chunk(SCREAMING_SNAKE_CASE__ , 2 ) snake_case: str = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale) + shift return x class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = CombinedTimestepLabelEmbeddings(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.SiLU() snake_case: Any = nn.Linear(SCREAMING_SNAKE_CASE__ , 6 * embedding_dim , bias=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ , eps=1E-6 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' snake_case: int = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=SCREAMING_SNAKE_CASE__ ) ) ) snake_case , snake_case , snake_case , snake_case , snake_case , snake_case: str = emb.chunk(6 , dim=1 ) snake_case: Dict = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 1E-5 ): '''simple docstring''' super().__init__() snake_case: str = num_groups snake_case: str = eps if act_fn is None: snake_case: Dict = None else: snake_case: List[str] = get_activation(SCREAMING_SNAKE_CASE__ ) snake_case: Any = nn.Linear(SCREAMING_SNAKE_CASE__ , out_dim * 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.act: snake_case: Optional[Any] = self.act(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.linear(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = emb[:, :, None, None] snake_case , snake_case: List[Any] = emb.chunk(2 , dim=1 ) snake_case: Any = F.group_norm(SCREAMING_SNAKE_CASE__ , self.num_groups , eps=self.eps ) snake_case: Optional[int] = x * (1 + scale) + shift return x
692
1
'''simple docstring''' def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' snake_case: str = [0] * len(__A ) snake_case: Tuple = [] snake_case: Tuple = [1] * len(__A ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__A ) ): if indegree[i] == 0: queue.append(__A ) while queue: snake_case: int = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: snake_case: Any = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(__A ) print(max(__A ) ) # Adjacency list of Graph __UpperCAmelCase = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
692
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = RoCBertTokenizer __UpperCamelCase = None __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = filter_non_english def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: Any = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '你', '好', '是', '谁', 'a', 'b', 'c', 'd'] snake_case: List[Any] = {} snake_case: List[str] = {} for i, value in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = i snake_case: Union[str, Any] = i snake_case: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) snake_case: Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] ) snake_case: str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: Dict = tokenizer.tokenize('你好[SEP]你是谁' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['你', '好', '[SEP]', '你', '是', '谁'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] snake_case: Union[str, Any] = {} for i, token in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: str = i snake_case: Optional[int] = RoCBertWordpieceTokenizer(vocab=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) if self.test_rust_tokenizer: snake_case: int = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) def _UpperCamelCase ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" snake_case: List[str] = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , ) snake_case: Optional[int] = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE__ , 'do_lower_case' ) else False snake_case: int = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'Allen'), ((21, 23), '##NL'), ((23, 24), '##P'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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, 15), tokenizer_r.mask_token), ((16, 21), 'allen'), ((21, 23), '##nl'), ((23, 24), '##p'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = ['的', '人', '有'] snake_case: Any = ''.join(SCREAMING_SNAKE_CASE__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = True snake_case: List[Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = False snake_case: Union[str, Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: int = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that only the first Chinese character is not preceded by "##". snake_case: Union[str, Any] = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE__ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: int = tokenizer.encode('你好' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Any = tokenizer.encode('你是谁' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Dict = '你好,你是谁' snake_case: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer.prepare_for_model( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.encode_plus(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
692
1
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = StableDiffusionPanoramaPipeline __UpperCamelCase = TEXT_TO_IMAGE_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS def _UpperCamelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) snake_case: Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) snake_case: Dict = DDIMScheduler() torch.manual_seed(0 ) snake_case: Tuple = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) snake_case: Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) snake_case: Optional[int] = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) snake_case: str = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) snake_case: Optional[int] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0 ): '''simple docstring''' snake_case: Union[str, Any] = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = { 'prompt': 'a photo of the dolomites', 'generator': generator, # Setting height and width to None to prevent OOMs on CPU. 'height': None, 'width': None, 'num_inference_steps': 1, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case: Optional[int] = self.get_dummy_components() snake_case: Union[str, Any] = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) snake_case: Any = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images snake_case: str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case: Optional[Any] = np.array([0.61_86, 0.53_74, 0.49_15, 0.41_35, 0.41_14, 0.45_63, 0.51_28, 0.49_77, 0.47_57] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _UpperCamelCase ( self ): '''simple docstring''' super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def _UpperCamelCase ( self ): '''simple docstring''' super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case: Union[str, Any] = self.get_dummy_components() snake_case: int = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) snake_case: int = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = 'french fries' snake_case: List[str] = sd_pipe(**SCREAMING_SNAKE_CASE__ , negative_prompt=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = output.images snake_case: Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case: List[Any] = np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case: Any = self.get_dummy_components() snake_case: List[Any] = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = sd_pipe(**SCREAMING_SNAKE_CASE__ , view_batch_size=2 ) snake_case: List[str] = output.images snake_case: str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case: List[str] = np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case: str = self.get_dummy_components() snake_case: Any = EulerAncestralDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' ) snake_case: List[str] = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images snake_case: List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case: Tuple = np.array([0.40_24, 0.65_10, 0.49_01, 0.53_78, 0.58_13, 0.56_22, 0.47_95, 0.44_67, 0.49_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case: Any = self.get_dummy_components() snake_case: Dict = PNDMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , skip_prk_steps=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) snake_case: int = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images snake_case: Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case: str = np.array([0.63_91, 0.62_91, 0.48_61, 0.51_34, 0.55_52, 0.45_78, 0.50_32, 0.50_23, 0.45_39] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__=0 ): '''simple docstring''' snake_case: Optional[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) snake_case: str = { 'prompt': 'a photo of the dolomites', 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = 'stabilityai/stable-diffusion-2-base' snake_case: Optional[Any] = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder='scheduler' ) snake_case: List[str] = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() snake_case: int = self.get_inputs() snake_case: Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images snake_case: Tuple = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) snake_case: List[str] = np.array( [ 0.36_96_83_92, 0.27_02_53_72, 0.32_44_67_66, 0.28_37_93_87, 0.36_36_32_74, 0.30_73_33_47, 0.27_10_00_27, 0.27_05_41_25, 0.25_53_60_96, ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-2 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = StableDiffusionPanoramaPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-base' , safety_checker=SCREAMING_SNAKE_CASE__ ) snake_case: Any = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() snake_case: Tuple = self.get_inputs() snake_case: Union[str, Any] = pipe(**SCREAMING_SNAKE_CASE__ ).images snake_case: Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) snake_case: str = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = 0 def callback_fn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> None: snake_case: Any = True nonlocal number_of_steps number_of_steps += 1 if step == 1: snake_case: Tuple = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) snake_case: str = latents[0, -3:, -3:, -1] snake_case: Optional[int] = np.array( [ 0.18_68_18_69, 0.33_90_78_16, 0.5_36_12_76, 0.14_43_28_65, -0.02_85_66_11, -0.73_94_11_23, 0.23_39_79_87, 0.47_32_26_82, -0.37_82_31_64, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: snake_case: str = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) snake_case: List[Any] = latents[0, -3:, -3:, -1] snake_case: Any = np.array( [ 0.18_53_96_45, 0.33_98_72_48, 0.5_37_85_59, 0.14_43_71_42, -0.02_45_52_61, -0.7_33_83_17, 0.23_99_07_55, 0.47_35_62_72, -0.3_78_65_05, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 snake_case: Any = False snake_case: List[str] = 'stabilityai/stable-diffusion-2-base' snake_case: Dict = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder='scheduler' ) snake_case: Union[str, Any] = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() snake_case: int = self.get_inputs() pipe(**SCREAMING_SNAKE_CASE__ , callback=SCREAMING_SNAKE_CASE__ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def _UpperCamelCase ( self ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() snake_case: Tuple = 'stabilityai/stable-diffusion-2-base' snake_case: Union[str, Any] = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder='scheduler' ) snake_case: str = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() snake_case: Tuple = self.get_inputs() snake_case: Optional[int] = pipe(**SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
692
'''simple docstring''' from math import asin, atan, cos, radians, sin, sqrt, tan __UpperCAmelCase = 6378137.0 __UpperCAmelCase = 6356752.314245 __UpperCAmelCase = 6_378_137 def lowerCAmelCase_ ( __A : float , __A : float , __A : float , __A : float ): '''simple docstring''' snake_case: Optional[Any] = (AXIS_A - AXIS_B) / AXIS_A snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: Tuple = radians(__A ) snake_case: Tuple = radians(__A ) # Equation snake_case: List[Any] = sin((phi_a - phi_a) / 2 ) snake_case: Dict = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda snake_case: Union[str, Any] = sqrt(sin_sq_phi + (cos(__A ) * cos(__A ) * sin_sq_lambda) ) return 2 * RADIUS * asin(__A ) if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''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, )
692
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCAmelCase = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
1
'''simple docstring''' __UpperCAmelCase = "\n# Transformers 설치 방법\n! pip install transformers datasets\n# 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" __UpperCAmelCase = [{"type": "code", "content": INSTALL_CONTENT}] __UpperCAmelCase = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
692
'''simple docstring''' import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def lowerCAmelCase_ ( __A : Tuple ): '''simple docstring''' snake_case: Tuple = model.config snake_case: str = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=1_28 , ) snake_case: Optional[Any] = MBartConfig( is_decoder=__A , is_encoder_decoder=__A , add_cross_attention=__A , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=__A , add_final_layer_norm=__A , ) return encoder_config, decoder_config def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if "encoder.model" in name: snake_case: Optional[Any] = name.replace('encoder.model' , 'encoder' ) if "decoder.model" in name: snake_case: str = name.replace('decoder.model' , 'decoder' ) if "patch_embed.proj" in name: snake_case: Any = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: snake_case: Optional[int] = name.replace('patch_embed.norm' , 'embeddings.norm' ) if name.startswith('encoder' ): if "layers" in name: snake_case: Tuple = 'encoder.' + name if "attn.proj" in name: snake_case: Optional[int] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name and "mask" not in name: snake_case: Dict = name.replace('attn' , 'attention.self' ) if "norm1" in name: snake_case: Union[str, Any] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: snake_case: Dict = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: snake_case: List[str] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: snake_case: Dict = name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": snake_case: Dict = 'encoder.layernorm.weight' if name == "encoder.norm.bias": snake_case: int = 'encoder.layernorm.bias' return name def lowerCAmelCase_ ( __A : List[Any] , __A : Optional[Any] ): '''simple docstring''' for key in orig_state_dict.copy().keys(): snake_case: List[Any] = orig_state_dict.pop(__A ) if "qkv" in key: snake_case: Union[str, Any] = key.split('.' ) snake_case: Optional[Any] = int(key_split[3] ) snake_case: Any = int(key_split[5] ) snake_case: Union[str, Any] = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: snake_case: Union[str, Any] = val[:dim, :] snake_case: Any = val[dim : dim * 2, :] snake_case: List[str] = val[-dim:, :] else: snake_case: str = val[:dim] snake_case: Union[str, Any] = val[dim : dim * 2] snake_case: List[Any] = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: snake_case: Optional[int] = val return orig_state_dict def lowerCAmelCase_ ( __A : List[Any] , __A : Any=None , __A : List[str]=False ): '''simple docstring''' snake_case: str = DonutModel.from_pretrained(__A ).eval() # load HuggingFace model snake_case , snake_case: Optional[Any] = get_configs(__A ) snake_case: Optional[int] = DonutSwinModel(__A ) snake_case: Tuple = MBartForCausalLM(__A ) snake_case: Optional[Any] = VisionEncoderDecoderModel(encoder=__A , decoder=__A ) model.eval() snake_case: Optional[int] = original_model.state_dict() snake_case: Optional[int] = convert_state_dict(__A , __A ) model.load_state_dict(__A ) # verify results on scanned document snake_case: Union[str, Any] = load_dataset('hf-internal-testing/example-documents' ) snake_case: str = dataset['test'][0]['image'].convert('RGB' ) snake_case: Optional[int] = XLMRobertaTokenizerFast.from_pretrained(__A , from_slow=__A ) snake_case: Any = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) snake_case: Dict = DonutProcessor(__A , __A ) snake_case: Optional[Any] = processor(__A , return_tensors='pt' ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": snake_case: int = '<s_docvqa><s_question>{user_input}</s_question><s_answer>' snake_case: Optional[Any] = 'When is the coffee break?' snake_case: Optional[int] = task_prompt.replace('{user_input}' , __A ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": snake_case: Dict = '<s_rvlcdip>' elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: snake_case: str = '<s_cord>' elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": snake_case: str = 's_cord-v2>' elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": snake_case: int = '<s_zhtrainticket>' elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt snake_case: Optional[Any] = 'hello world' else: raise ValueError('Model name not supported' ) snake_case: Optional[int] = original_model.decoder.tokenizer(__A , add_special_tokens=__A , return_tensors='pt' )[ 'input_ids' ] snake_case: Any = original_model.encoder.model.patch_embed(__A ) snake_case , snake_case: Dict = model.encoder.embeddings(__A ) assert torch.allclose(__A , __A , atol=1E-3 ) # verify encoder hidden states snake_case: Tuple = original_model.encoder(__A ) snake_case: List[str] = model.encoder(__A ).last_hidden_state assert torch.allclose(__A , __A , atol=1E-2 ) # verify decoder hidden states snake_case: List[Any] = original_model(__A , __A , __A ).logits snake_case: List[Any] = model(__A , decoder_input_ids=__A ).logits assert torch.allclose(__A , __A , atol=1E-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(__A ) processor.save_pretrained(__A ) if push_to_hub: model.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) processor.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) __UpperCAmelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
692
1
'''simple docstring''' import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("Googling.....") __UpperCAmelCase = "https://www.google.com/search?q=" + " ".join(sys.argv[1:]) __UpperCAmelCase = requests.get(url, headers={"UserAgent": UserAgent().random}) # res.raise_for_status() with open("project1a.html", "wb") as out_file: # only for knowing the class for data in res.iter_content(10_000): out_file.write(data) __UpperCAmelCase = BeautifulSoup(res.text, "html.parser") __UpperCAmelCase = list(soup.select(".eZt8xd"))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get("href")) else: webbrowser.open(F'https://google.com{link.get("href")}')
692
'''simple docstring''' 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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = { 'task_specific_params': { 'summarization': {'length_penalty': 1.0, 'max_length': 1_28, 'min_length': 12, 'num_beams': 4}, 'summarization_cnn': {'length_penalty': 2.0, 'max_length': 1_42, 'min_length': 56, 'num_beams': 4}, 'summarization_xsum': {'length_penalty': 1.0, 'max_length': 62, 'min_length': 11, 'num_beams': 6}, } } snake_case: Union[str, Any] = { 'task_specific_params.summarization.length_penalty': 1.0, 'task_specific_params.summarization.max_length': 1_28, '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': 1_42, '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(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , x.transpose() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = np.random.randn(3 , 4 ) snake_case: Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(3 , 4 , 5 ) snake_case: Optional[int] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Dict = np.random.randn(3 , 4 , 5 ) snake_case: str = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Optional[int] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Optional[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) snake_case: Optional[int] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: str = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: List[str] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.squeeze(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: List[str] = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) snake_case: List[str] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: int = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = np.random.randn(1 , 3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Union[str, Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(1 , 3 , 4 ) snake_case: List[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Tuple = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Tuple = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Any = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Any = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = np.random.randn(3 , 4 ) snake_case: int = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.asarray(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) )
692
1
'''simple docstring''' from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf __UpperCAmelCase = logging.get_logger(__name__) @dataclass class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = [ "no_inference", "no_cuda", "no_tpu", "no_speed", "no_memory", "no_env_print", "no_multi_process", ] def __init__( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: snake_case: Union[str, Any] = deprecated_arg[3:] snake_case: Any = not kwargs.pop(SCREAMING_SNAKE_CASE__ ) logger.warning( F"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or""" F""" {positive_arg}={kwargs[positive_arg]}""" ) snake_case: int = kwargs.pop('tpu_name' , self.tpu_name ) snake_case: Tuple = kwargs.pop('device_idx' , self.device_idx ) snake_case: str = kwargs.pop('eager_mode' , self.eager_mode ) snake_case: str = kwargs.pop('use_xla' , self.use_xla ) super().__init__(**SCREAMING_SNAKE_CASE__ ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Name of TPU"} , ) __UpperCamelCase = field( default=0 , metadata={"help": "CPU / GPU device index. Defaults to 0."} , ) __UpperCamelCase = field(default=snake_case , metadata={"help": "Benchmark models in eager model."} ) __UpperCamelCase = field( default=snake_case , metadata={ "help": "Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`." } , ) @cached_property def _UpperCamelCase ( self ): '''simple docstring''' requires_backends(self , ['tf'] ) snake_case: List[Any] = None if self.tpu: try: if self.tpu_name: snake_case: List[Any] = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: snake_case: Dict = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: snake_case: Any = None return tpu @cached_property def _UpperCamelCase ( self ): '''simple docstring''' requires_backends(self , ['tf'] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) snake_case: Union[str, Any] = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , 'GPU' ) snake_case: str = tf.distribute.OneDeviceStrategy(device=F"""/gpu:{self.device_idx}""" ) else: tf.config.set_visible_devices([] , 'GPU' ) # disable GPU snake_case: str = tf.distribute.OneDeviceStrategy(device=F"""/cpu:{self.device_idx}""" ) return strategy @property def _UpperCamelCase ( self ): '''simple docstring''' requires_backends(self , ['tf'] ) return self._setup_tpu is not None @property def _UpperCamelCase ( self ): '''simple docstring''' requires_backends(self , ['tf'] ) return self._setup_strategy @property def _UpperCamelCase ( self ): '''simple docstring''' requires_backends(self , ['tf'] ) return tf.config.list_physical_devices('GPU' ) @property def _UpperCamelCase ( self ): '''simple docstring''' requires_backends(self , ['tf'] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _UpperCamelCase ( self ): '''simple docstring''' return self.n_gpu > 0
692
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig __UpperCAmelCase = logging.get_logger(__name__) # General docstring __UpperCAmelCase = "PoolFormerConfig" # Base docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = [1, 512, 7, 7] # Image classification docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = "tabby, tabby cat" __UpperCAmelCase = [ "sail/poolformer_s12", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCAmelCase_ ( __A : Tuple , __A : float = 0.0 , __A : bool = False ): '''simple docstring''' if drop_prob == 0.0 or not training: return input snake_case: Union[str, Any] = 1 - drop_prob snake_case: List[Any] = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets snake_case: List[Any] = keep_prob + torch.rand(__A , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize snake_case: Any = input.div(__A ) * random_tensor return output class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' super().__init__() snake_case: List[str] = drop_prob def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return drop_path(SCREAMING_SNAKE_CASE__ , self.drop_prob , self.training ) def _UpperCamelCase ( self ): '''simple docstring''' return "p={}".format(self.drop_prob ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' super().__init__() snake_case: List[str] = patch_size if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (patch_size, patch_size) snake_case: List[str] = stride if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (stride, stride) snake_case: Union[str, Any] = padding if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (padding, padding) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , kernel_size=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = norm_layer(SCREAMING_SNAKE_CASE__ ) if norm_layer else nn.Identity() def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.projection(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.norm(SCREAMING_SNAKE_CASE__ ) return embeddings class SCREAMING_SNAKE_CASE ( nn.GroupNorm ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(1 , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.AvgPoolad(SCREAMING_SNAKE_CASE__ , stride=1 , padding=pool_size // 2 , count_include_pad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.pool(SCREAMING_SNAKE_CASE__ ) - hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: str = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if isinstance(config.hidden_act , SCREAMING_SNAKE_CASE__ ): snake_case: Tuple = ACTaFN[config.hidden_act] else: snake_case: int = config.hidden_act def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.act_fn(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.drop(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: str = self.drop(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = PoolFormerPooling(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerOutput(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) # Useful for training neural nets snake_case: Union[str, Any] = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if drop_path > 0.0 else nn.Identity() snake_case: Optional[Any] = config.use_layer_scale if config.use_layer_scale: snake_case: Any = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.use_layer_scale: snake_case: str = self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Dict = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection snake_case: str = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = () snake_case: Dict = self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Union[str, Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection snake_case: Any = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = (output,) + outputs return outputs else: snake_case: Optional[Any] = self.drop_path(self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) ) # First residual connection snake_case: Union[str, Any] = pooling_output + hidden_states snake_case: List[Any] = () # Second residual connection inside the PoolFormerOutput block snake_case: List[str] = self.drop_path(self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: Dict = hidden_states + layer_output snake_case: Optional[Any] = (output,) + outputs return outputs class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = config # stochastic depth decay rule snake_case: List[Any] = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings snake_case: Union[str, Any] = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) snake_case: List[Any] = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) # Transformer blocks snake_case: str = [] snake_case: int = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers snake_case: List[str] = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( SCREAMING_SNAKE_CASE__ , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(SCREAMING_SNAKE_CASE__ ) ) snake_case: Tuple = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True ): '''simple docstring''' snake_case: str = () if output_hidden_states else None snake_case: Dict = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): snake_case , snake_case: Dict = layers # Get patch embeddings from hidden_states snake_case: int = embedding_layer(SCREAMING_SNAKE_CASE__ ) # Send the embeddings through the blocks for _, blk in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = blk(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = layer_outputs[0] if output_hidden_states: snake_case: List[str] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = PoolFormerConfig __UpperCamelCase = "poolformer" __UpperCamelCase = "pixel_values" __UpperCamelCase = True def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = value __UpperCAmelCase = R"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" __UpperCAmelCase = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n" @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = config snake_case: Tuple = PoolFormerEncoder(SCREAMING_SNAKE_CASE__ ) # Initialize weights and apply final processing self.post_init() def _UpperCamelCase ( self ): '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Optional[int] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case: List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) snake_case: Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: List[Any] = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=encoder_outputs.hidden_states , ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Any = nn.Linear(config.hidden_size , config.hidden_size ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.dense(SCREAMING_SNAKE_CASE__ ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = config.num_labels snake_case: str = PoolFormerModel(SCREAMING_SNAKE_CASE__ ) # Final norm snake_case: int = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head snake_case: Dict = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict snake_case: Optional[Any] = self.poolformer( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: Any = outputs[0] snake_case: str = self.classifier(self.norm(SCREAMING_SNAKE_CASE__ ).mean([-2, -1] ) ) snake_case: Any = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: snake_case: Tuple = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): snake_case: Dict = 'single_label_classification' else: snake_case: List[str] = 'multi_label_classification' if self.config.problem_type == "regression": snake_case: Union[str, Any] = MSELoss() if self.num_labels == 1: snake_case: List[str] = loss_fct(logits.squeeze() , labels.squeeze() ) else: snake_case: int = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.config.problem_type == "single_label_classification": snake_case: Union[str, Any] = CrossEntropyLoss() snake_case: Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": snake_case: int = BCEWithLogitsLoss() snake_case: Optional[int] = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not return_dict: snake_case: str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=SCREAMING_SNAKE_CASE__ , logits=SCREAMING_SNAKE_CASE__ , hidden_states=outputs.hidden_states )
692
1
'''simple docstring''' def lowerCAmelCase_ ( __A : int , __A : Any ): '''simple docstring''' snake_case: int = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def lowerCAmelCase_ ( __A : int , __A : Optional[int] , __A : List[Any] ): '''simple docstring''' snake_case: List[Any] = 0 while b > 0: if b & 1: snake_case: Union[str, Any] = ((res % c) + (a % c)) % c a += a b >>= 1 return res
692
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def lowerCAmelCase_ ( __A : dict , __A : str , __A : set , __A : set , __A : dict , __A : dict , __A : PriorityQueue , __A : dict , __A : float | int , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue snake_case: Any = cst_fwd.get(__A , np.inf ) snake_case: int = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) snake_case: Union[str, Any] = new_cost_f snake_case: Tuple = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: snake_case: List[str] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def lowerCAmelCase_ ( __A : str , __A : str , __A : dict , __A : dict ): '''simple docstring''' snake_case: Optional[Any] = -1 snake_case: Any = set() snake_case: str = set() snake_case: int = {source: 0} snake_case: Dict = {destination: 0} snake_case: int = {source: None} snake_case: Union[str, Any] = {destination: None} snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: Tuple = 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(): snake_case , snake_case: List[str] = queue_forward.get() visited_forward.add(__A ) snake_case , snake_case: int = queue_backward.get() visited_backward.add(__A ) snake_case: str = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) snake_case: Optional[Any] = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: snake_case: Any = shortest_distance return shortest_path_distance __UpperCAmelCase = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } __UpperCAmelCase = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''simple docstring''' import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @property def _UpperCamelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) snake_case: Union[str, Any] = 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 @property def _UpperCamelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) snake_case: str = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _UpperCamelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) snake_case: Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModel(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.dummy_uncond_unet snake_case: Optional[Any] = DDIMScheduler() snake_case: Union[str, Any] = self.dummy_vq_model snake_case: Union[str, Any] = LDMPipeline(unet=SCREAMING_SNAKE_CASE__ , vqvae=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ldm.to(SCREAMING_SNAKE_CASE__ ) ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = torch.manual_seed(0 ) snake_case: Dict = ldm(generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type='numpy' ).images snake_case: Union[str, Any] = torch.manual_seed(0 ) snake_case: List[Any] = ldm(generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=2 , output_type='numpy' , return_dict=SCREAMING_SNAKE_CASE__ )[0] snake_case: Union[str, Any] = image[0, -3:, -3:, -1] snake_case: Tuple = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case: Optional[int] = np.array([0.85_12, 0.8_18, 0.64_11, 0.68_08, 0.44_65, 0.56_18, 0.46, 0.62_31, 0.51_72] ) snake_case: Union[str, Any] = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(SCREAMING_SNAKE_CASE__ ) ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: int = torch.manual_seed(0 ) snake_case: Union[str, Any] = ldm(generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=5 , output_type='numpy' ).images snake_case: Any = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) snake_case: Optional[int] = np.array([0.43_99, 0.4_49_75, 0.4_68_25, 0.4_74, 0.43_59, 0.45_81, 0.4_50_95, 0.43_41, 0.44_47] ) snake_case: List[Any] = 1E-2 if torch_device != 'mps' else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
692
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = "▁" __UpperCAmelCase = {"vocab_file": "sentencepiece.bpe.model"} __UpperCAmelCase = { "vocab_file": { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model", } } __UpperCAmelCase = { "facebook/xglm-564M": 2_048, } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer snake_case: Optional[Any] = 7 snake_case: List[str] = [F"""<madeupword{i}>""" for i in range(self.num_madeup_words )] snake_case: str = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) snake_case: int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) snake_case: int = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab snake_case: Tuple = 1 # Mimic fairseq token-to-id alignment for the first 4 token snake_case: Optional[Any] = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} snake_case: Union[str, Any] = len(self.sp_model ) snake_case: str = {F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ): '''simple docstring''' snake_case: List[Any] = self.__dict__.copy() snake_case: Union[str, Any] = None snake_case: Union[str, Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): snake_case: Union[str, Any] = {} snake_case: Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a snake_case: Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' snake_case: int = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def _UpperCamelCase ( self ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case: Dict = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip() return out_string def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case: List[str] = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: snake_case: int = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
692
1
'''simple docstring''' import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = ["model.decoder.embed_positions.weights"] def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if "emb" in name: snake_case: Optional[int] = name.replace('emb' , 'model.decoder.embed_tokens' ) if "transformer" in name: snake_case: Any = name.replace('transformer' , 'model.decoder' ) if "cross_attention" in name: snake_case: Optional[Any] = name.replace('cross_attention' , 'encoder_attn' ) if "linear1" in name: snake_case: Tuple = name.replace('linear1' , 'fc1' ) if "linear2" in name: snake_case: int = name.replace('linear2' , 'fc2' ) if "norm1" in name: snake_case: List[Any] = name.replace('norm1' , 'self_attn_layer_norm' ) if "norm_cross" in name: snake_case: List[Any] = name.replace('norm_cross' , 'encoder_attn_layer_norm' ) if "norm2" in name: snake_case: int = name.replace('norm2' , 'final_layer_norm' ) if "out_norm" in name: snake_case: Optional[int] = name.replace('out_norm' , 'model.decoder.layer_norm' ) if "linears" in name: snake_case: int = name.replace('linears' , 'lm_heads' ) if "condition_provider.conditioners.description.output_proj" in name: snake_case: Optional[int] = name.replace('condition_provider.conditioners.description.output_proj' , 'enc_to_dec_proj' ) return name def lowerCAmelCase_ ( __A : OrderedDict , __A : int ): '''simple docstring''' snake_case: Tuple = list(state_dict.keys() ) snake_case: Union[str, Any] = {} for key in keys: snake_case: Tuple = state_dict.pop(__A ) snake_case: Union[str, Any] = rename_keys(__A ) if "in_proj_weight" in key: # split fused qkv proj snake_case: str = val[:hidden_size, :] snake_case: Dict = val[hidden_size : 2 * hidden_size, :] snake_case: Any = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: snake_case: int = val else: snake_case: Any = val return state_dict, enc_dec_proj_state_dict def lowerCAmelCase_ ( __A : str ): '''simple docstring''' if checkpoint == "small": # default config values snake_case: Dict = 10_24 snake_case: Tuple = 24 snake_case: str = 16 elif checkpoint == "medium": snake_case: str = 15_36 snake_case: Dict = 48 snake_case: Optional[Any] = 24 elif checkpoint == "large": snake_case: List[str] = 20_48 snake_case: int = 48 snake_case: List[str] = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) snake_case: Union[str, Any] = MusicgenDecoderConfig( hidden_size=__A , ffn_dim=hidden_size * 4 , num_hidden_layers=__A , num_attention_heads=__A , ) return config @torch.no_grad() def lowerCAmelCase_ ( __A : str , __A : List[Any]=None , __A : Dict=None , __A : List[Any]="cpu" ): '''simple docstring''' snake_case: int = MusicGen.get_pretrained(__A , device=__A ) snake_case: Dict = decoder_config_from_checkpoint(__A ) snake_case: List[str] = fairseq_model.lm.state_dict() snake_case , snake_case: List[Any] = rename_state_dict( __A , hidden_size=decoder_config.hidden_size ) snake_case: List[Any] = TaEncoderModel.from_pretrained('t5-base' ) snake_case: List[Any] = EncodecModel.from_pretrained('facebook/encodec_32khz' ) snake_case: Tuple = MusicgenForCausalLM(__A ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection snake_case , snake_case: List[Any] = decoder.load_state_dict(__A , strict=__A ) for key in missing_keys.copy(): if key.startswith(('text_encoder', 'audio_encoder') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__A ) if len(__A ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(__A ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model snake_case: Optional[Any] = MusicgenForConditionalGeneration(text_encoder=__A , audio_encoder=__A , decoder=__A ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__A ) # check we can do a forward pass snake_case: Optional[int] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) snake_case: List[str] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): snake_case: Union[str, Any] = model(input_ids=__A , decoder_input_ids=__A ).logits if logits.shape != (8, 1, 20_48): raise ValueError('Incorrect shape for logits' ) # now construct the processor snake_case: Union[str, Any] = AutoTokenizer.from_pretrained('t5-base' ) snake_case: Optional[Any] = AutoFeatureExtractor.from_pretrained('facebook/encodec_32khz' , padding_side='left' ) snake_case: Optional[Any] = MusicgenProcessor(feature_extractor=__A , tokenizer=__A ) # set the appropriate bos/pad token ids snake_case: str = 20_48 snake_case: Dict = 20_48 # set other default generation config params snake_case: str = int(30 * audio_encoder.config.frame_rate ) snake_case: Union[str, Any] = True snake_case: Union[str, Any] = 3.0 if pytorch_dump_folder is not None: Path(__A ).mkdir(exist_ok=__A ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(__A ) processor.save_pretrained(__A ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(__A ) processor.push_to_hub(__A ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) __UpperCAmelCase = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
692
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' return getitem, k def lowerCAmelCase_ ( __A : Any , __A : Optional[int] ): '''simple docstring''' return setitem, k, v def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' return delitem, k def lowerCAmelCase_ ( __A : str , __A : int , *__A : Tuple ): '''simple docstring''' try: return fun(__A , *__A ), None except Exception as e: return None, e __UpperCAmelCase = ( _set("key_a", "val_a"), _set("key_b", "val_b"), ) __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_a", "val_b"), ] __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_b", "val_b"), _del("key_a"), _del("key_b"), _set("key_a", "val_a"), _del("key_a"), ] __UpperCAmelCase = [ _get("key_a"), _del("key_a"), _set("key_a", "val_a"), _del("key_a"), _del("key_a"), _get("key_a"), ] __UpperCAmelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] __UpperCAmelCase = [ *[_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 lowerCAmelCase_ ( __A : str ): '''simple docstring''' snake_case: List[Any] = HashMap(initial_block_size=4 ) snake_case: List[Any] = {} for _, (fun, *args) in enumerate(__A ): snake_case , snake_case: Optional[int] = _run_operation(__A , __A , *__A ) snake_case , snake_case: str = _run_operation(__A , __A , *__A ) assert my_res == py_res assert str(__A ) == str(__A ) assert set(__A ) == set(__A ) assert len(__A ) == len(__A ) assert set(my.items() ) == set(py.items() ) def lowerCAmelCase_ ( ): '''simple docstring''' def is_public(__A : str ) -> bool: return not name.startswith('_' ) snake_case: Dict = {name for name in dir({} ) if is_public(__A )} snake_case: List[str] = {name for name in dir(HashMap() ) if is_public(__A )} assert dict_public_names > hash_public_names
692
1
'''simple docstring''' from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: str = parent snake_case: Tuple = 13 snake_case: List[Any] = 7 snake_case: Tuple = 30 snake_case: Dict = self.seq_length + self.mem_len snake_case: Any = 15 snake_case: Optional[int] = True snake_case: Any = True snake_case: List[Any] = 99 snake_case: Union[str, Any] = [10, 50, 80] snake_case: Any = 32 snake_case: int = 32 snake_case: str = 4 snake_case: List[Any] = 8 snake_case: Any = 1_28 snake_case: Optional[Any] = 2 snake_case: Union[str, Any] = 2 snake_case: Dict = None snake_case: List[str] = 1 snake_case: List[Any] = 0 snake_case: Dict = 3 snake_case: Optional[Any] = self.vocab_size - 1 snake_case: Optional[int] = 0.01 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case: str = None if self.use_labels: snake_case: int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case: int = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def _UpperCamelCase ( self ): '''simple docstring''' random.seed(self.seed ) tf.random.set_seed(self.seed ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[Any] = TFTransfoXLModel(SCREAMING_SNAKE_CASE__ ) snake_case , snake_case: Tuple = model(SCREAMING_SNAKE_CASE__ ).to_tuple() snake_case: Dict = {'input_ids': input_ids_a, 'mems': mems_a} snake_case , snake_case: Tuple = model(SCREAMING_SNAKE_CASE__ ).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = TFTransfoXLLMHeadModel(SCREAMING_SNAKE_CASE__ ) snake_case , snake_case: Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ).to_tuple() snake_case: Dict = {'input_ids': input_ids_a, 'labels': lm_labels} snake_case , snake_case: int = model(SCREAMING_SNAKE_CASE__ ).to_tuple() snake_case , snake_case: Optional[Any] = model([input_ids_a, mems_a] ).to_tuple() snake_case: Optional[Any] = {'input_ids': input_ids_a, 'mems': mems_a, 'labels': lm_labels} snake_case , snake_case: str = model(SCREAMING_SNAKE_CASE__ ).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = TFTransfoXLForSequenceClassification(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = self.prepare_config_and_inputs() ((snake_case) , (snake_case) , (snake_case) , (snake_case)): List[str] = config_and_inputs snake_case: List[str] = {'input_ids': input_ids_a} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) __UpperCamelCase = () if is_tf_available() else () __UpperCamelCase = ( { "feature-extraction": TFTransfoXLModel, "text-classification": TFTransfoXLForSequenceClassification, "text-generation": TFTransfoXLLMHeadModel, "zero-shot": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = TFTransfoXLModelTester(self ) snake_case: Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , d_embed=37 ) def _UpperCamelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self ): '''simple docstring''' self.model_tester.set_seed() snake_case: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' self.model_tester.set_seed() snake_case: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case: List[str] = self.model_tester.prepare_config_and_inputs_for_common() snake_case: List[Any] = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: snake_case: Optional[int] = model_class(SCREAMING_SNAKE_CASE__ ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: snake_case: List[Any] = model.get_output_embeddings() assert isinstance(SCREAMING_SNAKE_CASE__ , tf.keras.layers.Layer ) snake_case: Any = model.get_bias() assert name is None else: snake_case: List[str] = model.get_output_embeddings() assert x is None snake_case: Optional[int] = model.get_bias() assert name is None def _UpperCamelCase ( self ): '''simple docstring''' pass @slow def _UpperCamelCase ( self ): '''simple docstring''' for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case: str = TFTransfoXLModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason='This model doesn\'t play well with fit() due to not returning a single loss.' ) def _UpperCamelCase ( self ): '''simple docstring''' pass @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @unittest.skip('Skip test until #12651 is resolved.' ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = TFTransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103' ) # fmt: off snake_case: Dict = tf.convert_to_tensor([[33,12_97,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,22,17_06,17,2_00_98,5,32_15,21,37,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,62_24,8_31,1_60_02,2,8,6_03,7_89_67,2_95_46,23,8_03,20,25,4_16,5,8,2_32,4,2_77,6,18_55,46_01,3,2_95_46,54,8,36_09,5,5_72_11,49,4,1,2_77,18,8,17_55,1_56_91,3,3_41,25,4_16,6_93,4_25_73,71,17,4_01,94,31,1_79_19,2,2_95_46,78_73,18,1,4_35,23,1_10_11,7_55,5,51_67,3,79_83,98,84,2,2_95_46,32_67,8,36_09,4,1,48_65,10_75,2,60_87,71,6,3_46,8,58_54,3,2_95_46,8_24,14_00,18_68,2,19,1_60,2,3_11,8,54_96,2,2_09_20,17,25,1_50_97,3,24,24,0]] , dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off snake_case: Any = [33,12_97,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,22,17_06,17,2_00_98,5,32_15,21,37,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,62_24,8_31,1_60_02,2,8,6_03,7_89_67,2_95_46,23,8_03,20,25,4_16,5,8,2_32,4,2_77,6,18_55,46_01,3,2_95_46,54,8,36_09,5,5_72_11,49,4,1,2_77,18,8,17_55,1_56_91,3,3_41,25,4_16,6_93,4_25_73,71,17,4_01,94,31,1_79_19,2,2_95_46,78_73,18,1,4_35,23,1_10_11,7_55,5,51_67,3,79_83,98,84,2,2_95_46,32_67,8,36_09,4,1,48_65,10_75,2,60_87,71,6,3_46,8,58_54,3,2_95_46,8_24,14_00,18_68,2,19,1_60,2,3_11,8,54_96,2,2_09_20,17,25,1_50_97,3,24,24,0,33,1,18_57,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,28,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> snake_case: Tuple = model.generate(SCREAMING_SNAKE_CASE__ , max_length=2_00 , do_sample=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE__ )
692
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "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": "lm_head", "mask_emb": "masked_spec_embed", } __UpperCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def lowerCAmelCase_ ( __A : Any , __A : Optional[Any] , __A : Union[str, Any] , __A : int , __A : Optional[int] ): '''simple docstring''' for attribute in key.split('.' ): snake_case: List[str] = getattr(__A , __A ) if weight_type is not None: snake_case: Optional[int] = getattr(__A , __A ).shape else: snake_case: Optional[int] = 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": snake_case: Optional[int] = value elif weight_type == "weight_g": snake_case: List[str] = value elif weight_type == "weight_v": snake_case: Dict = value elif weight_type == "bias": snake_case: Optional[Any] = value else: snake_case: int = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def lowerCAmelCase_ ( __A : List[Any] , __A : List[str] ): '''simple docstring''' snake_case: List[Any] = [] snake_case: List[Any] = fairseq_model.state_dict() snake_case: Union[str, Any] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight snake_case: Dict = None for name, value in fairseq_dict.items(): snake_case: Tuple = False if "conv_layers" in name: load_conv_layer( __A , __A , __A , __A , hf_model.config.feat_extract_norm == 'group' , ) snake_case: List[Any] = True elif name.split('.' )[0] == "proj": snake_case: List[Any] = fairseq_model.proj snake_case: int = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: snake_case: int = True if "*" in mapped_key: snake_case: List[str] = name.split(__A )[0].split('.' )[-2] snake_case: Dict = mapped_key.replace('*' , __A ) if "weight_g" in name: snake_case: Tuple = 'weight_g' elif "weight_v" in name: snake_case: int = 'weight_v' elif "bias" in name: snake_case: Tuple = 'bias' elif "weight" in name: snake_case: List[Any] = 'weight' else: snake_case: Any = None set_recursively(__A , __A , __A , __A , __A ) continue if not is_used: unused_weights.append(__A ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCAmelCase_ ( __A : List[str] , __A : List[Any] , __A : int , __A : Optional[Any] , __A : Optional[int] ): '''simple docstring''' snake_case: int = full_name.split('conv_layers.' )[-1] snake_case: Tuple = name.split('.' ) snake_case: Any = int(items[0] ) snake_case: Optional[int] = 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.""" ) snake_case: Tuple = 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.""" ) snake_case: int = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) snake_case: Any = 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.""" ) snake_case: str = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__A ) def lowerCAmelCase_ ( __A : Dict ): '''simple docstring''' snake_case , snake_case: List[Any] = emb.weight.shape snake_case: Optional[int] = nn.Linear(__A , __A , bias=__A ) snake_case: Any = emb.weight.data return lin_layer def lowerCAmelCase_ ( __A : Optional[int] ): '''simple docstring''' with open(__A , 'r' , encoding='utf-8' ) as f: snake_case: List[Any] = f.readlines() snake_case: Any = [line.split(' ' )[0] for line in lines] snake_case: int = len(__A ) snake_case: Dict = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(__A , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCAmelCase_ ( __A : Optional[Any] , __A : Union[str, Any] , __A : Dict , __A : Any , __A : List[Any] , __A : int , __A : str , ): '''simple docstring''' snake_case: Union[str, Any] = WavaVecaConfig.from_pretrained(__A ) snake_case: str = SpeechaTextaConfig.from_pretrained( __A , vocab_size=__A , decoder_layers=__A , do_stable_layer_norm=__A ) snake_case: List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=__A , return_attention_mask=__A , ) snake_case , snake_case , snake_case: List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) snake_case: List[Any] = model[0].eval() # set weights for wav2vec2 encoder snake_case: Optional[Any] = WavaVecaModel(__A ) snake_case: Any = recursively_load_weights_wavaveca(model.encoder , __A ) snake_case: Union[str, Any] = SpeechaTextaForCausalLM(__A ) snake_case , snake_case: Optional[Any] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__A ) # set output linear layer unexpected_keys.remove('embed_out' ) snake_case: str = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) snake_case: int = SpeechEncoderDecoderModel(encoder=__A , decoder=__A ) snake_case: List[Any] = False # add projection layer snake_case: Union[str, Any] = nn.Parameter(projection_layer.weight ) snake_case: Union[str, Any] = nn.Parameter(projection_layer.bias ) snake_case: List[Any] = create_vocab_dict(__A ) with open(os.path.join(__A , 'vocab.json' ) , 'w' ) as fp: json.dump(__A , __A ) snake_case: Union[str, Any] = SpeechaTextaTokenizer(os.path.join(__A , 'vocab.json' ) ) tokenizer.save_pretrained(__A ) snake_case: Tuple = hf_wavavec.config.to_dict() snake_case: int = tokenizer.pad_token_id snake_case: Dict = tokenizer.bos_token_id snake_case: Optional[int] = tokenizer.eos_token_id snake_case: Dict = 'speech_to_text_2' snake_case: Optional[Any] = 'wav2vec2' snake_case: Tuple = SpeechEncoderDecoderConfig.from_dict(__A ) hf_wavavec.save_pretrained(__A ) feature_extractor.save_pretrained(__A ) if __name__ == "__main__": __UpperCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") __UpperCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
692
1
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig __UpperCAmelCase = logging.get_logger(__name__) # General docstring __UpperCAmelCase = "PoolFormerConfig" # Base docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = [1, 512, 7, 7] # Image classification docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = "tabby, tabby cat" __UpperCAmelCase = [ "sail/poolformer_s12", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCAmelCase_ ( __A : Tuple , __A : float = 0.0 , __A : bool = False ): '''simple docstring''' if drop_prob == 0.0 or not training: return input snake_case: Union[str, Any] = 1 - drop_prob snake_case: List[Any] = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets snake_case: List[Any] = keep_prob + torch.rand(__A , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize snake_case: Any = input.div(__A ) * random_tensor return output class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' super().__init__() snake_case: List[str] = drop_prob def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return drop_path(SCREAMING_SNAKE_CASE__ , self.drop_prob , self.training ) def _UpperCamelCase ( self ): '''simple docstring''' return "p={}".format(self.drop_prob ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' super().__init__() snake_case: List[str] = patch_size if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (patch_size, patch_size) snake_case: List[str] = stride if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (stride, stride) snake_case: Union[str, Any] = padding if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (padding, padding) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , kernel_size=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = norm_layer(SCREAMING_SNAKE_CASE__ ) if norm_layer else nn.Identity() def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.projection(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.norm(SCREAMING_SNAKE_CASE__ ) return embeddings class SCREAMING_SNAKE_CASE ( nn.GroupNorm ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(1 , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.AvgPoolad(SCREAMING_SNAKE_CASE__ , stride=1 , padding=pool_size // 2 , count_include_pad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.pool(SCREAMING_SNAKE_CASE__ ) - hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: str = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if isinstance(config.hidden_act , SCREAMING_SNAKE_CASE__ ): snake_case: Tuple = ACTaFN[config.hidden_act] else: snake_case: int = config.hidden_act def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.act_fn(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.drop(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: str = self.drop(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = PoolFormerPooling(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerOutput(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) # Useful for training neural nets snake_case: Union[str, Any] = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if drop_path > 0.0 else nn.Identity() snake_case: Optional[Any] = config.use_layer_scale if config.use_layer_scale: snake_case: Any = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.use_layer_scale: snake_case: str = self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Dict = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection snake_case: str = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = () snake_case: Dict = self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Union[str, Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection snake_case: Any = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = (output,) + outputs return outputs else: snake_case: Optional[Any] = self.drop_path(self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) ) # First residual connection snake_case: Union[str, Any] = pooling_output + hidden_states snake_case: List[Any] = () # Second residual connection inside the PoolFormerOutput block snake_case: List[str] = self.drop_path(self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: Dict = hidden_states + layer_output snake_case: Optional[Any] = (output,) + outputs return outputs class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = config # stochastic depth decay rule snake_case: List[Any] = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings snake_case: Union[str, Any] = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) snake_case: List[Any] = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) # Transformer blocks snake_case: str = [] snake_case: int = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers snake_case: List[str] = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( SCREAMING_SNAKE_CASE__ , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(SCREAMING_SNAKE_CASE__ ) ) snake_case: Tuple = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True ): '''simple docstring''' snake_case: str = () if output_hidden_states else None snake_case: Dict = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): snake_case , snake_case: Dict = layers # Get patch embeddings from hidden_states snake_case: int = embedding_layer(SCREAMING_SNAKE_CASE__ ) # Send the embeddings through the blocks for _, blk in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = blk(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = layer_outputs[0] if output_hidden_states: snake_case: List[str] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = PoolFormerConfig __UpperCamelCase = "poolformer" __UpperCamelCase = "pixel_values" __UpperCamelCase = True def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = value __UpperCAmelCase = R"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" __UpperCAmelCase = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n" @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = config snake_case: Tuple = PoolFormerEncoder(SCREAMING_SNAKE_CASE__ ) # Initialize weights and apply final processing self.post_init() def _UpperCamelCase ( self ): '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Optional[int] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case: List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) snake_case: Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: List[Any] = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=encoder_outputs.hidden_states , ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Any = nn.Linear(config.hidden_size , config.hidden_size ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.dense(SCREAMING_SNAKE_CASE__ ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = config.num_labels snake_case: str = PoolFormerModel(SCREAMING_SNAKE_CASE__ ) # Final norm snake_case: int = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head snake_case: Dict = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict snake_case: Optional[Any] = self.poolformer( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: Any = outputs[0] snake_case: str = self.classifier(self.norm(SCREAMING_SNAKE_CASE__ ).mean([-2, -1] ) ) snake_case: Any = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: snake_case: Tuple = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): snake_case: Dict = 'single_label_classification' else: snake_case: List[str] = 'multi_label_classification' if self.config.problem_type == "regression": snake_case: Union[str, Any] = MSELoss() if self.num_labels == 1: snake_case: List[str] = loss_fct(logits.squeeze() , labels.squeeze() ) else: snake_case: int = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.config.problem_type == "single_label_classification": snake_case: Union[str, Any] = CrossEntropyLoss() snake_case: Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": snake_case: int = BCEWithLogitsLoss() snake_case: Optional[int] = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not return_dict: snake_case: str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=SCREAMING_SNAKE_CASE__ , logits=SCREAMING_SNAKE_CASE__ , hidden_states=outputs.hidden_states )
692
'''simple docstring''' def lowerCAmelCase_ ( __A : int = 1_00 ): '''simple docstring''' snake_case: List[str] = n * (n + 1) * (2 * n + 1) / 6 snake_case: List[Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F'{solution() = }')
692
1
'''simple docstring''' import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow __UpperCAmelCase = False class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__=32 ): '''simple docstring''' set_seed(0 ) snake_case: Tuple = UNetaDModel(sample_size=SCREAMING_SNAKE_CASE__ , in_channels=3 , out_channels=3 ) snake_case: Tuple = torch.optim.SGD(model.parameters() , lr=0.00_01 ) return model, optimizer @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = 'cpu' # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable snake_case: Tuple = DDPMScheduler( num_train_timesteps=10_00 , beta_start=0.00_01 , beta_end=0.02 , beta_schedule='linear' , clip_sample=SCREAMING_SNAKE_CASE__ , ) snake_case: str = DDIMScheduler( num_train_timesteps=10_00 , beta_start=0.00_01 , beta_end=0.02 , beta_schedule='linear' , clip_sample=SCREAMING_SNAKE_CASE__ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) snake_case: str = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(SCREAMING_SNAKE_CASE__ ) for _ in range(4 )] snake_case: Union[str, Any] = [torch.randn((4, 3, 32, 32) ).to(SCREAMING_SNAKE_CASE__ ) for _ in range(4 )] snake_case: Dict = [torch.randint(0 , 10_00 , (4,) ).long().to(SCREAMING_SNAKE_CASE__ ) for _ in range(4 )] # train with a DDPM scheduler snake_case , snake_case: Union[str, Any] = self.get_model_optimizer(resolution=32 ) model.train().to(SCREAMING_SNAKE_CASE__ ) for i in range(4 ): optimizer.zero_grad() snake_case: Any = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) snake_case: Optional[Any] = model(SCREAMING_SNAKE_CASE__ , timesteps[i] ).sample snake_case: List[str] = torch.nn.functional.mse_loss(SCREAMING_SNAKE_CASE__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM snake_case , snake_case: Dict = self.get_model_optimizer(resolution=32 ) model.train().to(SCREAMING_SNAKE_CASE__ ) for i in range(4 ): optimizer.zero_grad() snake_case: Optional[int] = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) snake_case: Union[str, Any] = model(SCREAMING_SNAKE_CASE__ , timesteps[i] ).sample snake_case: Tuple = torch.nn.functional.mse_loss(SCREAMING_SNAKE_CASE__ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-5 ) ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-5 ) )
692
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration __UpperCAmelCase = [ # tf -> hf ("/", "."), ("layer_", "layers."), ("kernel", "weight"), ("beta", "bias"), ("gamma", "weight"), ("pegasus", "model"), ] __UpperCAmelCase = [ (".output.dense", ".fc2"), ("intermediate.LayerNorm", "final_layer_norm"), ("intermediate.dense", "fc1"), ] __UpperCAmelCase = ( INIT_COMMON + [ ("attention.self.LayerNorm", "self_attn_layer_norm"), ("attention.output.dense", "self_attn.out_proj"), ("attention.self", "self_attn"), ("attention.encdec.LayerNorm", "encoder_attn_layer_norm"), ("attention.encdec_output.dense", "encoder_attn.out_proj"), ("attention.encdec", "encoder_attn"), ("key", "k_proj"), ("value", "v_proj"), ("query", "q_proj"), ("decoder.LayerNorm", "decoder.layernorm_embedding"), ] + END_COMMON ) __UpperCAmelCase = ( INIT_COMMON + [ ("embeddings.word_embeddings", "shared.weight"), ("embeddings.position_embeddings", "embed_positions.weight"), ("attention.self.LayerNorm", "self_attn_layer_norm"), ("attention.output.dense", "self_attn.output"), ("attention.self", "self_attn.self"), ("encoder.LayerNorm", "encoder.layernorm_embedding"), ] + END_COMMON ) __UpperCAmelCase = [ "encdec/key/bias", "encdec/query/bias", "encdec/value/bias", "self/key/bias", "self/query/bias", "self/value/bias", "encdec_output/dense/bias", "attention/output/dense/bias", ] def lowerCAmelCase_ ( __A : Dict , __A : List[Any] ): '''simple docstring''' for tf_name, hf_name in patterns: snake_case: List[Any] = k.replace(__A , __A ) return k def lowerCAmelCase_ ( __A : dict , __A : dict ): '''simple docstring''' snake_case: Optional[int] = BigBirdPegasusConfig(**__A ) snake_case: List[Any] = BigBirdPegasusForConditionalGeneration(__A ) snake_case: Any = torch_model.state_dict() snake_case: Any = {} # separating decoder weights snake_case: Optional[Any] = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder' )} snake_case: Any = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder' )} for k, v in tqdm(decoder_weights.items() , 'tf -> hf conversion' ): snake_case: List[str] = [k.endswith(__A ) for ending in KEYS_TO_IGNORE] if any(__A ): continue snake_case: Any = DECODER_PATTERNS snake_case: int = rename_state_dict_key(__A , __A ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): snake_case: Optional[Any] = v.T snake_case: Any = torch.from_numpy(__A ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items() , 'tf -> hf conversion' ): snake_case: List[Any] = [k.endswith(__A ) for ending in KEYS_TO_IGNORE] if any(__A ): continue snake_case: Union[str, Any] = REMAINING_PATTERNS snake_case: str = rename_state_dict_key(__A , __A ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): snake_case: int = v.T snake_case: Any = torch.from_numpy(__A ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" snake_case: str = mapping['model.embed_positions.weight'] snake_case: Any = mapping.pop('model.embed_positions.weight' ) snake_case , snake_case: Union[str, Any] = torch_model.load_state_dict(__A , strict=__A ) snake_case: Optional[int] = [ k for k in missing if k not in [ 'final_logits_bias', 'model.encoder.embed_tokens.weight', 'model.decoder.embed_tokens.weight', 'lm_head.weight', ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def lowerCAmelCase_ ( __A : Optional[int] ): '''simple docstring''' snake_case: Tuple = tf.train.list_variables(__A ) snake_case: str = {} snake_case: List[str] = ['global_step'] for name, shape in tqdm(__A , desc='converting tf checkpoint to dict' ): snake_case: str = any(pat in name for pat in ignore_name ) if skip_key: continue snake_case: Any = tf.train.load_variable(__A , __A ) snake_case: Optional[int] = array return tf_weights def lowerCAmelCase_ ( __A : str , __A : str , __A : dict ): '''simple docstring''' snake_case: int = get_tf_weights_as_numpy(__A ) snake_case: int = convert_bigbird_pegasus(__A , __A ) torch_model.save_pretrained(__A ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("--tf_ckpt_path", type=str, help="passed to tf.train.list_variables") parser.add_argument("--save_dir", default=None, type=str, help="Path to the output PyTorch model.") __UpperCAmelCase = parser.parse_args() __UpperCAmelCase = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
692
1
'''simple docstring''' import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py __UpperCAmelCase = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. __UpperCAmelCase = direct_transformers_import(PATH_TO_TRANSFORMERS) __UpperCAmelCase = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` __UpperCAmelCase = re.compile(R"\[(.+?)\]\((https://huggingface\.co/.+?)\)") __UpperCAmelCase = { "DecisionTransformerConfig", "EncoderDecoderConfig", "MusicgenConfig", "RagConfig", "SpeechEncoderDecoderConfig", "TimmBackboneConfig", "VisionEncoderDecoderConfig", "VisionTextDualEncoderConfig", "LlamaConfig", } def lowerCAmelCase_ ( __A : Any ): '''simple docstring''' snake_case: Union[str, Any] = None # source code of `config_class` snake_case: Optional[int] = inspect.getsource(__A ) snake_case: str = _re_checkpoint.findall(__A ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith('/' ): snake_case: Optional[int] = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link snake_case: int = f"""https://huggingface.co/{ckpt_name}""" if ckpt_link == ckpt_link_from_name: snake_case: List[str] = ckpt_name break return checkpoint def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: int = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue snake_case: str = get_checkpoint_from_config_class(__A ) snake_case: Union[str, Any] = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(__A ) if len(__A ) > 0: snake_case: Any = '\n'.join(sorted(__A ) ) raise ValueError(f"""The following configurations don't contain any valid checkpoint:\n{message}""" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
692
'''simple docstring''' def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' snake_case: str = [0] * len(__A ) snake_case: Tuple = [] snake_case: Tuple = [1] * len(__A ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__A ) ): if indegree[i] == 0: queue.append(__A ) while queue: snake_case: int = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: snake_case: Any = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(__A ) print(max(__A ) ) # Adjacency list of Graph __UpperCAmelCase = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
692
1
'''simple docstring''' import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def lowerCAmelCase_ ( __A : Tuple ): '''simple docstring''' snake_case: Tuple = model.config snake_case: str = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=1_28 , ) snake_case: Optional[Any] = MBartConfig( is_decoder=__A , is_encoder_decoder=__A , add_cross_attention=__A , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=__A , add_final_layer_norm=__A , ) return encoder_config, decoder_config def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if "encoder.model" in name: snake_case: Optional[Any] = name.replace('encoder.model' , 'encoder' ) if "decoder.model" in name: snake_case: str = name.replace('decoder.model' , 'decoder' ) if "patch_embed.proj" in name: snake_case: Any = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: snake_case: Optional[int] = name.replace('patch_embed.norm' , 'embeddings.norm' ) if name.startswith('encoder' ): if "layers" in name: snake_case: Tuple = 'encoder.' + name if "attn.proj" in name: snake_case: Optional[int] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name and "mask" not in name: snake_case: Dict = name.replace('attn' , 'attention.self' ) if "norm1" in name: snake_case: Union[str, Any] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: snake_case: Dict = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: snake_case: List[str] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: snake_case: Dict = name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": snake_case: Dict = 'encoder.layernorm.weight' if name == "encoder.norm.bias": snake_case: int = 'encoder.layernorm.bias' return name def lowerCAmelCase_ ( __A : List[Any] , __A : Optional[Any] ): '''simple docstring''' for key in orig_state_dict.copy().keys(): snake_case: List[Any] = orig_state_dict.pop(__A ) if "qkv" in key: snake_case: Union[str, Any] = key.split('.' ) snake_case: Optional[Any] = int(key_split[3] ) snake_case: Any = int(key_split[5] ) snake_case: Union[str, Any] = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: snake_case: Union[str, Any] = val[:dim, :] snake_case: Any = val[dim : dim * 2, :] snake_case: List[str] = val[-dim:, :] else: snake_case: str = val[:dim] snake_case: Union[str, Any] = val[dim : dim * 2] snake_case: List[Any] = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: snake_case: Optional[int] = val return orig_state_dict def lowerCAmelCase_ ( __A : List[Any] , __A : Any=None , __A : List[str]=False ): '''simple docstring''' snake_case: str = DonutModel.from_pretrained(__A ).eval() # load HuggingFace model snake_case , snake_case: Optional[Any] = get_configs(__A ) snake_case: Optional[int] = DonutSwinModel(__A ) snake_case: Tuple = MBartForCausalLM(__A ) snake_case: Optional[Any] = VisionEncoderDecoderModel(encoder=__A , decoder=__A ) model.eval() snake_case: Optional[int] = original_model.state_dict() snake_case: Optional[int] = convert_state_dict(__A , __A ) model.load_state_dict(__A ) # verify results on scanned document snake_case: Union[str, Any] = load_dataset('hf-internal-testing/example-documents' ) snake_case: str = dataset['test'][0]['image'].convert('RGB' ) snake_case: Optional[int] = XLMRobertaTokenizerFast.from_pretrained(__A , from_slow=__A ) snake_case: Any = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) snake_case: Dict = DonutProcessor(__A , __A ) snake_case: Optional[Any] = processor(__A , return_tensors='pt' ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": snake_case: int = '<s_docvqa><s_question>{user_input}</s_question><s_answer>' snake_case: Optional[Any] = 'When is the coffee break?' snake_case: Optional[int] = task_prompt.replace('{user_input}' , __A ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": snake_case: Dict = '<s_rvlcdip>' elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: snake_case: str = '<s_cord>' elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": snake_case: str = 's_cord-v2>' elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": snake_case: int = '<s_zhtrainticket>' elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt snake_case: Optional[Any] = 'hello world' else: raise ValueError('Model name not supported' ) snake_case: Optional[int] = original_model.decoder.tokenizer(__A , add_special_tokens=__A , return_tensors='pt' )[ 'input_ids' ] snake_case: Any = original_model.encoder.model.patch_embed(__A ) snake_case , snake_case: Dict = model.encoder.embeddings(__A ) assert torch.allclose(__A , __A , atol=1E-3 ) # verify encoder hidden states snake_case: Tuple = original_model.encoder(__A ) snake_case: List[str] = model.encoder(__A ).last_hidden_state assert torch.allclose(__A , __A , atol=1E-2 ) # verify decoder hidden states snake_case: List[Any] = original_model(__A , __A , __A ).logits snake_case: List[Any] = model(__A , decoder_input_ids=__A ).logits assert torch.allclose(__A , __A , atol=1E-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(__A ) processor.save_pretrained(__A ) if push_to_hub: model.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) processor.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) __UpperCAmelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
692
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = tempfile.mkdtemp() snake_case: Optional[Any] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '的', '价', '格', '是', '15', '便', 'alex', '##andra', ',', '。', '-', 't', 'shirt', ] snake_case: Optional[Any] = 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] ) ) snake_case: Optional[int] = { 'do_resize': True, 'size': {'height': 2_24, 'width': 2_24}, 'do_center_crop': True, 'crop_size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], 'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], 'do_convert_rgb': True, } snake_case: Union[str, Any] = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] snake_case: Tuple = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_tokenizer() snake_case: Union[str, Any] = self.get_rust_tokenizer() snake_case: Union[str, Any] = self.get_image_processor() snake_case: List[str] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) snake_case: List[str] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) snake_case: Any = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) snake_case: Optional[int] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case: Optional[int] = self.get_tokenizer(cls_token='(CLS)' , sep_token='(SEP)' ) snake_case: Union[str, Any] = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='(CLS)' , sep_token='(SEP)' , do_normalize=SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.get_image_processor() snake_case: Tuple = self.get_tokenizer() snake_case: Optional[Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.prepare_image_inputs() snake_case: List[Any] = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) snake_case: Dict = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_image_processor() snake_case: Optional[int] = self.get_tokenizer() snake_case: List[Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = 'Alexandra,T-shirt的价格是15便士。' snake_case: Union[str, Any] = processor(text=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer(SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_image_processor() snake_case: Dict = self.get_tokenizer() snake_case: Optional[int] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Dict = 'Alexandra,T-shirt的价格是15便士。' snake_case: Tuple = self.prepare_image_inputs() snake_case: Any = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.get_image_processor() snake_case: str = self.get_tokenizer() snake_case: Union[str, Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] snake_case: int = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_image_processor() snake_case: Dict = self.get_tokenizer() snake_case: Optional[int] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = 'Alexandra,T-shirt的价格是15便士。' snake_case: List[Any] = self.prepare_image_inputs() snake_case: Dict = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
692
1
'''simple docstring''' import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=13 , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=99 , SCREAMING_SNAKE_CASE__=64 , 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__=5_12 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=None , ): '''simple docstring''' snake_case: Tuple = parent snake_case: Optional[Any] = batch_size snake_case: Any = seq_length snake_case: Optional[Any] = is_training snake_case: Union[str, Any] = use_input_mask snake_case: Tuple = use_token_type_ids snake_case: List[str] = use_labels snake_case: Optional[int] = vocab_size snake_case: Union[str, Any] = hidden_size snake_case: int = num_hidden_layers snake_case: Optional[int] = num_attention_heads snake_case: Tuple = intermediate_size snake_case: Union[str, Any] = hidden_act snake_case: str = hidden_dropout_prob snake_case: Dict = attention_probs_dropout_prob snake_case: str = max_position_embeddings snake_case: Optional[int] = type_vocab_size snake_case: List[str] = type_sequence_label_size snake_case: str = initializer_range snake_case: Union[str, Any] = num_labels snake_case: List[str] = num_choices snake_case: Any = scope snake_case: Union[str, Any] = vocab_size - 1 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case: Dict = None if self.use_input_mask: snake_case: Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case: List[str] = None if self.use_labels: snake_case: str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case: Dict = self.get_config() return config, input_ids, input_mask, token_labels def _UpperCamelCase ( self ): '''simple docstring''' return GPTNeoXConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , pad_token_id=self.pad_token_id , ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case , snake_case , snake_case: Optional[Any] = self.prepare_config_and_inputs() snake_case: Tuple = True return config, input_ids, input_mask, token_labels def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = GPTNeoXModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Dict = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) snake_case: int = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = True snake_case: str = GPTNeoXModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Optional[Any] = 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 _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = GPTNeoXForCausalLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Union[str, Any] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.num_labels snake_case: Tuple = GPTNeoXForQuestionAnswering(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: List[Any] = model(SCREAMING_SNAKE_CASE__ , attention_mask=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 _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.num_labels snake_case: List[Any] = GPTNeoXForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case: str = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Tuple = self.num_labels snake_case: List[Any] = GPTNeoXForTokenClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: int = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Union[str, Any] = True snake_case: Union[str, Any] = GPTNeoXForCausalLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() # first forward pass snake_case: Optional[Any] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) snake_case: str = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids snake_case: Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) snake_case: Tuple = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and snake_case: List[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case: Optional[int] = torch.cat([input_mask, next_mask] , dim=-1 ) snake_case: List[str] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ ) snake_case: Any = output_from_no_past['hidden_states'][0] snake_case: Optional[Any] = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , )['hidden_states'][0] # select random slice snake_case: Union[str, Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case: Tuple = output_from_no_past[:, -3:, random_slice_idx].detach() snake_case: List[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.prepare_config_and_inputs() snake_case , snake_case , snake_case , snake_case: Any = config_and_inputs snake_case: List[str] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase = (GPTNeoXForCausalLM,) if is_torch_available() else () __UpperCamelCase = ( { "feature-extraction": GPTNeoXModel, "question-answering": GPTNeoXForQuestionAnswering, "text-classification": GPTNeoXForSequenceClassification, "text-generation": GPTNeoXForCausalLM, "token-classification": GPTNeoXForTokenClassification, "zero-shot": GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = GPTNeoXModelTester(self ) snake_case: Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=64 , num_attention_heads=8 ) def _UpperCamelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case , snake_case , snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case , snake_case , snake_case: Any = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case , snake_case , snake_case: List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() snake_case: List[str] = None self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case , snake_case , snake_case: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason='Feed forward chunking is not implemented' ) def _UpperCamelCase ( self ): '''simple docstring''' pass @parameterized.expand([('linear',), ('dynamic',)] ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case , snake_case: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case: List[str] = ids_tensor([1, 10] , config.vocab_size ) snake_case: Optional[Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights snake_case: List[str] = GPTNeoXModel(SCREAMING_SNAKE_CASE__ ) original_model.to(SCREAMING_SNAKE_CASE__ ) original_model.eval() snake_case: Dict = original_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state snake_case: List[str] = original_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights snake_case: Any = {'type': scaling_type, 'factor': 10.0} snake_case: Optional[int] = GPTNeoXModel(SCREAMING_SNAKE_CASE__ ) scaled_model.to(SCREAMING_SNAKE_CASE__ ) scaled_model.eval() snake_case: str = scaled_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state snake_case: Dict = scaled_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-5 ) ) @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = AutoTokenizer.from_pretrained('EleutherAI/pythia-410m-deduped' ) for checkpointing in [True, False]: snake_case: List[Any] = GPTNeoXForCausalLM.from_pretrained('EleutherAI/pythia-410m-deduped' ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer('My favorite food is' , return_tensors='pt' ).to(SCREAMING_SNAKE_CASE__ ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 snake_case: Dict = 'My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI\'m not sure' snake_case: Dict = model.generate(**SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ , max_new_tokens=20 ) snake_case: Union[str, Any] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )[0] self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
692
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "microsoft/swinv2-tiny-patch4-window8-256": ( "https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json" ), } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = "swinv2" __UpperCamelCase = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , SCREAMING_SNAKE_CASE__=2_24 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=96 , SCREAMING_SNAKE_CASE__=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE__=[3, 6, 12, 24] , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=4.0 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=32 , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case: int = image_size snake_case: Union[str, Any] = patch_size snake_case: List[str] = num_channels snake_case: Tuple = embed_dim snake_case: str = depths snake_case: Any = len(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = num_heads snake_case: Optional[int] = window_size snake_case: Any = mlp_ratio snake_case: Optional[int] = qkv_bias snake_case: Union[str, Any] = hidden_dropout_prob snake_case: List[str] = attention_probs_dropout_prob snake_case: Dict = drop_path_rate snake_case: List[str] = hidden_act snake_case: int = use_absolute_embeddings snake_case: Any = layer_norm_eps snake_case: Dict = initializer_range snake_case: List[Any] = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model snake_case: Tuple = int(embed_dim * 2 ** (len(SCREAMING_SNAKE_CASE__ ) - 1) ) snake_case: Union[str, Any] = (0, 0, 0, 0)
692
1
'''simple docstring''' __UpperCAmelCase = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" __UpperCAmelCase = [{"type": "code", "content": INSTALL_CONTENT}] __UpperCAmelCase = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
692
'''simple docstring''' import os import sys import unittest __UpperCAmelCase = 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_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __UpperCAmelCase = os.path.join(git_repo_path, "src", "transformers") __UpperCAmelCase = "\n{0} = None\n" __UpperCAmelCase = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n" __UpperCAmelCase = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n" class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = find_backend(' _import_structure["models.albert"].append("AlbertTokenizerFast")' ) self.assertIsNone(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = find_backend(' if not is_tokenizers_available():' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'tokenizers' ) snake_case: List[Any] = find_backend(' if not is_tensorflow_text_available():' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'tensorflow_text' ) snake_case: int = find_backend(' if not (is_sentencepiece_available() and is_tokenizers_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tokenizers' ) snake_case: Optional[Any] = find_backend( ' if not (is_sentencepiece_available() and is_tensorflow_text_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tensorflow_text' ) snake_case: Dict = find_backend( ' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tokenizers_and_vision' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('torch' , SCREAMING_SNAKE_CASE__ ) self.assertIn('tensorflow_text' , SCREAMING_SNAKE_CASE__ ) self.assertIn('sentencepiece_and_tokenizers' , SCREAMING_SNAKE_CASE__ ) # Likewise, we can't assert on the exact content of a key self.assertIn('BertModel' , objects['torch'] ) self.assertIn('TFBertModel' , objects['tf'] ) self.assertIn('FlaxBertModel' , objects['flax'] ) self.assertIn('BertModel' , objects['torch'] ) self.assertIn('TFBertTokenizer' , objects['tensorflow_text'] ) self.assertIn('convert_slow_tokenizer' , objects['sentencepiece_and_tokenizers'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = create_dummy_object('CONSTANT' , '\'torch\'' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , '\nCONSTANT = None\n' ) snake_case: Any = create_dummy_object('function' , '\'torch\'' ) self.assertEqual( SCREAMING_SNAKE_CASE__ , '\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n' ) snake_case: Optional[int] = '\nclass FakeClass(metaclass=DummyObject):\n _backends = \'torch\'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, \'torch\')\n' snake_case: Tuple = create_dummy_object('FakeClass' , '\'torch\'' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = ["torch"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, ["torch"])\n' snake_case: Optional[int] = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} ) self.assertEqual(dummy_files['torch'] , SCREAMING_SNAKE_CASE__ )
692
1
'''simple docstring''' import string def lowerCAmelCase_ ( __A : str ): '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): snake_case: Tuple = '' for symbol in message: if symbol in string.ascii_uppercase: snake_case: int = string.ascii_uppercase.find(__A ) snake_case: List[Any] = num - key if num < 0: snake_case: Tuple = num + len(string.ascii_uppercase ) snake_case: str = translated + string.ascii_uppercase[num] else: snake_case: Optional[int] = translated + symbol print(f"""Decryption using Key #{key}: {translated}""" ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: str = input('Encrypted message: ' ) snake_case: str = message.upper() decrypt(__A ) if __name__ == "__main__": import doctest doctest.testmod() main()
692
'''simple docstring''' import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig __UpperCAmelCase = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = question_encoder snake_case: Union[str, Any] = generator snake_case: Optional[int] = self.question_encoder def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if os.path.isfile(SCREAMING_SNAKE_CASE__ ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , 'question_encoder_tokenizer' ) snake_case: Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , 'generator_tokenizer' ) self.question_encoder.save_pretrained(SCREAMING_SNAKE_CASE__ ) self.generator.save_pretrained(SCREAMING_SNAKE_CASE__ ) @classmethod def _UpperCamelCase ( cls , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer snake_case: int = kwargs.pop('config' , SCREAMING_SNAKE_CASE__ ) if config is None: snake_case: str = RagConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE__ , config=config.question_encoder , subfolder='question_encoder_tokenizer' ) snake_case: Dict = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE__ , config=config.generator , subfolder='generator_tokenizer' ) return cls(question_encoder=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) def __call__( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.current_tokenizer(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.generator.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.generator.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.question_encoder def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.generator def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "longest" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = True , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' warnings.warn( '`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ' 'regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ' 'context manager to prepare your targets. See the documentation of your specific tokenizer for more ' 'details' , SCREAMING_SNAKE_CASE__ , ) if max_length is None: snake_case: Optional[Any] = self.current_tokenizer.model_max_length snake_case: int = self( SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: snake_case: Any = self.current_tokenizer.model_max_length snake_case: List[str] = self( text_target=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case: Dict = labels['input_ids'] return model_inputs
692
1
'''simple docstring''' import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = (CMStochasticIterativeScheduler,) __UpperCamelCase = 10 def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = { 'num_train_timesteps': 2_01, 'sigma_min': 0.0_02, 'sigma_max': 80.0, } config.update(**SCREAMING_SNAKE_CASE__ ) return config def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = 10 snake_case: Optional[Any] = self.get_scheduler_config() snake_case: Union[str, Any] = self.scheduler_classes[0](**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = scheduler.timesteps[0] snake_case: Dict = scheduler.timesteps[1] snake_case: Optional[Any] = self.dummy_sample snake_case: str = 0.1 * sample snake_case: int = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample snake_case: int = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _UpperCamelCase ( self ): '''simple docstring''' for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.scheduler_classes[0] snake_case: List[Any] = self.get_scheduler_config() snake_case: Tuple = scheduler_class(**SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = 1 scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = scheduler.timesteps snake_case: Optional[int] = torch.manual_seed(0 ) snake_case: Any = self.dummy_model() snake_case: List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(SCREAMING_SNAKE_CASE__ ): # 1. scale model input snake_case: Optional[int] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 2. predict noise residual snake_case: Union[str, Any] = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 3. predict previous sample x_t-1 snake_case: Union[str, Any] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ).prev_sample snake_case: Union[str, Any] = pred_prev_sample snake_case: str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) snake_case: Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 1_92.76_14 ) < 1E-2 assert abs(result_mean.item() - 0.25_10 ) < 1E-3 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.scheduler_classes[0] snake_case: Optional[Any] = self.get_scheduler_config() snake_case: int = scheduler_class(**SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = [1_06, 0] scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = scheduler.timesteps snake_case: str = torch.manual_seed(0 ) snake_case: int = self.dummy_model() snake_case: List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input snake_case: List[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 2. predict noise residual snake_case: Union[str, Any] = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 3. predict previous sample x_t-1 snake_case: str = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ).prev_sample snake_case: str = pred_prev_sample snake_case: Dict = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) snake_case: str = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 3_47.63_57 ) < 1E-2 assert abs(result_mean.item() - 0.45_27 ) < 1E-3 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.scheduler_classes[0] snake_case: Tuple = self.get_scheduler_config() snake_case: List[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = [39, 30, 12, 15, 0] with self.assertRaises(SCREAMING_SNAKE_CASE__ , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = self.scheduler_classes[0] snake_case: int = self.get_scheduler_config() snake_case: Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) snake_case: int = [39, 30, 12, 1, 0] snake_case: Union[str, Any] = len(SCREAMING_SNAKE_CASE__ ) with self.assertRaises(SCREAMING_SNAKE_CASE__ , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE__ , timesteps=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.scheduler_classes[0] snake_case: List[str] = self.get_scheduler_config() snake_case: List[str] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) snake_case: str = [scheduler.config.num_train_timesteps] with self.assertRaises( SCREAMING_SNAKE_CASE__ , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE__ )
692
'''simple docstring''' 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_ ( __A : Tuple ): '''simple docstring''' assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ): '''simple docstring''' assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Union[str, Any] = 'mock-s3-bucket' snake_case: int = f"""s3://{mock_bucket}""" snake_case: Any = extract_path_from_uri(__A ) assert dataset_path.startswith('s3://' ) is False snake_case: Union[str, Any] = './local/path' snake_case: Union[str, Any] = extract_path_from_uri(__A ) assert dataset_path == new_dataset_path def lowerCAmelCase_ ( __A : Any ): '''simple docstring''' snake_case: List[str] = is_remote_filesystem(__A ) assert is_remote is True snake_case: int = fsspec.filesystem('file' ) snake_case: int = is_remote_filesystem(__A ) assert is_remote is False @pytest.mark.parametrize('compression_fs_class' , __A ) def lowerCAmelCase_ ( __A : Optional[int] , __A : int , __A : str , __A : Optional[Any] , __A : List[str] , __A : Optional[Any] , __A : Optional[int] ): '''simple docstring''' snake_case: Optional[Any] = {'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_file, 'bz2': bza_file, 'lz4': lza_file} snake_case: Optional[int] = input_paths[compression_fs_class.protocol] if input_path is None: snake_case: str = 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(__A ) snake_case: List[str] = fsspec.filesystem(compression_fs_class.protocol , fo=__A ) assert isinstance(__A , __A ) snake_case: Any = os.path.basename(__A ) snake_case: int = expected_filename[: expected_filename.rindex('.' )] assert fs.glob('*' ) == [expected_filename] with fs.open(__A , 'r' , encoding='utf-8' ) as f, open(__A , encoding='utf-8' ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize('protocol' , ['zip', 'gzip'] ) def lowerCAmelCase_ ( __A : Any , __A : int , __A : int ): '''simple docstring''' snake_case: List[str] = {'zip': zip_jsonl_path, 'gzip': jsonl_gz_path} snake_case: str = compressed_file_paths[protocol] snake_case: Dict = 'dataset.jsonl' snake_case: Optional[Any] = f"""{protocol}://{member_file_path}::{compressed_file_path}""" snake_case , *snake_case: List[Any] = fsspec.get_fs_token_paths(__A ) assert fs.isfile(__A ) assert not fs.isfile('non_existing_' + member_file_path ) @pytest.mark.integration def lowerCAmelCase_ ( __A : Optional[Any] , __A : Union[str, Any] , __A : Union[str, Any] , __A : List[Any] ): '''simple docstring''' snake_case: Tuple = hf_api.dataset_info(__A , token=__A ) snake_case: List[str] = HfFileSystem(repo_info=__A , token=__A ) assert sorted(hffs.glob('*' ) ) == [".gitattributes", "data"] assert hffs.isdir('data' ) assert hffs.isfile('.gitattributes' ) and hffs.isfile('data/text_data.txt' ) with open(__A ) as f: assert hffs.open('data/text_data.txt' , 'r' ).read() == f.read() def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Union[str, Any] = 'bz2' # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(__A , __A , clobber=__A ) with pytest.warns(__A ) as warning_info: importlib.reload(datasets.filesystems ) assert len(__A ) == 1 assert ( str(warning_info[0].message ) == f"""A filesystem protocol was already set for {protocol} and will be overwritten.""" )
692
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) def lowerCAmelCase_ ( __A : Optional[int] , __A : int=False ): '''simple docstring''' snake_case: str = [] 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" snake_case: str = [(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 lowerCAmelCase_ ( __A : Optional[Any] , __A : List[str] , __A : Tuple=False ): '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: snake_case: List[Any] = '' else: snake_case: Optional[Any] = 'deit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case: Dict = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) snake_case: Union[str, Any] = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case: str = in_proj_weight[ : config.hidden_size, : ] snake_case: int = in_proj_bias[: config.hidden_size] snake_case: List[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case: int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case: List[Any] = in_proj_weight[ -config.hidden_size :, : ] snake_case: List[str] = in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( __A : Dict , __A : Union[str, Any] , __A : List[str] ): '''simple docstring''' snake_case: Union[str, Any] = dct.pop(__A ) snake_case: Optional[Any] = val def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: int = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case: Union[str, Any] = Image.open(requests.get(__A , stream=__A ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( __A : Union[str, Any] , __A : Optional[int] ): '''simple docstring''' snake_case: str = DeiTConfig() # all deit models have fine-tuned heads snake_case: Union[str, Any] = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size snake_case: Any = 10_00 snake_case: List[str] = 'huggingface/label-files' snake_case: Dict = 'imagenet-1k-id2label.json' snake_case: List[str] = json.load(open(hf_hub_download(__A , __A , repo_type='dataset' ) , 'r' ) ) snake_case: List[str] = {int(__A ): v for k, v in idalabel.items()} snake_case: Tuple = idalabel snake_case: Union[str, Any] = {v: k for k, v in idalabel.items()} snake_case: List[Any] = int(deit_name[-6:-4] ) snake_case: Optional[Any] = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith('tiny' ): snake_case: List[str] = 1_92 snake_case: str = 7_68 snake_case: Union[str, Any] = 12 snake_case: int = 3 elif deit_name[9:].startswith('small' ): snake_case: Optional[int] = 3_84 snake_case: List[str] = 15_36 snake_case: int = 12 snake_case: Optional[Any] = 6 if deit_name[9:].startswith('base' ): pass elif deit_name[4:].startswith('large' ): snake_case: List[Any] = 10_24 snake_case: int = 40_96 snake_case: str = 24 snake_case: Dict = 16 # load original model from timm snake_case: List[str] = timm.create_model(__A , pretrained=__A ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case: Dict = timm_model.state_dict() snake_case: Union[str, Any] = 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 snake_case: List[Any] = DeiTForImageClassificationWithTeacher(__A ).eval() model.load_state_dict(__A ) # Check outputs on an image, prepared by DeiTImageProcessor snake_case: List[Any] = 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 snake_case: Tuple = DeiTImageProcessor(size=__A , crop_size=config.image_size ) snake_case: Optional[Any] = image_processor(images=prepare_img() , return_tensors='pt' ) snake_case: List[str] = encoding['pixel_values'] snake_case: List[Any] = model(__A ) snake_case: Tuple = 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__": __UpperCAmelCase = 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." ) __UpperCAmelCase = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
692
'''simple docstring''' import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.17.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") __UpperCAmelCase = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = field( default="tab_fact" , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) __UpperCamelCase = field( default="tab_fact" , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} , ) __UpperCamelCase = field( default=1024 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "A csv or a json file containing the training data."} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "A csv or a json file containing the validation data."} ) __UpperCamelCase = field(default=snake_case , metadata={"help": "A csv or a json file containing the test data."} ) def _UpperCamelCase ( self ): '''simple docstring''' if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError('Need either a GLUE task, a training/validation file or a dataset name.' ) else: snake_case: str = self.train_file.split('.' )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." snake_case: Optional[Any] = self.validation_file.split('.' )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = field( default=snake_case , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) __UpperCamelCase = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case , snake_case , snake_case: Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case , snake_case , snake_case: str = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) snake_case: Tuple = training_args.get_process_log_level() logger.setLevel(__A ) datasets.utils.logging.set_verbosity(__A ) transformers.utils.logging.set_verbosity(__A ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. snake_case: Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case: List[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. snake_case: int = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. snake_case: Optional[int] = {'train': data_args.train_file, 'validation': data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: snake_case: Tuple = data_args.train_file.split('.' )[-1] snake_case: Union[str, Any] = data_args.test_file.split('.' )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." snake_case: Union[str, Any] = data_args.test_file else: raise ValueError('Need either a GLUE task or a test file for `do_predict`.' ) for key in data_files.keys(): logger.info(f"""load a local file for {key}: {data_files[key]}""" ) if data_args.train_file.endswith('.csv' ): # Loading a dataset from local csv files snake_case: List[Any] = load_dataset('csv' , data_files=__A , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files snake_case: Optional[Any] = load_dataset('json' , data_files=__A , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels snake_case: Tuple = raw_datasets['train'].features['label'].names snake_case: List[str] = len(__A ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case: Tuple = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer snake_case: List[str] = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=__A , ) snake_case: Union[str, Any] = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=__A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: snake_case: int = 'max_length' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch snake_case: Union[str, Any] = False # Some models have set the order of the labels to use, so let's make sure we do use it. snake_case: Optional[Any] = {'Refused': 0, 'Entailed': 1} snake_case: List[Any] = {0: 'Refused', 1: 'Entailed'} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) snake_case: List[str] = min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(__A : Any ): # Tokenize the texts def _convert_table_text_to_pandas(__A : Dict ): snake_case: str = [_table_row.split('#' ) for _table_row in _table_text.strip('\n' ).split('\n' )] snake_case: List[str] = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd snake_case: str = examples['statement'] snake_case: int = list(map(_convert_table_text_to_pandas , examples['table_text'] ) ) snake_case: List[Any] = tokenizer(__A , __A , padding=__A , max_length=__A , truncation=__A ) snake_case: List[Any] = examples['label'] return result with training_args.main_process_first(desc='dataset map pre-processing' ): snake_case: int = raw_datasets.map( __A , batched=__A , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on dataset' , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError('--do_train requires a train dataset' ) snake_case: List[str] = raw_datasets['train'] if data_args.max_train_samples is not None: snake_case: Tuple = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError('--do_eval requires a validation dataset' ) snake_case: Any = raw_datasets['validation'] if data_args.max_eval_samples is not None: snake_case: Optional[int] = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError('--do_predict requires a test dataset' ) snake_case: str = raw_datasets['test'] if data_args.max_predict_samples is not None: snake_case: List[str] = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(__A ) ) , 3 ): logger.info(f"""Sample {index} of the training set: {train_dataset[index]}.""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__A : EvalPrediction ): snake_case: int = p.predictions[0] if isinstance(p.predictions , __A ) else p.predictions snake_case: List[str] = np.argmax(__A , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: snake_case: str = default_data_collator elif training_args.fpaa: snake_case: List[str] = DataCollatorWithPadding(__A , pad_to_multiple_of=8 ) else: snake_case: List[Any] = None # Initialize our Trainer snake_case: List[str] = Trainer( model=__A , args=__A , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__A , tokenizer=__A , data_collator=__A , ) # Training if training_args.do_train: snake_case: Optional[int] = None if training_args.resume_from_checkpoint is not None: snake_case: str = training_args.resume_from_checkpoint elif last_checkpoint is not None: snake_case: Optional[Any] = last_checkpoint snake_case: Union[str, Any] = trainer.train(resume_from_checkpoint=__A ) snake_case: List[Any] = train_result.metrics snake_case: List[Any] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__A ) ) snake_case: Optional[Any] = min(__A , len(__A ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('train' , __A ) trainer.save_metrics('train' , __A ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) snake_case: Dict = trainer.evaluate(eval_dataset=__A ) snake_case: Optional[int] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__A ) snake_case: Dict = min(__A , len(__A ) ) trainer.log_metrics('eval' , __A ) trainer.save_metrics('eval' , __A ) if training_args.do_predict: logger.info('*** Predict ***' ) # Removing the `label` columns because it contains -1 and Trainer won't like that. snake_case: Optional[int] = predict_dataset.remove_columns('label' ) snake_case: str = trainer.predict(__A , metric_key_prefix='predict' ).predictions snake_case: Any = np.argmax(__A , axis=1 ) snake_case: int = os.path.join(training_args.output_dir , 'predict_results_tabfact.txt' ) if trainer.is_world_process_zero(): with open(__A , 'w' ) as writer: logger.info('***** Predict Results *****' ) writer.write('index\tprediction\n' ) for index, item in enumerate(__A ): snake_case: int = label_list[item] writer.write(f"""{index}\t{item}\n""" ) snake_case: Optional[int] = {'finetuned_from': model_args.model_name_or_path, 'tasks': 'text-classification'} if training_args.push_to_hub: trainer.push_to_hub(**__A ) else: trainer.create_model_card(**__A ) def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' main() if __name__ == "__main__": main()
692
1
'''simple docstring''' from __future__ import annotations __UpperCAmelCase = [True] * 1_000_001 __UpperCAmelCase = 2 while i * i <= 1_000_000: if seive[i]: for j in range(i * i, 1_000_001, i): __UpperCAmelCase = False i += 1 def lowerCAmelCase_ ( __A : int ): '''simple docstring''' return seive[n] def lowerCAmelCase_ ( __A : int ): '''simple docstring''' return any(digit in '02468' for digit in str(__A ) ) def lowerCAmelCase_ ( __A : int = 1_00_00_00 ): '''simple docstring''' snake_case: Optional[int] = [2] # result already includes the number 2. for num in range(3 , limit + 1 , 2 ): if is_prime(__A ) and not contains_an_even_digit(__A ): snake_case: Optional[int] = str(__A ) snake_case: List[Any] = [int(str_num[j:] + str_num[:j] ) for j in range(len(__A ) )] if all(is_prime(__A ) for i in list_nums ): result.append(__A ) return result def lowerCAmelCase_ ( ): '''simple docstring''' return len(find_circular_primes() ) if __name__ == "__main__": print(F'{len(find_circular_primes()) = }')
692
'''simple docstring''' import math def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCAmelCase_ ( __A : float = 0.1 ): '''simple docstring''' snake_case: Optional[int] = 3 snake_case: int = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(__A ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "facebook/convnextv2-tiny-1k-224": "https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json", } class SCREAMING_SNAKE_CASE ( snake_case , snake_case ): '''simple docstring''' __UpperCamelCase = "convnextv2" def __init__( self , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-12 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=2_24 , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case: Dict = num_channels snake_case: Optional[int] = patch_size snake_case: List[str] = num_stages snake_case: Dict = [96, 1_92, 3_84, 7_68] if hidden_sizes is None else hidden_sizes snake_case: Union[str, Any] = [3, 3, 9, 3] if depths is None else depths snake_case: Union[str, Any] = hidden_act snake_case: List[Any] = initializer_range snake_case: int = layer_norm_eps snake_case: List[Any] = drop_path_rate snake_case: Tuple = image_size snake_case: Optional[int] = ['stem'] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] snake_case , snake_case: int = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE__ , out_indices=SCREAMING_SNAKE_CASE__ , stage_names=self.stage_names )
692
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): __UpperCAmelCase = "pt" elif is_tf_available(): __UpperCAmelCase = "tf" else: __UpperCAmelCase = "jax" class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ByTaTokenizer __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: int = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _UpperCamelCase ( self ): '''simple docstring''' return ByTaTokenizer.from_pretrained('google/byt5-small' ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=20 , SCREAMING_SNAKE_CASE__=5 ): '''simple docstring''' snake_case: Optional[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): try: snake_case: Optional[Any] = tokenizer.decode([i] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) except UnicodeDecodeError: pass toks.append((i, tok) ) snake_case: List[str] = list(filter(lambda SCREAMING_SNAKE_CASE__ : re.match(r'^[ a-zA-Z]+$' , t[1] ) , SCREAMING_SNAKE_CASE__ ) ) snake_case: str = list(filter(lambda SCREAMING_SNAKE_CASE__ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) ) if max_length is not None and len(SCREAMING_SNAKE_CASE__ ) > max_length: snake_case: Union[str, Any] = 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: snake_case: Tuple = toks + toks # toks_str = [t[1] for t in toks] snake_case: Dict = [t[0] for t in toks] # Ensure consistency snake_case: int = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) if " " not in output_txt and len(SCREAMING_SNAKE_CASE__ ) > 1: snake_case: str = ( 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: snake_case: Tuple = ' ' + output_txt snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) return output_txt, output_ids def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: str = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) snake_case: List[Any] = tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: Union[str, Any] = 'Unicode €.' snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = [88, 1_13, 1_08, 1_02, 1_14, 1_03, 1_04, 35, 2_29, 1_33, 1_75, 49, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[str] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'Unicode €.</s>' ) snake_case: List[Any] = tokenizer('e è é ê ë' ) snake_case: Optional[Any] = [1_04, 35, 1_98, 1_71, 35, 1_98, 1_72, 35, 1_98, 1_73, 35, 1_98, 1_74, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.ta_base_tokenizer snake_case: Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off snake_case: Optional[int] = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 1, 0] # fmt: on snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if FRAMEWORK != "jax": snake_case: Optional[Any] = list(batch.input_ids.numpy()[0] ) else: snake_case: Dict = list(batch.input_ids.tolist()[0] ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.ta_base_tokenizer snake_case: List[str] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] snake_case: Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertIn('attention_mask' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_attention_mask' , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.ta_base_tokenizer snake_case: str = [ 'Summary of the text.', 'Another summary.', ] snake_case: Dict = tokenizer( text_target=SCREAMING_SNAKE_CASE__ , max_length=32 , padding='max_length' , truncation=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.ta_base_tokenizer snake_case: Optional[int] = ['A long paragraph for summarization. </s>'] snake_case: str = ['Summary of the text. </s>'] # fmt: off snake_case: str = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 35, 1] snake_case: Optional[int] = [86, 1_20, 1_12, 1_12, 1_00, 1_17, 1_24, 35, 1_14, 1_05, 35, 1_19, 1_07, 1_04, 35, 1_19, 1_04, 1_23, 1_19, 49, 35, 1] # fmt: on snake_case: List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ , text_target=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['input_ids'][0] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['labels'][0] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test snake_case: Optional[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: Union[str, Any] = tempfile.mkdtemp() snake_case: Dict = ' He is very happy, UNwant\u00E9d,running' snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Any = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: List[str] = tempfile.mkdtemp() snake_case: str = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) snake_case: List[str] = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) snake_case: int = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) snake_case: Union[str, Any] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: snake_case: Any = json.load(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: snake_case: str = json.load(SCREAMING_SNAKE_CASE__ ) snake_case: int = [F"""<extra_id_{i}>""" for i in range(1_25 )] snake_case: Optional[int] = added_tokens_extra_ids + [ 'an_additional_special_token' ] snake_case: str = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files snake_case: Dict = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained snake_case: Union[str, Any] = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=SCREAMING_SNAKE_CASE__ )] snake_case: Union[str, Any] = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.decode([2_55] ) == '' ) def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_tokenizers(fast=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Union[str, Any] = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] snake_case: List[str] = tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Optional[Any] = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] snake_case: Dict = 0 snake_case: List[Any] = tokenizer.convert_ids_to_tokens( SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) for attr in attributes_list: setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [] ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
692
1
'''simple docstring''' from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class SCREAMING_SNAKE_CASE : '''simple docstring''' def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' raise NotImplementedError() def _UpperCamelCase ( self ): '''simple docstring''' raise NotImplementedError() class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = tokenizer snake_case: Dict = skip_prompt snake_case: Any = decode_kwargs # variables used in the streaming process snake_case: Tuple = [] snake_case: Tuple = 0 snake_case: List[str] = True def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError('TextStreamer only supports batch size 1' ) elif len(value.shape ) > 1: snake_case: Any = value[0] if self.skip_prompt and self.next_tokens_are_prompt: snake_case: str = False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) snake_case: int = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith('\n' ): snake_case: Union[str, Any] = text[self.print_len :] snake_case: List[str] = [] snake_case: List[str] = 0 # If the last token is a CJK character, we print the characters. elif len(SCREAMING_SNAKE_CASE__ ) > 0 and self._is_chinese_char(ord(text[-1] ) ): snake_case: List[Any] = text[self.print_len :] self.print_len += len(SCREAMING_SNAKE_CASE__ ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: snake_case: List[str] = text[self.print_len : text.rfind(' ' ) + 1] self.print_len += len(SCREAMING_SNAKE_CASE__ ) self.on_finalized_text(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' if len(self.token_cache ) > 0: snake_case: Any = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) snake_case: Optional[Any] = text[self.print_len :] snake_case: str = [] snake_case: Tuple = 0 else: snake_case: List[str] = '' snake_case: Any = True self.on_finalized_text(SCREAMING_SNAKE_CASE__ , stream_end=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False ): '''simple docstring''' print(SCREAMING_SNAKE_CASE__ , flush=SCREAMING_SNAKE_CASE__ , end='' if not stream_end else None ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if ( (cp >= 0x4_e00 and cp <= 0x9_fff) or (cp >= 0x3_400 and cp <= 0x4_dbf) # or (cp >= 0x20_000 and cp <= 0x2a_6df) # or (cp >= 0x2a_700 and cp <= 0x2b_73f) # or (cp >= 0x2b_740 and cp <= 0x2b_81f) # or (cp >= 0x2b_820 and cp <= 0x2c_eaf) # or (cp >= 0xf_900 and cp <= 0xf_aff) or (cp >= 0x2f_800 and cp <= 0x2f_a1f) # ): # return True return False class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = Queue() snake_case: List[str] = None snake_case: Tuple = timeout def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False ): '''simple docstring''' self.text_queue.put(SCREAMING_SNAKE_CASE__ , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self ): '''simple docstring''' return self def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
692
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = "layer_norm" , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__() snake_case: List[str] = only_cross_attention snake_case: Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero' snake_case: Tuple = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to""" F""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""" ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: snake_case: List[str] = AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: snake_case: str = AdaLayerNormZero(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: snake_case: int = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = Attention( query_dim=SCREAMING_SNAKE_CASE__ , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. snake_case: Tuple = ( AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) ) snake_case: Any = Attention( query_dim=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # is self-attn if encoder_hidden_states is none else: snake_case: int = None snake_case: Tuple = None # 3. Feed-forward snake_case: Union[str, Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = FeedForward(SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , activation_fn=SCREAMING_SNAKE_CASE__ , final_dropout=SCREAMING_SNAKE_CASE__ ) # let chunk size default to None snake_case: Any = None snake_case: Any = 0 def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = chunk_size snake_case: str = dim def _UpperCamelCase ( 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 , ): '''simple docstring''' if self.use_ada_layer_norm: snake_case: Optional[int] = self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: snake_case , snake_case , snake_case , snake_case , snake_case: int = self.norma( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=hidden_states.dtype ) else: snake_case: List[str] = self.norma(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = cross_attention_kwargs if cross_attention_kwargs is not None else {} snake_case: List[str] = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if self.use_ada_layer_norm_zero: snake_case: Tuple = gate_msa.unsqueeze(1 ) * attn_output snake_case: List[str] = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: snake_case: Dict = ( self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else self.norma(SCREAMING_SNAKE_CASE__ ) ) snake_case: Any = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case: List[str] = attn_output + hidden_states # 3. Feed-forward snake_case: str = self.norma(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: snake_case: str = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""" ) snake_case: List[str] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size snake_case: Optional[Any] = torch.cat( [self.ff(SCREAMING_SNAKE_CASE__ ) for hid_slice in norm_hidden_states.chunk(SCREAMING_SNAKE_CASE__ , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: snake_case: int = self.ff(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: snake_case: Union[str, Any] = gate_mlp.unsqueeze(1 ) * ff_output snake_case: Tuple = ff_output + hidden_states return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 4 , SCREAMING_SNAKE_CASE__ = 0.0 , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__() snake_case: int = int(dim * mult ) snake_case: Optional[Any] = dim_out if dim_out is not None else dim if activation_fn == "gelu": snake_case: int = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if activation_fn == "gelu-approximate": snake_case: Optional[Any] = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , approximate='tanh' ) elif activation_fn == "geglu": snake_case: List[Any] = GEGLU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif activation_fn == "geglu-approximate": snake_case: Optional[int] = ApproximateGELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Any = nn.ModuleList([] ) # project in self.net.append(SCREAMING_SNAKE_CASE__ ) # project dropout self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) # project out self.net.append(nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' for module in self.net: snake_case: Optional[int] = module(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "none" ): '''simple docstring''' super().__init__() snake_case: Optional[int] = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = approximate def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.proj(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = self.gelu(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = nn.Linear(SCREAMING_SNAKE_CASE__ , dim_out * 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case , snake_case: int = self.proj(SCREAMING_SNAKE_CASE__ ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = self.proj(SCREAMING_SNAKE_CASE__ ) return x * torch.sigmoid(1.7_02 * x ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Optional[Any] = nn.Embedding(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = nn.SiLU() snake_case: Union[str, Any] = nn.Linear(SCREAMING_SNAKE_CASE__ , embedding_dim * 2 ) snake_case: int = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ ) ) ) snake_case , snake_case: Dict = torch.chunk(SCREAMING_SNAKE_CASE__ , 2 ) snake_case: str = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale) + shift return x class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = CombinedTimestepLabelEmbeddings(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.SiLU() snake_case: Any = nn.Linear(SCREAMING_SNAKE_CASE__ , 6 * embedding_dim , bias=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ , eps=1E-6 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' snake_case: int = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=SCREAMING_SNAKE_CASE__ ) ) ) snake_case , snake_case , snake_case , snake_case , snake_case , snake_case: str = emb.chunk(6 , dim=1 ) snake_case: Dict = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 1E-5 ): '''simple docstring''' super().__init__() snake_case: str = num_groups snake_case: str = eps if act_fn is None: snake_case: Dict = None else: snake_case: List[str] = get_activation(SCREAMING_SNAKE_CASE__ ) snake_case: Any = nn.Linear(SCREAMING_SNAKE_CASE__ , out_dim * 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.act: snake_case: Optional[Any] = self.act(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.linear(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = emb[:, :, None, None] snake_case , snake_case: List[Any] = emb.chunk(2 , dim=1 ) snake_case: Any = F.group_norm(SCREAMING_SNAKE_CASE__ , self.num_groups , eps=self.eps ) snake_case: Optional[int] = x * (1 + scale) + shift return x
692
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCAmelCase = { "configuration_bridgetower": [ "BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP", "BridgeTowerConfig", "BridgeTowerTextConfig", "BridgeTowerVisionConfig", ], "processing_bridgetower": ["BridgeTowerProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["BridgeTowerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST", "BridgeTowerForContrastiveLearning", "BridgeTowerForImageAndTextRetrieval", "BridgeTowerForMaskedLM", "BridgeTowerModel", "BridgeTowerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure)
692
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = RoCBertTokenizer __UpperCamelCase = None __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = filter_non_english def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: Any = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '你', '好', '是', '谁', 'a', 'b', 'c', 'd'] snake_case: List[Any] = {} snake_case: List[str] = {} for i, value in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = i snake_case: Union[str, Any] = i snake_case: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) snake_case: Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] ) snake_case: str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: Dict = tokenizer.tokenize('你好[SEP]你是谁' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['你', '好', '[SEP]', '你', '是', '谁'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] snake_case: Union[str, Any] = {} for i, token in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: str = i snake_case: Optional[int] = RoCBertWordpieceTokenizer(vocab=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) if self.test_rust_tokenizer: snake_case: int = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) def _UpperCamelCase ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" snake_case: List[str] = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , ) snake_case: Optional[int] = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE__ , 'do_lower_case' ) else False snake_case: int = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'Allen'), ((21, 23), '##NL'), ((23, 24), '##P'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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, 15), tokenizer_r.mask_token), ((16, 21), 'allen'), ((21, 23), '##nl'), ((23, 24), '##p'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = ['的', '人', '有'] snake_case: Any = ''.join(SCREAMING_SNAKE_CASE__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = True snake_case: List[Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = False snake_case: Union[str, Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: int = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that only the first Chinese character is not preceded by "##". snake_case: Union[str, Any] = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE__ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: int = tokenizer.encode('你好' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Any = tokenizer.encode('你是谁' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Dict = '你好,你是谁' snake_case: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer.prepare_for_model( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.encode_plus(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
692
1
'''simple docstring''' import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCAmelCase_ ( __A : str ): '''simple docstring''' snake_case: str = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(__A , __A ) def lowerCAmelCase_ ( __A : int ): '''simple docstring''' snake_case , snake_case: Optional[Any] = emb.weight.shape snake_case: Optional[Any] = nn.Linear(__A , __A , bias=__A ) snake_case: List[str] = emb.weight.data return lin_layer def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' snake_case: Tuple = torch.load(__A , map_location='cpu' ) snake_case: Optional[int] = mam_aaa['args'] or mam_aaa['cfg']['model'] snake_case: Union[str, Any] = mam_aaa['model'] remove_ignore_keys_(__A ) snake_case: Optional[Any] = state_dict['encoder.embed_tokens.weight'].shape[0] snake_case: str = MaMaaaConfig( vocab_size=__A , max_position_embeddings=10_24 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) snake_case: Optional[int] = state_dict['decoder.embed_tokens.weight'] snake_case: Union[str, Any] = MaMaaaForConditionalGeneration(__A ) model.model.load_state_dict(__A , strict=__A ) snake_case: Optional[int] = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument("fairseq_path", type=str, help="path to a model.pt on local filesystem.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") __UpperCAmelCase = parser.parse_args() __UpperCAmelCase = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
692
'''simple docstring''' from math import asin, atan, cos, radians, sin, sqrt, tan __UpperCAmelCase = 6378137.0 __UpperCAmelCase = 6356752.314245 __UpperCAmelCase = 6_378_137 def lowerCAmelCase_ ( __A : float , __A : float , __A : float , __A : float ): '''simple docstring''' snake_case: Optional[Any] = (AXIS_A - AXIS_B) / AXIS_A snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: Tuple = radians(__A ) snake_case: Tuple = radians(__A ) # Equation snake_case: List[Any] = sin((phi_a - phi_a) / 2 ) snake_case: Dict = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda snake_case: Union[str, Any] = sqrt(sin_sq_phi + (cos(__A ) * cos(__A ) * sin_sq_lambda) ) return 2 * RADIUS * asin(__A ) if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''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 convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __UpperCAmelCase = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = ["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__ = 1 / 2_55 , 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: Optional[Any] = size if size is not None else {'height': 3_84, 'width': 3_84} snake_case: int = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) snake_case: Dict = do_resize snake_case: int = size snake_case: Optional[Any] = resample snake_case: Optional[int] = do_rescale snake_case: Tuple = rescale_factor snake_case: Tuple = do_normalize snake_case: Tuple = image_mean if image_mean is not None else OPENAI_CLIP_MEAN snake_case: List[str] = image_std if image_std is not None else OPENAI_CLIP_STD snake_case: Tuple = do_convert_rgb def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: int = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""" ) snake_case: Tuple = (size['height'], size['width']) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( 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 _UpperCamelCase ( 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 _UpperCamelCase ( 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__ , ): '''simple docstring''' snake_case: Optional[int] = do_resize if do_resize is not None else self.do_resize snake_case: Dict = resample if resample is not None else self.resample snake_case: Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale snake_case: Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case: Tuple = do_normalize if do_normalize is not None else self.do_normalize snake_case: Any = 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: int = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb snake_case: Any = size if size is not None else self.size snake_case: Optional[Any] = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = 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_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: Any = [convert_to_rgb(SCREAMING_SNAKE_CASE__ ) for image in images] # All transformations expect numpy arrays. snake_case: Dict = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: snake_case: List[Any] = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=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: Any = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] snake_case: Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] snake_case: Optional[Any] = BatchFeature(data={'pixel_values': images} , tensor_type=SCREAMING_SNAKE_CASE__ ) return encoded_outputs
692
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCAmelCase = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
1
'''simple docstring''' 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() __UpperCAmelCase = logging.get_logger(__name__) def lowerCAmelCase_ ( __A : str ): '''simple docstring''' snake_case: Tuple = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: snake_case: List[Any] = 1_92 snake_case: Dict = 7_68 snake_case: Dict = 12 snake_case: List[str] = 3 snake_case: Any = [8_00, 13_33] snake_case: Any = False elif yolos_name == "yolos_s_dWr": snake_case: int = 3_30 snake_case: Tuple = 14 snake_case: Tuple = 6 snake_case: Dict = 13_20 elif "yolos_s" in yolos_name: snake_case: str = 3_84 snake_case: str = 15_36 snake_case: Any = 12 snake_case: int = 6 elif "yolos_b" in yolos_name: snake_case: List[Any] = [8_00, 13_44] snake_case: Union[str, Any] = 91 snake_case: List[str] = 'huggingface/label-files' snake_case: Optional[Any] = 'coco-detection-id2label.json' snake_case: Dict = json.load(open(hf_hub_download(__A , __A , repo_type='dataset' ) , 'r' ) ) snake_case: Any = {int(__A ): v for k, v in idalabel.items()} snake_case: Any = idalabel snake_case: Union[str, Any] = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase_ ( __A : dict , __A : YolosConfig , __A : bool = False ): '''simple docstring''' for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case: Optional[Any] = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) snake_case: Union[str, Any] = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case: Optional[Any] = in_proj_weight[: config.hidden_size, :] snake_case: Optional[int] = in_proj_bias[: config.hidden_size] snake_case: Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case: List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case: str = in_proj_weight[-config.hidden_size :, :] snake_case: List[str] = in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( __A : str ): '''simple docstring''' if "backbone" in name: snake_case: List[str] = name.replace('backbone' , 'vit' ) if "cls_token" in name: snake_case: Optional[int] = name.replace('cls_token' , 'embeddings.cls_token' ) if "det_token" in name: snake_case: Tuple = name.replace('det_token' , 'embeddings.detection_tokens' ) if "mid_pos_embed" in name: snake_case: List[Any] = name.replace('mid_pos_embed' , 'encoder.mid_position_embeddings' ) if "pos_embed" in name: snake_case: Optional[int] = name.replace('pos_embed' , 'embeddings.position_embeddings' ) if "patch_embed.proj" in name: snake_case: Dict = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "blocks" in name: snake_case: Tuple = name.replace('blocks' , 'encoder.layer' ) if "attn.proj" in name: snake_case: Optional[Any] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: snake_case: Optional[int] = name.replace('attn' , 'attention.self' ) if "norm1" in name: snake_case: Union[str, Any] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: snake_case: Any = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: snake_case: Optional[Any] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: snake_case: Any = name.replace('mlp.fc2' , 'output.dense' ) if "class_embed" in name: snake_case: List[Any] = name.replace('class_embed' , 'class_labels_classifier' ) if "bbox_embed" in name: snake_case: str = name.replace('bbox_embed' , 'bbox_predictor' ) if "vit.norm" in name: snake_case: List[Any] = name.replace('vit.norm' , 'vit.layernorm' ) return name def lowerCAmelCase_ ( __A : dict , __A : YolosForObjectDetection ): '''simple docstring''' for key in orig_state_dict.copy().keys(): snake_case: Union[str, Any] = orig_state_dict.pop(__A ) if "qkv" in key: snake_case: Dict = key.split('.' ) snake_case: List[Any] = int(key_split[2] ) snake_case: List[str] = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: snake_case: Tuple = val[:dim, :] snake_case: Any = val[ dim : dim * 2, : ] snake_case: Tuple = val[-dim:, :] else: snake_case: int = val[:dim] snake_case: str = val[dim : dim * 2] snake_case: List[Any] = val[-dim:] else: snake_case: List[str] = val return orig_state_dict def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Union[str, Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case: List[Any] = Image.open(requests.get(__A , stream=__A ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( __A : str , __A : str , __A : str , __A : bool = False ): '''simple docstring''' snake_case: str = get_yolos_config(__A ) # load original state_dict snake_case: List[Any] = torch.load(__A , map_location='cpu' )['model'] # load 🤗 model snake_case: Dict = YolosForObjectDetection(__A ) model.eval() snake_case: str = convert_state_dict(__A , __A ) model.load_state_dict(__A ) # Check outputs on an image, prepared by YolosImageProcessor snake_case: Tuple = 8_00 if yolos_name != 'yolos_ti' else 5_12 snake_case: Any = YolosImageProcessor(format='coco_detection' , size=__A ) snake_case: Union[str, Any] = image_processor(images=prepare_img() , return_tensors='pt' ) snake_case: Any = model(**__A ) snake_case , snake_case: Optional[Any] = outputs.logits, outputs.pred_boxes snake_case , snake_case: Optional[int] = None, None if yolos_name == "yolos_ti": snake_case: Optional[Any] = torch.tensor( [[-39.50_22, -11.98_20, -17.68_88], [-29.95_74, -9.97_69, -17.76_91], [-42.32_81, -20.72_00, -30.62_94]] ) snake_case: Optional[int] = torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": snake_case: Dict = torch.tensor( [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]] ) snake_case: List[Any] = torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": snake_case: int = torch.tensor( [[-36.22_20, -14.43_85, -23.54_57], [-35.69_70, -14.75_83, -21.39_35], [-31.59_39, -13.60_42, -16.80_49]] ) snake_case: List[Any] = torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": snake_case: Tuple = torch.tensor( [[-42.86_68, -24.10_49, -41.16_90], [-34.74_56, -14.12_74, -24.91_94], [-33.78_98, -12.19_46, -25.64_95]] ) snake_case: Any = torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": snake_case: str = torch.tensor( [[-40.60_64, -24.30_84, -32.64_47], [-55.19_90, -30.77_19, -35.58_77], [-51.43_11, -33.35_07, -35.64_62]] ) snake_case: Dict = torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(f"""Unknown yolos_name: {yolos_name}""" ) assert torch.allclose(logits[0, :3, :3] , __A , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , __A , atol=1E-4 ) Path(__A ).mkdir(exist_ok=__A ) print(f"""Saving model {yolos_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 push_to_hub: snake_case: Any = { '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...' ) snake_case: int = model_mapping[yolos_name] image_processor.push_to_hub(__A , organization='hustvl' ) model.push_to_hub(__A , organization='hustvl' ) if __name__ == "__main__": __UpperCAmelCase = 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." ) __UpperCAmelCase = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
692
'''simple docstring''' import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def lowerCAmelCase_ ( __A : Tuple ): '''simple docstring''' snake_case: Tuple = model.config snake_case: str = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=1_28 , ) snake_case: Optional[Any] = MBartConfig( is_decoder=__A , is_encoder_decoder=__A , add_cross_attention=__A , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=__A , add_final_layer_norm=__A , ) return encoder_config, decoder_config def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if "encoder.model" in name: snake_case: Optional[Any] = name.replace('encoder.model' , 'encoder' ) if "decoder.model" in name: snake_case: str = name.replace('decoder.model' , 'decoder' ) if "patch_embed.proj" in name: snake_case: Any = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: snake_case: Optional[int] = name.replace('patch_embed.norm' , 'embeddings.norm' ) if name.startswith('encoder' ): if "layers" in name: snake_case: Tuple = 'encoder.' + name if "attn.proj" in name: snake_case: Optional[int] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name and "mask" not in name: snake_case: Dict = name.replace('attn' , 'attention.self' ) if "norm1" in name: snake_case: Union[str, Any] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: snake_case: Dict = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: snake_case: List[str] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: snake_case: Dict = name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": snake_case: Dict = 'encoder.layernorm.weight' if name == "encoder.norm.bias": snake_case: int = 'encoder.layernorm.bias' return name def lowerCAmelCase_ ( __A : List[Any] , __A : Optional[Any] ): '''simple docstring''' for key in orig_state_dict.copy().keys(): snake_case: List[Any] = orig_state_dict.pop(__A ) if "qkv" in key: snake_case: Union[str, Any] = key.split('.' ) snake_case: Optional[Any] = int(key_split[3] ) snake_case: Any = int(key_split[5] ) snake_case: Union[str, Any] = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: snake_case: Union[str, Any] = val[:dim, :] snake_case: Any = val[dim : dim * 2, :] snake_case: List[str] = val[-dim:, :] else: snake_case: str = val[:dim] snake_case: Union[str, Any] = val[dim : dim * 2] snake_case: List[Any] = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: snake_case: Optional[int] = val return orig_state_dict def lowerCAmelCase_ ( __A : List[Any] , __A : Any=None , __A : List[str]=False ): '''simple docstring''' snake_case: str = DonutModel.from_pretrained(__A ).eval() # load HuggingFace model snake_case , snake_case: Optional[Any] = get_configs(__A ) snake_case: Optional[int] = DonutSwinModel(__A ) snake_case: Tuple = MBartForCausalLM(__A ) snake_case: Optional[Any] = VisionEncoderDecoderModel(encoder=__A , decoder=__A ) model.eval() snake_case: Optional[int] = original_model.state_dict() snake_case: Optional[int] = convert_state_dict(__A , __A ) model.load_state_dict(__A ) # verify results on scanned document snake_case: Union[str, Any] = load_dataset('hf-internal-testing/example-documents' ) snake_case: str = dataset['test'][0]['image'].convert('RGB' ) snake_case: Optional[int] = XLMRobertaTokenizerFast.from_pretrained(__A , from_slow=__A ) snake_case: Any = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) snake_case: Dict = DonutProcessor(__A , __A ) snake_case: Optional[Any] = processor(__A , return_tensors='pt' ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": snake_case: int = '<s_docvqa><s_question>{user_input}</s_question><s_answer>' snake_case: Optional[Any] = 'When is the coffee break?' snake_case: Optional[int] = task_prompt.replace('{user_input}' , __A ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": snake_case: Dict = '<s_rvlcdip>' elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: snake_case: str = '<s_cord>' elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": snake_case: str = 's_cord-v2>' elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": snake_case: int = '<s_zhtrainticket>' elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt snake_case: Optional[Any] = 'hello world' else: raise ValueError('Model name not supported' ) snake_case: Optional[int] = original_model.decoder.tokenizer(__A , add_special_tokens=__A , return_tensors='pt' )[ 'input_ids' ] snake_case: Any = original_model.encoder.model.patch_embed(__A ) snake_case , snake_case: Dict = model.encoder.embeddings(__A ) assert torch.allclose(__A , __A , atol=1E-3 ) # verify encoder hidden states snake_case: Tuple = original_model.encoder(__A ) snake_case: List[str] = model.encoder(__A ).last_hidden_state assert torch.allclose(__A , __A , atol=1E-2 ) # verify decoder hidden states snake_case: List[Any] = original_model(__A , __A , __A ).logits snake_case: List[Any] = model(__A , decoder_input_ids=__A ).logits assert torch.allclose(__A , __A , atol=1E-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(__A ) processor.save_pretrained(__A ) if push_to_hub: model.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) processor.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) __UpperCAmelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
692
1
'''simple docstring''' from __future__ import annotations from random import random class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' snake_case: Optional[Any] = value snake_case: List[str] = random() snake_case: Node | None = None snake_case: Node | None = None def __repr__( self ): '''simple docstring''' from pprint import pformat if self.left is None and self.right is None: return F"""'{self.value}: {self.prior:.5}'""" else: return pformat( {F"""{self.value}: {self.prior:.5}""": (self.left, self.right)} , indent=1 ) def __str__( self ): '''simple docstring''' snake_case: Union[str, Any] = str(self.value ) + ' ' snake_case: str = str(self.left or '' ) snake_case: Union[str, Any] = str(self.right or '' ) return value + left + right def lowerCAmelCase_ ( __A : Node | None , __A : int ): '''simple docstring''' if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: snake_case , snake_case: Dict = split(root.left , __A ) return left, root else: snake_case , snake_case: Any = split(root.right , __A ) return root, right def lowerCAmelCase_ ( __A : Node | None , __A : Node | None ): '''simple docstring''' if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: snake_case: Optional[Any] = merge(left.right , __A ) return left else: snake_case: List[Any] = merge(__A , right.left ) return right def lowerCAmelCase_ ( __A : Node | None , __A : int ): '''simple docstring''' snake_case: Optional[Any] = Node(__A ) snake_case , snake_case: int = split(__A , __A ) return merge(merge(__A , __A ) , __A ) def lowerCAmelCase_ ( __A : Node | None , __A : int ): '''simple docstring''' snake_case , snake_case: List[Any] = split(__A , value - 1 ) snake_case , snake_case: Any = split(__A , __A ) return merge(__A , __A ) def lowerCAmelCase_ ( __A : Node | None ): '''simple docstring''' if not root: # None return else: inorder(root.left ) print(root.value , end=',' ) inorder(root.right ) def lowerCAmelCase_ ( __A : Node | None , __A : str ): '''simple docstring''' for arg in args.split(): if arg[0] == "+": snake_case: str = insert(__A , int(arg[1:] ) ) elif arg[0] == "-": snake_case: Dict = erase(__A , int(arg[1:] ) ) else: print('Unknown command' ) return root def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Optional[int] = None print( 'enter numbers to create a tree, + value to add value into treap, ' '- value to erase all nodes with value. \'q\' to quit. ' ) snake_case: Any = input() while args != "q": snake_case: str = interact_treap(__A , __A ) print(__A ) snake_case: List[Any] = input() print('good by!' ) if __name__ == "__main__": import doctest doctest.testmod() main()
692
'''simple docstring''' 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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = { 'task_specific_params': { 'summarization': {'length_penalty': 1.0, 'max_length': 1_28, 'min_length': 12, 'num_beams': 4}, 'summarization_cnn': {'length_penalty': 2.0, 'max_length': 1_42, 'min_length': 56, 'num_beams': 4}, 'summarization_xsum': {'length_penalty': 1.0, 'max_length': 62, 'min_length': 11, 'num_beams': 6}, } } snake_case: Union[str, Any] = { 'task_specific_params.summarization.length_penalty': 1.0, 'task_specific_params.summarization.max_length': 1_28, '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': 1_42, '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(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , x.transpose() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = np.random.randn(3 , 4 ) snake_case: Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(3 , 4 , 5 ) snake_case: Optional[int] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Dict = np.random.randn(3 , 4 , 5 ) snake_case: str = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Optional[int] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Optional[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) snake_case: Optional[int] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: str = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: List[str] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.squeeze(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: List[str] = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) snake_case: List[str] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: int = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = np.random.randn(1 , 3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Union[str, Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(1 , 3 , 4 ) snake_case: List[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Tuple = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Tuple = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Any = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Any = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = np.random.randn(3 , 4 ) snake_case: int = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.asarray(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) )
692
1
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def lowerCAmelCase_ ( __A : dict , __A : str , __A : set , __A : set , __A : dict , __A : dict , __A : PriorityQueue , __A : dict , __A : float | int , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue snake_case: Any = cst_fwd.get(__A , np.inf ) snake_case: int = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) snake_case: Union[str, Any] = new_cost_f snake_case: Tuple = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: snake_case: List[str] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def lowerCAmelCase_ ( __A : str , __A : str , __A : dict , __A : dict ): '''simple docstring''' snake_case: Optional[Any] = -1 snake_case: Any = set() snake_case: str = set() snake_case: int = {source: 0} snake_case: Dict = {destination: 0} snake_case: int = {source: None} snake_case: Union[str, Any] = {destination: None} snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: Tuple = 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(): snake_case , snake_case: List[str] = queue_forward.get() visited_forward.add(__A ) snake_case , snake_case: int = queue_backward.get() visited_backward.add(__A ) snake_case: str = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) snake_case: Optional[Any] = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: snake_case: Any = shortest_distance return shortest_path_distance __UpperCAmelCase = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } __UpperCAmelCase = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
692
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig __UpperCAmelCase = logging.get_logger(__name__) # General docstring __UpperCAmelCase = "PoolFormerConfig" # Base docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = [1, 512, 7, 7] # Image classification docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = "tabby, tabby cat" __UpperCAmelCase = [ "sail/poolformer_s12", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCAmelCase_ ( __A : Tuple , __A : float = 0.0 , __A : bool = False ): '''simple docstring''' if drop_prob == 0.0 or not training: return input snake_case: Union[str, Any] = 1 - drop_prob snake_case: List[Any] = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets snake_case: List[Any] = keep_prob + torch.rand(__A , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize snake_case: Any = input.div(__A ) * random_tensor return output class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' super().__init__() snake_case: List[str] = drop_prob def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return drop_path(SCREAMING_SNAKE_CASE__ , self.drop_prob , self.training ) def _UpperCamelCase ( self ): '''simple docstring''' return "p={}".format(self.drop_prob ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' super().__init__() snake_case: List[str] = patch_size if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (patch_size, patch_size) snake_case: List[str] = stride if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (stride, stride) snake_case: Union[str, Any] = padding if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (padding, padding) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , kernel_size=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = norm_layer(SCREAMING_SNAKE_CASE__ ) if norm_layer else nn.Identity() def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.projection(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.norm(SCREAMING_SNAKE_CASE__ ) return embeddings class SCREAMING_SNAKE_CASE ( nn.GroupNorm ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(1 , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.AvgPoolad(SCREAMING_SNAKE_CASE__ , stride=1 , padding=pool_size // 2 , count_include_pad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.pool(SCREAMING_SNAKE_CASE__ ) - hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: str = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if isinstance(config.hidden_act , SCREAMING_SNAKE_CASE__ ): snake_case: Tuple = ACTaFN[config.hidden_act] else: snake_case: int = config.hidden_act def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.act_fn(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.drop(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: str = self.drop(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = PoolFormerPooling(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerOutput(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) # Useful for training neural nets snake_case: Union[str, Any] = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if drop_path > 0.0 else nn.Identity() snake_case: Optional[Any] = config.use_layer_scale if config.use_layer_scale: snake_case: Any = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.use_layer_scale: snake_case: str = self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Dict = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection snake_case: str = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = () snake_case: Dict = self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Union[str, Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection snake_case: Any = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = (output,) + outputs return outputs else: snake_case: Optional[Any] = self.drop_path(self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) ) # First residual connection snake_case: Union[str, Any] = pooling_output + hidden_states snake_case: List[Any] = () # Second residual connection inside the PoolFormerOutput block snake_case: List[str] = self.drop_path(self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: Dict = hidden_states + layer_output snake_case: Optional[Any] = (output,) + outputs return outputs class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = config # stochastic depth decay rule snake_case: List[Any] = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings snake_case: Union[str, Any] = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) snake_case: List[Any] = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) # Transformer blocks snake_case: str = [] snake_case: int = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers snake_case: List[str] = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( SCREAMING_SNAKE_CASE__ , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(SCREAMING_SNAKE_CASE__ ) ) snake_case: Tuple = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True ): '''simple docstring''' snake_case: str = () if output_hidden_states else None snake_case: Dict = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): snake_case , snake_case: Dict = layers # Get patch embeddings from hidden_states snake_case: int = embedding_layer(SCREAMING_SNAKE_CASE__ ) # Send the embeddings through the blocks for _, blk in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = blk(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = layer_outputs[0] if output_hidden_states: snake_case: List[str] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = PoolFormerConfig __UpperCamelCase = "poolformer" __UpperCamelCase = "pixel_values" __UpperCamelCase = True def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = value __UpperCAmelCase = R"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" __UpperCAmelCase = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n" @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = config snake_case: Tuple = PoolFormerEncoder(SCREAMING_SNAKE_CASE__ ) # Initialize weights and apply final processing self.post_init() def _UpperCamelCase ( self ): '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Optional[int] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case: List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) snake_case: Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: List[Any] = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=encoder_outputs.hidden_states , ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Any = nn.Linear(config.hidden_size , config.hidden_size ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.dense(SCREAMING_SNAKE_CASE__ ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = config.num_labels snake_case: str = PoolFormerModel(SCREAMING_SNAKE_CASE__ ) # Final norm snake_case: int = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head snake_case: Dict = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict snake_case: Optional[Any] = self.poolformer( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: Any = outputs[0] snake_case: str = self.classifier(self.norm(SCREAMING_SNAKE_CASE__ ).mean([-2, -1] ) ) snake_case: Any = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: snake_case: Tuple = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): snake_case: Dict = 'single_label_classification' else: snake_case: List[str] = 'multi_label_classification' if self.config.problem_type == "regression": snake_case: Union[str, Any] = MSELoss() if self.num_labels == 1: snake_case: List[str] = loss_fct(logits.squeeze() , labels.squeeze() ) else: snake_case: int = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.config.problem_type == "single_label_classification": snake_case: Union[str, Any] = CrossEntropyLoss() snake_case: Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": snake_case: int = BCEWithLogitsLoss() snake_case: Optional[int] = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not return_dict: snake_case: str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=SCREAMING_SNAKE_CASE__ , logits=SCREAMING_SNAKE_CASE__ , hidden_states=outputs.hidden_states )
692
1
'''simple docstring''' def lowerCAmelCase_ ( __A : int , __A : int , __A : list[list[int]] ): '''simple docstring''' def update_area_of_max_square(__A : int , __A : int ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 snake_case: List[Any] = update_area_of_max_square(__A , col + 1 ) snake_case: Dict = update_area_of_max_square(row + 1 , col + 1 ) snake_case: List[Any] = update_area_of_max_square(row + 1 , __A ) if mat[row][col]: snake_case: Optional[int] = 1 + min([right, diagonal, down] ) snake_case: int = max(largest_square_area[0] , __A ) return sub_problem_sol else: return 0 snake_case: Tuple = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def lowerCAmelCase_ ( __A : int , __A : int , __A : list[list[int]] ): '''simple docstring''' def update_area_of_max_square_using_dp_array( __A : int , __A : int , __A : list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] snake_case: Optional[Any] = update_area_of_max_square_using_dp_array(__A , col + 1 , __A ) snake_case: Dict = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , __A ) snake_case: List[Any] = update_area_of_max_square_using_dp_array(row + 1 , __A , __A ) if mat[row][col]: snake_case: str = 1 + min([right, diagonal, down] ) snake_case: Any = max(largest_square_area[0] , __A ) snake_case: int = sub_problem_sol return sub_problem_sol else: return 0 snake_case: Tuple = [0] snake_case: Union[str, Any] = [[-1] * cols for _ in range(__A )] update_area_of_max_square_using_dp_array(0 , 0 , __A ) return largest_square_area[0] def lowerCAmelCase_ ( __A : int , __A : int , __A : list[list[int]] ): '''simple docstring''' snake_case: str = [[0] * (cols + 1) for _ in range(rows + 1 )] snake_case: Dict = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): snake_case: Optional[int] = dp_array[row][col + 1] snake_case: Optional[int] = dp_array[row + 1][col + 1] snake_case: int = dp_array[row + 1][col] if mat[row][col] == 1: snake_case: Optional[Any] = 1 + min(__A , __A , __A ) snake_case: List[Any] = max(dp_array[row][col] , __A ) else: snake_case: Optional[Any] = 0 return largest_square_area def lowerCAmelCase_ ( __A : int , __A : int , __A : list[list[int]] ): '''simple docstring''' snake_case: str = [0] * (cols + 1) snake_case: Union[str, Any] = [0] * (cols + 1) snake_case: Union[str, Any] = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): snake_case: Any = current_row[col + 1] snake_case: str = next_row[col + 1] snake_case: List[str] = next_row[col] if mat[row][col] == 1: snake_case: Dict = 1 + min(__A , __A , __A ) snake_case: Dict = max(current_row[col] , __A ) else: snake_case: str = 0 snake_case: List[str] = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
692
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def lowerCAmelCase_ ( __A : dict , __A : str , __A : set , __A : set , __A : dict , __A : dict , __A : PriorityQueue , __A : dict , __A : float | int , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue snake_case: Any = cst_fwd.get(__A , np.inf ) snake_case: int = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) snake_case: Union[str, Any] = new_cost_f snake_case: Tuple = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: snake_case: List[str] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def lowerCAmelCase_ ( __A : str , __A : str , __A : dict , __A : dict ): '''simple docstring''' snake_case: Optional[Any] = -1 snake_case: Any = set() snake_case: str = set() snake_case: int = {source: 0} snake_case: Dict = {destination: 0} snake_case: int = {source: None} snake_case: Union[str, Any] = {destination: None} snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: Tuple = 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(): snake_case , snake_case: List[str] = queue_forward.get() visited_forward.add(__A ) snake_case , snake_case: int = queue_backward.get() visited_backward.add(__A ) snake_case: str = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) snake_case: Optional[Any] = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: snake_case: Any = shortest_distance return shortest_path_distance __UpperCAmelCase = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } __UpperCAmelCase = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase = { "configuration_instructblip": [ "INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "InstructBlipConfig", "InstructBlipQFormerConfig", "InstructBlipVisionConfig", ], "processing_instructblip": ["InstructBlipProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "InstructBlipQFormerModel", "InstructBlipPreTrainedModel", "InstructBlipForConditionalGeneration", "InstructBlipVisionModel", ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = "▁" __UpperCAmelCase = {"vocab_file": "sentencepiece.bpe.model"} __UpperCAmelCase = { "vocab_file": { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model", } } __UpperCAmelCase = { "facebook/xglm-564M": 2_048, } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer snake_case: Optional[Any] = 7 snake_case: List[str] = [F"""<madeupword{i}>""" for i in range(self.num_madeup_words )] snake_case: str = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) snake_case: int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) snake_case: int = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab snake_case: Tuple = 1 # Mimic fairseq token-to-id alignment for the first 4 token snake_case: Optional[Any] = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} snake_case: Union[str, Any] = len(self.sp_model ) snake_case: str = {F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ): '''simple docstring''' snake_case: List[Any] = self.__dict__.copy() snake_case: Union[str, Any] = None snake_case: Union[str, Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): snake_case: Union[str, Any] = {} snake_case: Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a snake_case: Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' snake_case: int = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def _UpperCamelCase ( self ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case: Dict = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip() return out_string def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case: List[str] = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: snake_case: int = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
692
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "facebook/timesformer": "https://huggingface.co/facebook/timesformer/resolve/main/config.json", } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = "timesformer" def __init__( self , SCREAMING_SNAKE_CASE__=2_24 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=8 , SCREAMING_SNAKE_CASE__=7_68 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=30_72 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-6 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__="divided_space_time" , SCREAMING_SNAKE_CASE__=0 , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = image_size snake_case: Tuple = patch_size snake_case: int = num_channels snake_case: int = num_frames snake_case: Tuple = hidden_size snake_case: Optional[int] = num_hidden_layers snake_case: Any = num_attention_heads snake_case: Tuple = intermediate_size snake_case: List[str] = hidden_act snake_case: int = hidden_dropout_prob snake_case: List[str] = attention_probs_dropout_prob snake_case: List[str] = initializer_range snake_case: int = layer_norm_eps snake_case: str = qkv_bias snake_case: Optional[int] = attention_type snake_case: List[str] = drop_path_rate
692
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' return getitem, k def lowerCAmelCase_ ( __A : Any , __A : Optional[int] ): '''simple docstring''' return setitem, k, v def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' return delitem, k def lowerCAmelCase_ ( __A : str , __A : int , *__A : Tuple ): '''simple docstring''' try: return fun(__A , *__A ), None except Exception as e: return None, e __UpperCAmelCase = ( _set("key_a", "val_a"), _set("key_b", "val_b"), ) __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_a", "val_b"), ] __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_b", "val_b"), _del("key_a"), _del("key_b"), _set("key_a", "val_a"), _del("key_a"), ] __UpperCAmelCase = [ _get("key_a"), _del("key_a"), _set("key_a", "val_a"), _del("key_a"), _del("key_a"), _get("key_a"), ] __UpperCAmelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] __UpperCAmelCase = [ *[_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 lowerCAmelCase_ ( __A : str ): '''simple docstring''' snake_case: List[Any] = HashMap(initial_block_size=4 ) snake_case: List[Any] = {} for _, (fun, *args) in enumerate(__A ): snake_case , snake_case: Optional[int] = _run_operation(__A , __A , *__A ) snake_case , snake_case: str = _run_operation(__A , __A , *__A ) assert my_res == py_res assert str(__A ) == str(__A ) assert set(__A ) == set(__A ) assert len(__A ) == len(__A ) assert set(my.items() ) == set(py.items() ) def lowerCAmelCase_ ( ): '''simple docstring''' def is_public(__A : str ) -> bool: return not name.startswith('_' ) snake_case: Dict = {name for name in dir({} ) if is_public(__A )} snake_case: List[str] = {name for name in dir(HashMap() ) if is_public(__A )} assert dict_public_names > hash_public_names
692
1
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "EleutherAI/gpt-j-6B": "https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json", # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = "gptj" __UpperCamelCase = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , SCREAMING_SNAKE_CASE__=5_04_00 , SCREAMING_SNAKE_CASE__=20_48 , SCREAMING_SNAKE_CASE__=40_96 , SCREAMING_SNAKE_CASE__=28 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=64 , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__="gelu_new" , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=5_02_56 , SCREAMING_SNAKE_CASE__=5_02_56 , SCREAMING_SNAKE_CASE__=False , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: Optional[int] = vocab_size snake_case: Any = n_positions snake_case: Tuple = n_embd snake_case: Tuple = n_layer snake_case: List[str] = n_head snake_case: Optional[Any] = n_inner snake_case: Optional[Any] = rotary_dim snake_case: Dict = activation_function snake_case: int = resid_pdrop snake_case: List[Any] = embd_pdrop snake_case: Optional[Any] = attn_pdrop snake_case: Optional[Any] = layer_norm_epsilon snake_case: Union[str, Any] = initializer_range snake_case: Any = use_cache snake_case: Optional[int] = bos_token_id snake_case: List[str] = eos_token_id super().__init__( bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , tie_word_embeddings=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "default" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ , task=SCREAMING_SNAKE_CASE__ , patching_specs=SCREAMING_SNAKE_CASE__ , use_past=SCREAMING_SNAKE_CASE__ ) if not getattr(self._config , 'pad_token_id' , SCREAMING_SNAKE_CASE__ ): # TODO: how to do that better? snake_case: Optional[Any] = 0 @property def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE__ , direction='inputs' ) snake_case: Any = {0: 'batch', 1: 'past_sequence + sequence'} else: snake_case: str = {0: 'batch', 1: 'sequence'} return common_inputs @property def _UpperCamelCase ( self ): '''simple docstring''' return self._config.n_layer @property def _UpperCamelCase ( self ): '''simple docstring''' return self._config.n_head def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Optional[int] = super(SCREAMING_SNAKE_CASE__ , self ).generate_dummy_inputs( SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , seq_length=SCREAMING_SNAKE_CASE__ , is_pair=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) # We need to order the input in the way they appears in the forward() snake_case: Optional[int] = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch snake_case , snake_case: int = common_inputs['input_ids'].shape # Not using the same length for past_key_values snake_case: Any = seqlen + 2 snake_case: Any = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) snake_case: Dict = [ (torch.zeros(SCREAMING_SNAKE_CASE__ ), torch.zeros(SCREAMING_SNAKE_CASE__ )) for _ in range(self.num_layers ) ] snake_case: Optional[int] = common_inputs['attention_mask'] if self.use_past: snake_case: List[Any] = ordered_inputs['attention_mask'].dtype snake_case: str = torch.cat( [ordered_inputs['attention_mask'], torch.ones(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ )] , dim=1 ) return ordered_inputs @property def _UpperCamelCase ( self ): '''simple docstring''' return 13
692
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "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": "lm_head", "mask_emb": "masked_spec_embed", } __UpperCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def lowerCAmelCase_ ( __A : Any , __A : Optional[Any] , __A : Union[str, Any] , __A : int , __A : Optional[int] ): '''simple docstring''' for attribute in key.split('.' ): snake_case: List[str] = getattr(__A , __A ) if weight_type is not None: snake_case: Optional[int] = getattr(__A , __A ).shape else: snake_case: Optional[int] = 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": snake_case: Optional[int] = value elif weight_type == "weight_g": snake_case: List[str] = value elif weight_type == "weight_v": snake_case: Dict = value elif weight_type == "bias": snake_case: Optional[Any] = value else: snake_case: int = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def lowerCAmelCase_ ( __A : List[Any] , __A : List[str] ): '''simple docstring''' snake_case: List[Any] = [] snake_case: List[Any] = fairseq_model.state_dict() snake_case: Union[str, Any] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight snake_case: Dict = None for name, value in fairseq_dict.items(): snake_case: Tuple = False if "conv_layers" in name: load_conv_layer( __A , __A , __A , __A , hf_model.config.feat_extract_norm == 'group' , ) snake_case: List[Any] = True elif name.split('.' )[0] == "proj": snake_case: List[Any] = fairseq_model.proj snake_case: int = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: snake_case: int = True if "*" in mapped_key: snake_case: List[str] = name.split(__A )[0].split('.' )[-2] snake_case: Dict = mapped_key.replace('*' , __A ) if "weight_g" in name: snake_case: Tuple = 'weight_g' elif "weight_v" in name: snake_case: int = 'weight_v' elif "bias" in name: snake_case: Tuple = 'bias' elif "weight" in name: snake_case: List[Any] = 'weight' else: snake_case: Any = None set_recursively(__A , __A , __A , __A , __A ) continue if not is_used: unused_weights.append(__A ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCAmelCase_ ( __A : List[str] , __A : List[Any] , __A : int , __A : Optional[Any] , __A : Optional[int] ): '''simple docstring''' snake_case: int = full_name.split('conv_layers.' )[-1] snake_case: Tuple = name.split('.' ) snake_case: Any = int(items[0] ) snake_case: Optional[int] = 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.""" ) snake_case: Tuple = 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.""" ) snake_case: int = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) snake_case: Any = 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.""" ) snake_case: str = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__A ) def lowerCAmelCase_ ( __A : Dict ): '''simple docstring''' snake_case , snake_case: List[Any] = emb.weight.shape snake_case: Optional[int] = nn.Linear(__A , __A , bias=__A ) snake_case: Any = emb.weight.data return lin_layer def lowerCAmelCase_ ( __A : Optional[int] ): '''simple docstring''' with open(__A , 'r' , encoding='utf-8' ) as f: snake_case: List[Any] = f.readlines() snake_case: Any = [line.split(' ' )[0] for line in lines] snake_case: int = len(__A ) snake_case: Dict = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(__A , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCAmelCase_ ( __A : Optional[Any] , __A : Union[str, Any] , __A : Dict , __A : Any , __A : List[Any] , __A : int , __A : str , ): '''simple docstring''' snake_case: Union[str, Any] = WavaVecaConfig.from_pretrained(__A ) snake_case: str = SpeechaTextaConfig.from_pretrained( __A , vocab_size=__A , decoder_layers=__A , do_stable_layer_norm=__A ) snake_case: List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=__A , return_attention_mask=__A , ) snake_case , snake_case , snake_case: List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) snake_case: List[Any] = model[0].eval() # set weights for wav2vec2 encoder snake_case: Optional[Any] = WavaVecaModel(__A ) snake_case: Any = recursively_load_weights_wavaveca(model.encoder , __A ) snake_case: Union[str, Any] = SpeechaTextaForCausalLM(__A ) snake_case , snake_case: Optional[Any] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__A ) # set output linear layer unexpected_keys.remove('embed_out' ) snake_case: str = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) snake_case: int = SpeechEncoderDecoderModel(encoder=__A , decoder=__A ) snake_case: List[Any] = False # add projection layer snake_case: Union[str, Any] = nn.Parameter(projection_layer.weight ) snake_case: Union[str, Any] = nn.Parameter(projection_layer.bias ) snake_case: List[Any] = create_vocab_dict(__A ) with open(os.path.join(__A , 'vocab.json' ) , 'w' ) as fp: json.dump(__A , __A ) snake_case: Union[str, Any] = SpeechaTextaTokenizer(os.path.join(__A , 'vocab.json' ) ) tokenizer.save_pretrained(__A ) snake_case: Tuple = hf_wavavec.config.to_dict() snake_case: int = tokenizer.pad_token_id snake_case: Dict = tokenizer.bos_token_id snake_case: Optional[int] = tokenizer.eos_token_id snake_case: Dict = 'speech_to_text_2' snake_case: Optional[Any] = 'wav2vec2' snake_case: Tuple = SpeechEncoderDecoderConfig.from_dict(__A ) hf_wavavec.save_pretrained(__A ) feature_extractor.save_pretrained(__A ) if __name__ == "__main__": __UpperCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") __UpperCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
692
1
'''simple docstring''' from math import factorial __UpperCAmelCase = {str(d): factorial(d) for d in range(10)} def lowerCAmelCase_ ( __A : int ): '''simple docstring''' return sum(DIGIT_FACTORIAL[d] for d in str(__A ) ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Dict = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , __A ) if sum_of_digit_factorial(__A ) == i ) if __name__ == "__main__": print(F'{solution() = }')
692
'''simple docstring''' def lowerCAmelCase_ ( __A : int = 1_00 ): '''simple docstring''' snake_case: List[str] = n * (n + 1) * (2 * n + 1) / 6 snake_case: List[Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F'{solution() = }')
692
1
'''simple docstring''' import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging __UpperCAmelCase = { "cola": 2, "mnli": 3, "mrpc": 2, "sst-2": 2, "sts-b": 1, "qqp": 2, "qnli": 2, "rte": 2, "wnli": 2, } logging.set_verbosity_info() def lowerCAmelCase_ ( __A : int , __A : Tuple , __A : int , __A : List[Any]=None ): '''simple docstring''' snake_case: List[str] = XLNetConfig.from_json_file(__A ) snake_case: List[str] = finetuning_task.lower() if finetuning_task is not None else '' if finetuning_task in GLUE_TASKS_NUM_LABELS: print(f"""Building PyTorch XLNetForSequenceClassification model from configuration: {config}""" ) snake_case: int = finetuning_task snake_case: List[Any] = GLUE_TASKS_NUM_LABELS[finetuning_task] snake_case: Optional[int] = XLNetForSequenceClassification(__A ) elif "squad" in finetuning_task: snake_case: Dict = finetuning_task snake_case: Optional[Any] = XLNetForQuestionAnswering(__A ) else: snake_case: Dict = XLNetLMHeadModel(__A ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(__A , __A , __A ) # Save pytorch-model snake_case: Optional[Any] = os.path.join(__A , __A ) snake_case: List[Any] = os.path.join(__A , __A ) print(f"""Save PyTorch model to {os.path.abspath(__A )}""" ) torch.save(model.state_dict() , __A ) print(f"""Save configuration file to {os.path.abspath(__A )}""" ) with open(__A , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--xlnet_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained XLNet model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--finetuning_task", default=None, type=str, help="Name of a task on which the XLNet TensorFlow model was fine-tuned", ) __UpperCAmelCase = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
692
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration __UpperCAmelCase = [ # tf -> hf ("/", "."), ("layer_", "layers."), ("kernel", "weight"), ("beta", "bias"), ("gamma", "weight"), ("pegasus", "model"), ] __UpperCAmelCase = [ (".output.dense", ".fc2"), ("intermediate.LayerNorm", "final_layer_norm"), ("intermediate.dense", "fc1"), ] __UpperCAmelCase = ( INIT_COMMON + [ ("attention.self.LayerNorm", "self_attn_layer_norm"), ("attention.output.dense", "self_attn.out_proj"), ("attention.self", "self_attn"), ("attention.encdec.LayerNorm", "encoder_attn_layer_norm"), ("attention.encdec_output.dense", "encoder_attn.out_proj"), ("attention.encdec", "encoder_attn"), ("key", "k_proj"), ("value", "v_proj"), ("query", "q_proj"), ("decoder.LayerNorm", "decoder.layernorm_embedding"), ] + END_COMMON ) __UpperCAmelCase = ( INIT_COMMON + [ ("embeddings.word_embeddings", "shared.weight"), ("embeddings.position_embeddings", "embed_positions.weight"), ("attention.self.LayerNorm", "self_attn_layer_norm"), ("attention.output.dense", "self_attn.output"), ("attention.self", "self_attn.self"), ("encoder.LayerNorm", "encoder.layernorm_embedding"), ] + END_COMMON ) __UpperCAmelCase = [ "encdec/key/bias", "encdec/query/bias", "encdec/value/bias", "self/key/bias", "self/query/bias", "self/value/bias", "encdec_output/dense/bias", "attention/output/dense/bias", ] def lowerCAmelCase_ ( __A : Dict , __A : List[Any] ): '''simple docstring''' for tf_name, hf_name in patterns: snake_case: List[Any] = k.replace(__A , __A ) return k def lowerCAmelCase_ ( __A : dict , __A : dict ): '''simple docstring''' snake_case: Optional[int] = BigBirdPegasusConfig(**__A ) snake_case: List[Any] = BigBirdPegasusForConditionalGeneration(__A ) snake_case: Any = torch_model.state_dict() snake_case: Any = {} # separating decoder weights snake_case: Optional[Any] = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder' )} snake_case: Any = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder' )} for k, v in tqdm(decoder_weights.items() , 'tf -> hf conversion' ): snake_case: List[str] = [k.endswith(__A ) for ending in KEYS_TO_IGNORE] if any(__A ): continue snake_case: Any = DECODER_PATTERNS snake_case: int = rename_state_dict_key(__A , __A ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): snake_case: Optional[Any] = v.T snake_case: Any = torch.from_numpy(__A ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items() , 'tf -> hf conversion' ): snake_case: List[Any] = [k.endswith(__A ) for ending in KEYS_TO_IGNORE] if any(__A ): continue snake_case: Union[str, Any] = REMAINING_PATTERNS snake_case: str = rename_state_dict_key(__A , __A ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): snake_case: int = v.T snake_case: Any = torch.from_numpy(__A ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" snake_case: str = mapping['model.embed_positions.weight'] snake_case: Any = mapping.pop('model.embed_positions.weight' ) snake_case , snake_case: Union[str, Any] = torch_model.load_state_dict(__A , strict=__A ) snake_case: Optional[int] = [ k for k in missing if k not in [ 'final_logits_bias', 'model.encoder.embed_tokens.weight', 'model.decoder.embed_tokens.weight', 'lm_head.weight', ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def lowerCAmelCase_ ( __A : Optional[int] ): '''simple docstring''' snake_case: Tuple = tf.train.list_variables(__A ) snake_case: str = {} snake_case: List[str] = ['global_step'] for name, shape in tqdm(__A , desc='converting tf checkpoint to dict' ): snake_case: str = any(pat in name for pat in ignore_name ) if skip_key: continue snake_case: Any = tf.train.load_variable(__A , __A ) snake_case: Optional[int] = array return tf_weights def lowerCAmelCase_ ( __A : str , __A : str , __A : dict ): '''simple docstring''' snake_case: int = get_tf_weights_as_numpy(__A ) snake_case: int = convert_bigbird_pegasus(__A , __A ) torch_model.save_pretrained(__A ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("--tf_ckpt_path", type=str, help="passed to tf.train.list_variables") parser.add_argument("--save_dir", default=None, type=str, help="Path to the output PyTorch model.") __UpperCAmelCase = parser.parse_args() __UpperCAmelCase = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
692
1
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ShapEPipeline __UpperCamelCase = ["prompt"] __UpperCamelCase = ["prompt"] __UpperCamelCase = [ "num_images_per_prompt", "num_inference_steps", "generator", "latents", "guidance_scale", "frame_size", "output_type", "return_dict", ] __UpperCamelCase = False @property def _UpperCamelCase ( self ): '''simple docstring''' return 32 @property def _UpperCamelCase ( self ): '''simple docstring''' return 32 @property def _UpperCamelCase ( self ): '''simple docstring''' return self.time_input_dim * 4 @property def _UpperCamelCase ( self ): '''simple docstring''' return 8 @property def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def _UpperCamelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) snake_case: Dict = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModelWithProjection(SCREAMING_SNAKE_CASE__ ) @property def _UpperCamelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) snake_case: Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } snake_case: Optional[Any] = PriorTransformer(**SCREAMING_SNAKE_CASE__ ) return model @property def _UpperCamelCase ( self ): '''simple docstring''' torch.manual_seed(0 ) snake_case: Tuple = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } snake_case: Union[str, Any] = ShapERenderer(**SCREAMING_SNAKE_CASE__ ) return model def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = self.dummy_prior snake_case: Dict = self.dummy_text_encoder snake_case: int = self.dummy_tokenizer snake_case: List[str] = self.dummy_renderer snake_case: Tuple = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=10_24 , prediction_type='sample' , use_karras_sigmas=SCREAMING_SNAKE_CASE__ , clip_sample=SCREAMING_SNAKE_CASE__ , clip_sample_range=1.0 , ) snake_case: Any = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0 ): '''simple docstring''' if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): snake_case: Union[str, Any] = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: snake_case: Union[str, Any] = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) snake_case: int = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = 'cpu' snake_case: List[str] = self.get_dummy_components() snake_case: Tuple = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) snake_case: int = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) ) snake_case: Union[str, Any] = output.images[0] snake_case: List[str] = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) snake_case: Union[str, Any] = np.array( [ 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _UpperCamelCase ( self ): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = torch_device == 'cpu' snake_case: Union[str, Any] = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=SCREAMING_SNAKE_CASE__ , relax_max_difference=SCREAMING_SNAKE_CASE__ , ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_dummy_components() snake_case: Dict = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = 1 snake_case: List[Any] = 2 snake_case: Optional[Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) for key in inputs.keys(): if key in self.batch_params: snake_case: Any = batch_size * [inputs[key]] snake_case: Dict = pipe(**SCREAMING_SNAKE_CASE__ , num_images_per_prompt=SCREAMING_SNAKE_CASE__ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) snake_case: Tuple = ShapEPipeline.from_pretrained('openai/shap-e' ) snake_case: List[str] = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(0 ) snake_case: int = pipe( 'a shark' , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
692
'''simple docstring''' def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' snake_case: str = [0] * len(__A ) snake_case: Tuple = [] snake_case: Tuple = [1] * len(__A ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__A ) ): if indegree[i] == 0: queue.append(__A ) while queue: snake_case: int = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: snake_case: Any = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(__A ) print(max(__A ) ) # Adjacency list of Graph __UpperCAmelCase = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
692
1
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = OrderedDict( [ # Base model mapping ("albert", "FlaxAlbertModel"), ("bart", "FlaxBartModel"), ("beit", "FlaxBeitModel"), ("bert", "FlaxBertModel"), ("big_bird", "FlaxBigBirdModel"), ("blenderbot", "FlaxBlenderbotModel"), ("blenderbot-small", "FlaxBlenderbotSmallModel"), ("clip", "FlaxCLIPModel"), ("distilbert", "FlaxDistilBertModel"), ("electra", "FlaxElectraModel"), ("gpt-sw3", "FlaxGPT2Model"), ("gpt2", "FlaxGPT2Model"), ("gpt_neo", "FlaxGPTNeoModel"), ("gptj", "FlaxGPTJModel"), ("longt5", "FlaxLongT5Model"), ("marian", "FlaxMarianModel"), ("mbart", "FlaxMBartModel"), ("mt5", "FlaxMT5Model"), ("opt", "FlaxOPTModel"), ("pegasus", "FlaxPegasusModel"), ("regnet", "FlaxRegNetModel"), ("resnet", "FlaxResNetModel"), ("roberta", "FlaxRobertaModel"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"), ("roformer", "FlaxRoFormerModel"), ("t5", "FlaxT5Model"), ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"), ("vit", "FlaxViTModel"), ("wav2vec2", "FlaxWav2Vec2Model"), ("whisper", "FlaxWhisperModel"), ("xglm", "FlaxXGLMModel"), ("xlm-roberta", "FlaxXLMRobertaModel"), ] ) __UpperCAmelCase = OrderedDict( [ # Model for pre-training mapping ("albert", "FlaxAlbertForPreTraining"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForPreTraining"), ("big_bird", "FlaxBigBirdForPreTraining"), ("electra", "FlaxElectraForPreTraining"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("t5", "FlaxT5ForConditionalGeneration"), ("wav2vec2", "FlaxWav2Vec2ForPreTraining"), ("whisper", "FlaxWhisperForConditionalGeneration"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) __UpperCAmelCase = OrderedDict( [ # Model for Masked LM mapping ("albert", "FlaxAlbertForMaskedLM"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForMaskedLM"), ("big_bird", "FlaxBigBirdForMaskedLM"), ("distilbert", "FlaxDistilBertForMaskedLM"), ("electra", "FlaxElectraForMaskedLM"), ("mbart", "FlaxMBartForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) __UpperCAmelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("bart", "FlaxBartForConditionalGeneration"), ("blenderbot", "FlaxBlenderbotForConditionalGeneration"), ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"), ("encoder-decoder", "FlaxEncoderDecoderModel"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("marian", "FlaxMarianMTModel"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("pegasus", "FlaxPegasusForConditionalGeneration"), ("t5", "FlaxT5ForConditionalGeneration"), ] ) __UpperCAmelCase = OrderedDict( [ # Model for Image-classsification ("beit", "FlaxBeitForImageClassification"), ("regnet", "FlaxRegNetForImageClassification"), ("resnet", "FlaxResNetForImageClassification"), ("vit", "FlaxViTForImageClassification"), ] ) __UpperCAmelCase = OrderedDict( [ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"), ] ) __UpperCAmelCase = OrderedDict( [ # Model for Causal LM mapping ("bart", "FlaxBartForCausalLM"), ("bert", "FlaxBertForCausalLM"), ("big_bird", "FlaxBigBirdForCausalLM"), ("electra", "FlaxElectraForCausalLM"), ("gpt-sw3", "FlaxGPT2LMHeadModel"), ("gpt2", "FlaxGPT2LMHeadModel"), ("gpt_neo", "FlaxGPTNeoForCausalLM"), ("gptj", "FlaxGPTJForCausalLM"), ("opt", "FlaxOPTForCausalLM"), ("roberta", "FlaxRobertaForCausalLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"), ("xglm", "FlaxXGLMForCausalLM"), ("xlm-roberta", "FlaxXLMRobertaForCausalLM"), ] ) __UpperCAmelCase = OrderedDict( [ # Model for Sequence Classification mapping ("albert", "FlaxAlbertForSequenceClassification"), ("bart", "FlaxBartForSequenceClassification"), ("bert", "FlaxBertForSequenceClassification"), ("big_bird", "FlaxBigBirdForSequenceClassification"), ("distilbert", "FlaxDistilBertForSequenceClassification"), ("electra", "FlaxElectraForSequenceClassification"), ("mbart", "FlaxMBartForSequenceClassification"), ("roberta", "FlaxRobertaForSequenceClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"), ("roformer", "FlaxRoFormerForSequenceClassification"), ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"), ] ) __UpperCAmelCase = OrderedDict( [ # Model for Question Answering mapping ("albert", "FlaxAlbertForQuestionAnswering"), ("bart", "FlaxBartForQuestionAnswering"), ("bert", "FlaxBertForQuestionAnswering"), ("big_bird", "FlaxBigBirdForQuestionAnswering"), ("distilbert", "FlaxDistilBertForQuestionAnswering"), ("electra", "FlaxElectraForQuestionAnswering"), ("mbart", "FlaxMBartForQuestionAnswering"), ("roberta", "FlaxRobertaForQuestionAnswering"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"), ("roformer", "FlaxRoFormerForQuestionAnswering"), ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"), ] ) __UpperCAmelCase = OrderedDict( [ # Model for Token Classification mapping ("albert", "FlaxAlbertForTokenClassification"), ("bert", "FlaxBertForTokenClassification"), ("big_bird", "FlaxBigBirdForTokenClassification"), ("distilbert", "FlaxDistilBertForTokenClassification"), ("electra", "FlaxElectraForTokenClassification"), ("roberta", "FlaxRobertaForTokenClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"), ("roformer", "FlaxRoFormerForTokenClassification"), ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"), ] ) __UpperCAmelCase = OrderedDict( [ # Model for Multiple Choice mapping ("albert", "FlaxAlbertForMultipleChoice"), ("bert", "FlaxBertForMultipleChoice"), ("big_bird", "FlaxBigBirdForMultipleChoice"), ("distilbert", "FlaxDistilBertForMultipleChoice"), ("electra", "FlaxElectraForMultipleChoice"), ("roberta", "FlaxRobertaForMultipleChoice"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"), ("roformer", "FlaxRoFormerForMultipleChoice"), ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"), ] ) __UpperCAmelCase = OrderedDict( [ ("bert", "FlaxBertForNextSentencePrediction"), ] ) __UpperCAmelCase = OrderedDict( [ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"), ("whisper", "FlaxWhisperForConditionalGeneration"), ] ) __UpperCAmelCase = OrderedDict( [ ("whisper", "FlaxWhisperForAudioClassification"), ] ) __UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) __UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) __UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) __UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) __UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) __UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) __UpperCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) __UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) __UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) __UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) __UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) __UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) __UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) __UpperCAmelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_MAPPING __UpperCAmelCase = auto_class_update(FlaxAutoModel) class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING __UpperCAmelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING __UpperCAmelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING __UpperCAmelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __UpperCAmelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __UpperCAmelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING __UpperCAmelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING __UpperCAmelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING __UpperCAmelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING __UpperCAmelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING __UpperCAmelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING __UpperCAmelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling") class SCREAMING_SNAKE_CASE ( _BaseAutoModelClass ): '''simple docstring''' __UpperCamelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING __UpperCAmelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling" )
692
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = tempfile.mkdtemp() snake_case: Optional[Any] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '的', '价', '格', '是', '15', '便', 'alex', '##andra', ',', '。', '-', 't', 'shirt', ] snake_case: Optional[Any] = 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] ) ) snake_case: Optional[int] = { 'do_resize': True, 'size': {'height': 2_24, 'width': 2_24}, 'do_center_crop': True, 'crop_size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], 'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], 'do_convert_rgb': True, } snake_case: Union[str, Any] = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] snake_case: Tuple = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_tokenizer() snake_case: Union[str, Any] = self.get_rust_tokenizer() snake_case: Union[str, Any] = self.get_image_processor() snake_case: List[str] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) snake_case: List[str] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) snake_case: Any = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) snake_case: Optional[int] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case: Optional[int] = self.get_tokenizer(cls_token='(CLS)' , sep_token='(SEP)' ) snake_case: Union[str, Any] = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='(CLS)' , sep_token='(SEP)' , do_normalize=SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.get_image_processor() snake_case: Tuple = self.get_tokenizer() snake_case: Optional[Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.prepare_image_inputs() snake_case: List[Any] = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) snake_case: Dict = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_image_processor() snake_case: Optional[int] = self.get_tokenizer() snake_case: List[Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = 'Alexandra,T-shirt的价格是15便士。' snake_case: Union[str, Any] = processor(text=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer(SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_image_processor() snake_case: Dict = self.get_tokenizer() snake_case: Optional[int] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Dict = 'Alexandra,T-shirt的价格是15便士。' snake_case: Tuple = self.prepare_image_inputs() snake_case: Any = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.get_image_processor() snake_case: str = self.get_tokenizer() snake_case: Union[str, Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] snake_case: int = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_image_processor() snake_case: Dict = self.get_tokenizer() snake_case: Optional[int] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = 'Alexandra,T-shirt的价格是15便士。' snake_case: List[Any] = self.prepare_image_inputs() snake_case: Dict = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
692
1
'''simple docstring''' from __future__ import annotations __UpperCAmelCase = "#" class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self ): '''simple docstring''' snake_case: dict = {} def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: str = self._trie for char in text: if char not in trie: snake_case: Optional[int] = {} snake_case: Any = trie[char] snake_case: Optional[Any] = True def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: str = self._trie for char in prefix: if char in trie: snake_case: int = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[Any] = [] for c, v in d.items(): snake_case: Union[str, Any] = [' '] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) __UpperCAmelCase = Trie() __UpperCAmelCase = ("depart", "detergent", "daring", "dog", "deer", "deal") for word in words: trie.insert_word(word) def lowerCAmelCase_ ( __A : str ): '''simple docstring''' snake_case: List[str] = trie.find_word(__A ) return tuple(string + word for word in suffixes ) def lowerCAmelCase_ ( ): '''simple docstring''' print(autocomplete_using_trie('de' ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
692
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "microsoft/swinv2-tiny-patch4-window8-256": ( "https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json" ), } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = "swinv2" __UpperCamelCase = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , SCREAMING_SNAKE_CASE__=2_24 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=96 , SCREAMING_SNAKE_CASE__=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE__=[3, 6, 12, 24] , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=4.0 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=32 , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case: int = image_size snake_case: Union[str, Any] = patch_size snake_case: List[str] = num_channels snake_case: Tuple = embed_dim snake_case: str = depths snake_case: Any = len(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = num_heads snake_case: Optional[int] = window_size snake_case: Any = mlp_ratio snake_case: Optional[int] = qkv_bias snake_case: Union[str, Any] = hidden_dropout_prob snake_case: List[str] = attention_probs_dropout_prob snake_case: Dict = drop_path_rate snake_case: List[str] = hidden_act snake_case: int = use_absolute_embeddings snake_case: Any = layer_norm_eps snake_case: Dict = initializer_range snake_case: List[Any] = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model snake_case: Tuple = int(embed_dim * 2 ** (len(SCREAMING_SNAKE_CASE__ ) - 1) ) snake_case: Union[str, Any] = (0, 0, 0, 0)
692
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import is_flaky, 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 DonutImageProcessor class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=18 , SCREAMING_SNAKE_CASE__=30 , SCREAMING_SNAKE_CASE__=4_00 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__=[0.5, 0.5, 0.5] , ): '''simple docstring''' snake_case: Optional[int] = parent snake_case: Union[str, Any] = batch_size snake_case: List[str] = num_channels snake_case: str = image_size snake_case: Union[str, Any] = min_resolution snake_case: Dict = max_resolution snake_case: List[Any] = do_resize snake_case: Dict = size if size is not None else {'height': 18, 'width': 20} snake_case: List[str] = do_thumbnail snake_case: Optional[int] = do_align_axis snake_case: Union[str, Any] = do_pad snake_case: Dict = do_normalize snake_case: Tuple = image_mean snake_case: str = image_std def _UpperCamelCase ( self ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = DonutImageProcessor if is_vision_available() else None def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = DonutImageProcessingTester(self ) @property def _UpperCamelCase ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_thumbnail' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_align_long_axis' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_pad' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 20} ) snake_case: Any = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) # Previous config had dimensions in (width, height) order snake_case: Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) ) self.assertEqual(image_processor.size , {'height': 84, 'width': 42} ) def _UpperCamelCase ( self ): '''simple docstring''' pass @is_flaky() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case: Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input 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(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) @is_flaky() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case: List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input snake_case: Dict = 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(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) @is_flaky() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: 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=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input snake_case: List[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched snake_case: Optional[int] = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , )
692
'''simple docstring''' import os import sys import unittest __UpperCAmelCase = 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_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __UpperCAmelCase = os.path.join(git_repo_path, "src", "transformers") __UpperCAmelCase = "\n{0} = None\n" __UpperCAmelCase = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n" __UpperCAmelCase = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n" class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = find_backend(' _import_structure["models.albert"].append("AlbertTokenizerFast")' ) self.assertIsNone(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = find_backend(' if not is_tokenizers_available():' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'tokenizers' ) snake_case: List[Any] = find_backend(' if not is_tensorflow_text_available():' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'tensorflow_text' ) snake_case: int = find_backend(' if not (is_sentencepiece_available() and is_tokenizers_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tokenizers' ) snake_case: Optional[Any] = find_backend( ' if not (is_sentencepiece_available() and is_tensorflow_text_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tensorflow_text' ) snake_case: Dict = find_backend( ' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tokenizers_and_vision' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('torch' , SCREAMING_SNAKE_CASE__ ) self.assertIn('tensorflow_text' , SCREAMING_SNAKE_CASE__ ) self.assertIn('sentencepiece_and_tokenizers' , SCREAMING_SNAKE_CASE__ ) # Likewise, we can't assert on the exact content of a key self.assertIn('BertModel' , objects['torch'] ) self.assertIn('TFBertModel' , objects['tf'] ) self.assertIn('FlaxBertModel' , objects['flax'] ) self.assertIn('BertModel' , objects['torch'] ) self.assertIn('TFBertTokenizer' , objects['tensorflow_text'] ) self.assertIn('convert_slow_tokenizer' , objects['sentencepiece_and_tokenizers'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = create_dummy_object('CONSTANT' , '\'torch\'' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , '\nCONSTANT = None\n' ) snake_case: Any = create_dummy_object('function' , '\'torch\'' ) self.assertEqual( SCREAMING_SNAKE_CASE__ , '\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n' ) snake_case: Optional[int] = '\nclass FakeClass(metaclass=DummyObject):\n _backends = \'torch\'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, \'torch\')\n' snake_case: Tuple = create_dummy_object('FakeClass' , '\'torch\'' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = ["torch"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, ["torch"])\n' snake_case: Optional[int] = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} ) self.assertEqual(dummy_files['torch'] , SCREAMING_SNAKE_CASE__ )
692
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "microsoft/trocr-base-handwritten": ( "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = "trocr" __UpperCamelCase = ["past_key_values"] __UpperCamelCase = { "num_attention_heads": "decoder_attention_heads", "hidden_size": "d_model", "num_hidden_layers": "decoder_layers", } def __init__( self , SCREAMING_SNAKE_CASE__=5_02_65 , SCREAMING_SNAKE_CASE__=10_24 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=40_96 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=5_12 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=2 , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: str = vocab_size snake_case: Dict = d_model snake_case: Optional[int] = decoder_layers snake_case: Union[str, Any] = decoder_attention_heads snake_case: int = decoder_ffn_dim snake_case: Tuple = activation_function snake_case: int = max_position_embeddings snake_case: Any = dropout snake_case: List[str] = attention_dropout snake_case: Optional[int] = activation_dropout snake_case: Dict = init_std snake_case: Optional[Any] = decoder_layerdrop snake_case: Tuple = use_cache snake_case: Tuple = scale_embedding snake_case: List[Any] = use_learned_position_embeddings snake_case: List[Any] = layernorm_embedding super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
692
'''simple docstring''' import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig __UpperCAmelCase = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = question_encoder snake_case: Union[str, Any] = generator snake_case: Optional[int] = self.question_encoder def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if os.path.isfile(SCREAMING_SNAKE_CASE__ ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , 'question_encoder_tokenizer' ) snake_case: Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , 'generator_tokenizer' ) self.question_encoder.save_pretrained(SCREAMING_SNAKE_CASE__ ) self.generator.save_pretrained(SCREAMING_SNAKE_CASE__ ) @classmethod def _UpperCamelCase ( cls , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer snake_case: int = kwargs.pop('config' , SCREAMING_SNAKE_CASE__ ) if config is None: snake_case: str = RagConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE__ , config=config.question_encoder , subfolder='question_encoder_tokenizer' ) snake_case: Dict = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE__ , config=config.generator , subfolder='generator_tokenizer' ) return cls(question_encoder=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) def __call__( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.current_tokenizer(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.generator.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.generator.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.question_encoder def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.generator def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "longest" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = True , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' warnings.warn( '`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ' 'regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ' 'context manager to prepare your targets. See the documentation of your specific tokenizer for more ' 'details' , SCREAMING_SNAKE_CASE__ , ) if max_length is None: snake_case: Optional[Any] = self.current_tokenizer.model_max_length snake_case: int = self( SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: snake_case: Any = self.current_tokenizer.model_max_length snake_case: List[str] = self( text_target=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case: Dict = labels['input_ids'] return model_inputs
692
1
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "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": "lm_head", "mask_emb": "masked_spec_embed", } __UpperCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def lowerCAmelCase_ ( __A : Any , __A : Optional[Any] , __A : Union[str, Any] , __A : int , __A : Optional[int] ): '''simple docstring''' for attribute in key.split('.' ): snake_case: List[str] = getattr(__A , __A ) if weight_type is not None: snake_case: Optional[int] = getattr(__A , __A ).shape else: snake_case: Optional[int] = 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": snake_case: Optional[int] = value elif weight_type == "weight_g": snake_case: List[str] = value elif weight_type == "weight_v": snake_case: Dict = value elif weight_type == "bias": snake_case: Optional[Any] = value else: snake_case: int = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def lowerCAmelCase_ ( __A : List[Any] , __A : List[str] ): '''simple docstring''' snake_case: List[Any] = [] snake_case: List[Any] = fairseq_model.state_dict() snake_case: Union[str, Any] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight snake_case: Dict = None for name, value in fairseq_dict.items(): snake_case: Tuple = False if "conv_layers" in name: load_conv_layer( __A , __A , __A , __A , hf_model.config.feat_extract_norm == 'group' , ) snake_case: List[Any] = True elif name.split('.' )[0] == "proj": snake_case: List[Any] = fairseq_model.proj snake_case: int = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: snake_case: int = True if "*" in mapped_key: snake_case: List[str] = name.split(__A )[0].split('.' )[-2] snake_case: Dict = mapped_key.replace('*' , __A ) if "weight_g" in name: snake_case: Tuple = 'weight_g' elif "weight_v" in name: snake_case: int = 'weight_v' elif "bias" in name: snake_case: Tuple = 'bias' elif "weight" in name: snake_case: List[Any] = 'weight' else: snake_case: Any = None set_recursively(__A , __A , __A , __A , __A ) continue if not is_used: unused_weights.append(__A ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCAmelCase_ ( __A : List[str] , __A : List[Any] , __A : int , __A : Optional[Any] , __A : Optional[int] ): '''simple docstring''' snake_case: int = full_name.split('conv_layers.' )[-1] snake_case: Tuple = name.split('.' ) snake_case: Any = int(items[0] ) snake_case: Optional[int] = 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.""" ) snake_case: Tuple = 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.""" ) snake_case: int = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) snake_case: Any = 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.""" ) snake_case: str = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__A ) def lowerCAmelCase_ ( __A : Dict ): '''simple docstring''' snake_case , snake_case: List[Any] = emb.weight.shape snake_case: Optional[int] = nn.Linear(__A , __A , bias=__A ) snake_case: Any = emb.weight.data return lin_layer def lowerCAmelCase_ ( __A : Optional[int] ): '''simple docstring''' with open(__A , 'r' , encoding='utf-8' ) as f: snake_case: List[Any] = f.readlines() snake_case: Any = [line.split(' ' )[0] for line in lines] snake_case: int = len(__A ) snake_case: Dict = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(__A , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCAmelCase_ ( __A : Optional[Any] , __A : Union[str, Any] , __A : Dict , __A : Any , __A : List[Any] , __A : int , __A : str , ): '''simple docstring''' snake_case: Union[str, Any] = WavaVecaConfig.from_pretrained(__A ) snake_case: str = SpeechaTextaConfig.from_pretrained( __A , vocab_size=__A , decoder_layers=__A , do_stable_layer_norm=__A ) snake_case: List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=__A , return_attention_mask=__A , ) snake_case , snake_case , snake_case: List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) snake_case: List[Any] = model[0].eval() # set weights for wav2vec2 encoder snake_case: Optional[Any] = WavaVecaModel(__A ) snake_case: Any = recursively_load_weights_wavaveca(model.encoder , __A ) snake_case: Union[str, Any] = SpeechaTextaForCausalLM(__A ) snake_case , snake_case: Optional[Any] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__A ) # set output linear layer unexpected_keys.remove('embed_out' ) snake_case: str = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) snake_case: int = SpeechEncoderDecoderModel(encoder=__A , decoder=__A ) snake_case: List[Any] = False # add projection layer snake_case: Union[str, Any] = nn.Parameter(projection_layer.weight ) snake_case: Union[str, Any] = nn.Parameter(projection_layer.bias ) snake_case: List[Any] = create_vocab_dict(__A ) with open(os.path.join(__A , 'vocab.json' ) , 'w' ) as fp: json.dump(__A , __A ) snake_case: Union[str, Any] = SpeechaTextaTokenizer(os.path.join(__A , 'vocab.json' ) ) tokenizer.save_pretrained(__A ) snake_case: Tuple = hf_wavavec.config.to_dict() snake_case: int = tokenizer.pad_token_id snake_case: Dict = tokenizer.bos_token_id snake_case: Optional[int] = tokenizer.eos_token_id snake_case: Dict = 'speech_to_text_2' snake_case: Optional[Any] = 'wav2vec2' snake_case: Tuple = SpeechEncoderDecoderConfig.from_dict(__A ) hf_wavavec.save_pretrained(__A ) feature_extractor.save_pretrained(__A ) if __name__ == "__main__": __UpperCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") __UpperCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
692
'''simple docstring''' 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_ ( __A : Tuple ): '''simple docstring''' assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ): '''simple docstring''' assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Union[str, Any] = 'mock-s3-bucket' snake_case: int = f"""s3://{mock_bucket}""" snake_case: Any = extract_path_from_uri(__A ) assert dataset_path.startswith('s3://' ) is False snake_case: Union[str, Any] = './local/path' snake_case: Union[str, Any] = extract_path_from_uri(__A ) assert dataset_path == new_dataset_path def lowerCAmelCase_ ( __A : Any ): '''simple docstring''' snake_case: List[str] = is_remote_filesystem(__A ) assert is_remote is True snake_case: int = fsspec.filesystem('file' ) snake_case: int = is_remote_filesystem(__A ) assert is_remote is False @pytest.mark.parametrize('compression_fs_class' , __A ) def lowerCAmelCase_ ( __A : Optional[int] , __A : int , __A : str , __A : Optional[Any] , __A : List[str] , __A : Optional[Any] , __A : Optional[int] ): '''simple docstring''' snake_case: Optional[Any] = {'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_file, 'bz2': bza_file, 'lz4': lza_file} snake_case: Optional[int] = input_paths[compression_fs_class.protocol] if input_path is None: snake_case: str = 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(__A ) snake_case: List[str] = fsspec.filesystem(compression_fs_class.protocol , fo=__A ) assert isinstance(__A , __A ) snake_case: Any = os.path.basename(__A ) snake_case: int = expected_filename[: expected_filename.rindex('.' )] assert fs.glob('*' ) == [expected_filename] with fs.open(__A , 'r' , encoding='utf-8' ) as f, open(__A , encoding='utf-8' ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize('protocol' , ['zip', 'gzip'] ) def lowerCAmelCase_ ( __A : Any , __A : int , __A : int ): '''simple docstring''' snake_case: List[str] = {'zip': zip_jsonl_path, 'gzip': jsonl_gz_path} snake_case: str = compressed_file_paths[protocol] snake_case: Dict = 'dataset.jsonl' snake_case: Optional[Any] = f"""{protocol}://{member_file_path}::{compressed_file_path}""" snake_case , *snake_case: List[Any] = fsspec.get_fs_token_paths(__A ) assert fs.isfile(__A ) assert not fs.isfile('non_existing_' + member_file_path ) @pytest.mark.integration def lowerCAmelCase_ ( __A : Optional[Any] , __A : Union[str, Any] , __A : Union[str, Any] , __A : List[Any] ): '''simple docstring''' snake_case: Tuple = hf_api.dataset_info(__A , token=__A ) snake_case: List[str] = HfFileSystem(repo_info=__A , token=__A ) assert sorted(hffs.glob('*' ) ) == [".gitattributes", "data"] assert hffs.isdir('data' ) assert hffs.isfile('.gitattributes' ) and hffs.isfile('data/text_data.txt' ) with open(__A ) as f: assert hffs.open('data/text_data.txt' , 'r' ).read() == f.read() def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Union[str, Any] = 'bz2' # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(__A , __A , clobber=__A ) with pytest.warns(__A ) as warning_info: importlib.reload(datasets.filesystems ) assert len(__A ) == 1 assert ( str(warning_info[0].message ) == f"""A filesystem protocol was already set for {protocol} and will be overwritten.""" )
692
1
'''simple docstring''' 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 __UpperCAmelCase = { "169M": 12, "430M": 24, "1B5": 24, "3B": 32, "7B": 32, "14B": 40, } __UpperCAmelCase = { "169M": 768, "430M": 1_024, "1B5": 2_048, "3B": 2_560, "7B": 4_096, "14B": 5_120, } def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' snake_case: List[Any] = list(state_dict.keys() ) for name in state_dict_keys: snake_case: str = state_dict.pop(__A ) # emb -> embedding if name.startswith('emb.' ): snake_case: Dict = name.replace('emb.' , 'embeddings.' ) # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0' ): snake_case: Union[str, Any] = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln' ) # att -> attention snake_case: Union[str, Any] = re.sub(r'blocks\.(\d+)\.att' , r'blocks.\1.attention' , __A ) # ffn -> feed_forward snake_case: Dict = re.sub(r'blocks\.(\d+)\.ffn' , r'blocks.\1.feed_forward' , __A ) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k' ): snake_case: Union[str, Any] = name.replace('.time_mix_k' , '.time_mix_key' ) # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v' ): snake_case: List[Any] = name.replace('.time_mix_v' , '.time_mix_value' ) # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r' ): snake_case: List[Any] = name.replace('.time_mix_r' , '.time_mix_receptance' ) if name != "head.weight": snake_case: Union[str, Any] = 'rwkv.' + name snake_case: Optional[int] = weight return state_dict def lowerCAmelCase_ ( __A : Tuple , __A : Union[str, Any] , __A : Optional[Any] , __A : Optional[Any]=None , __A : str=None , __A : int=False , __A : Any=None ): '''simple docstring''' if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.' ) snake_case: Union[str, Any] = 5_02_77 snake_case: List[str] = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b' ) else: snake_case: str = PreTrainedTokenizerFast(tokenizer_file=__A ) snake_case: Optional[int] = len(__A ) tokenizer.save_pretrained(__A ) # 2. Build the config snake_case: int = 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: snake_case: List[str] = 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}.""" ) snake_case: str = RwkvConfig( vocab_size=__A , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(__A ) # 3. Download model file then convert state_dict snake_case: int = hf_hub_download(__A , __A ) snake_case: Any = torch.load(__A , map_location='cpu' ) snake_case: str = convert_state_dict(__A ) # 4. Split in shards and save snake_case , snake_case: Optional[Any] = shard_checkpoint(__A ) for shard_file, shard in shards.items(): torch.save(__A , os.path.join(__A , __A ) ) if index is not None: snake_case: int = os.path.join(__A , __A ) # Save the index as well with open(__A , 'w' , encoding='utf-8' ) as f: snake_case: List[str] = json.dumps(__A , indent=2 , sort_keys=__A ) + '\n' f.write(__A ) # 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.' ) snake_case: Any = list(shards.keys() ) del state_dict del shards gc.collect() for shard_file in shard_files: snake_case: Optional[Any] = torch.load(os.path.join(__A , __A ) ) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(__A , __A ) ) 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.' ) snake_case: str = AutoModelForCausalLM.from_pretrained(__A ) model.push_to_hub(__A , max_shard_size='2GB' ) tokenizer.push_to_hub(__A ) if __name__ == "__main__": __UpperCAmelCase = 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.", ) __UpperCAmelCase = 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, )
692
'''simple docstring''' import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.17.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") __UpperCAmelCase = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = field( default="tab_fact" , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) __UpperCamelCase = field( default="tab_fact" , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} , ) __UpperCamelCase = field( default=1024 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "A csv or a json file containing the training data."} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "A csv or a json file containing the validation data."} ) __UpperCamelCase = field(default=snake_case , metadata={"help": "A csv or a json file containing the test data."} ) def _UpperCamelCase ( self ): '''simple docstring''' if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError('Need either a GLUE task, a training/validation file or a dataset name.' ) else: snake_case: str = self.train_file.split('.' )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." snake_case: Optional[Any] = self.validation_file.split('.' )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = field( default=snake_case , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) __UpperCamelCase = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case , snake_case , snake_case: Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case , snake_case , snake_case: str = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) snake_case: Tuple = training_args.get_process_log_level() logger.setLevel(__A ) datasets.utils.logging.set_verbosity(__A ) transformers.utils.logging.set_verbosity(__A ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. snake_case: Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case: List[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. snake_case: int = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. snake_case: Optional[int] = {'train': data_args.train_file, 'validation': data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: snake_case: Tuple = data_args.train_file.split('.' )[-1] snake_case: Union[str, Any] = data_args.test_file.split('.' )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." snake_case: Union[str, Any] = data_args.test_file else: raise ValueError('Need either a GLUE task or a test file for `do_predict`.' ) for key in data_files.keys(): logger.info(f"""load a local file for {key}: {data_files[key]}""" ) if data_args.train_file.endswith('.csv' ): # Loading a dataset from local csv files snake_case: List[Any] = load_dataset('csv' , data_files=__A , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files snake_case: Optional[Any] = load_dataset('json' , data_files=__A , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels snake_case: Tuple = raw_datasets['train'].features['label'].names snake_case: List[str] = len(__A ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case: Tuple = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer snake_case: List[str] = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=__A , ) snake_case: Union[str, Any] = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=__A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: snake_case: int = 'max_length' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch snake_case: Union[str, Any] = False # Some models have set the order of the labels to use, so let's make sure we do use it. snake_case: Optional[Any] = {'Refused': 0, 'Entailed': 1} snake_case: List[Any] = {0: 'Refused', 1: 'Entailed'} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) snake_case: List[str] = min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(__A : Any ): # Tokenize the texts def _convert_table_text_to_pandas(__A : Dict ): snake_case: str = [_table_row.split('#' ) for _table_row in _table_text.strip('\n' ).split('\n' )] snake_case: List[str] = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd snake_case: str = examples['statement'] snake_case: int = list(map(_convert_table_text_to_pandas , examples['table_text'] ) ) snake_case: List[Any] = tokenizer(__A , __A , padding=__A , max_length=__A , truncation=__A ) snake_case: List[Any] = examples['label'] return result with training_args.main_process_first(desc='dataset map pre-processing' ): snake_case: int = raw_datasets.map( __A , batched=__A , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on dataset' , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError('--do_train requires a train dataset' ) snake_case: List[str] = raw_datasets['train'] if data_args.max_train_samples is not None: snake_case: Tuple = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError('--do_eval requires a validation dataset' ) snake_case: Any = raw_datasets['validation'] if data_args.max_eval_samples is not None: snake_case: Optional[int] = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError('--do_predict requires a test dataset' ) snake_case: str = raw_datasets['test'] if data_args.max_predict_samples is not None: snake_case: List[str] = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(__A ) ) , 3 ): logger.info(f"""Sample {index} of the training set: {train_dataset[index]}.""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__A : EvalPrediction ): snake_case: int = p.predictions[0] if isinstance(p.predictions , __A ) else p.predictions snake_case: List[str] = np.argmax(__A , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: snake_case: str = default_data_collator elif training_args.fpaa: snake_case: List[str] = DataCollatorWithPadding(__A , pad_to_multiple_of=8 ) else: snake_case: List[Any] = None # Initialize our Trainer snake_case: List[str] = Trainer( model=__A , args=__A , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__A , tokenizer=__A , data_collator=__A , ) # Training if training_args.do_train: snake_case: Optional[int] = None if training_args.resume_from_checkpoint is not None: snake_case: str = training_args.resume_from_checkpoint elif last_checkpoint is not None: snake_case: Optional[Any] = last_checkpoint snake_case: Union[str, Any] = trainer.train(resume_from_checkpoint=__A ) snake_case: List[Any] = train_result.metrics snake_case: List[Any] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__A ) ) snake_case: Optional[Any] = min(__A , len(__A ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('train' , __A ) trainer.save_metrics('train' , __A ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) snake_case: Dict = trainer.evaluate(eval_dataset=__A ) snake_case: Optional[int] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__A ) snake_case: Dict = min(__A , len(__A ) ) trainer.log_metrics('eval' , __A ) trainer.save_metrics('eval' , __A ) if training_args.do_predict: logger.info('*** Predict ***' ) # Removing the `label` columns because it contains -1 and Trainer won't like that. snake_case: Optional[int] = predict_dataset.remove_columns('label' ) snake_case: str = trainer.predict(__A , metric_key_prefix='predict' ).predictions snake_case: Any = np.argmax(__A , axis=1 ) snake_case: int = os.path.join(training_args.output_dir , 'predict_results_tabfact.txt' ) if trainer.is_world_process_zero(): with open(__A , 'w' ) as writer: logger.info('***** Predict Results *****' ) writer.write('index\tprediction\n' ) for index, item in enumerate(__A ): snake_case: int = label_list[item] writer.write(f"""{index}\t{item}\n""" ) snake_case: Optional[int] = {'finetuned_from': model_args.model_name_or_path, 'tasks': 'text-classification'} if training_args.push_to_hub: trainer.push_to_hub(**__A ) else: trainer.create_model_card(**__A ) def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' main() if __name__ == "__main__": main()
692
1
'''simple docstring''' import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=13 , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=False , 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__=5_12 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=None , ): '''simple docstring''' snake_case: List[str] = parent snake_case: int = batch_size snake_case: Any = seq_length snake_case: Optional[int] = is_training snake_case: List[Any] = use_input_mask snake_case: Union[str, Any] = use_token_type_ids snake_case: str = use_labels snake_case: Optional[int] = vocab_size snake_case: Tuple = hidden_size snake_case: Dict = num_hidden_layers snake_case: Optional[Any] = num_attention_heads snake_case: Optional[Any] = intermediate_size snake_case: Optional[int] = hidden_act snake_case: int = hidden_dropout_prob snake_case: List[str] = attention_probs_dropout_prob snake_case: Optional[int] = max_position_embeddings snake_case: List[str] = type_vocab_size snake_case: Union[str, Any] = type_sequence_label_size snake_case: Dict = initializer_range snake_case: Dict = num_labels snake_case: Any = num_choices snake_case: str = scope def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case: List[str] = None if self.use_input_mask: snake_case: Dict = random_attention_mask([self.batch_size, self.seq_length] ) snake_case: Optional[int] = None if self.use_token_type_ids: snake_case: Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case: int = None snake_case: Dict = None snake_case: List[Any] = None if self.use_labels: snake_case: Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case: Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case: Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) snake_case: Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self ): '''simple docstring''' return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[str] = BioGptModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: List[Any] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: List[str] = BioGptForCausalLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Tuple = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[str] = BioGptModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() # create attention mask snake_case: Any = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.seq_length // 2 snake_case: List[str] = 0 # first forward pass snake_case , snake_case: Any = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ).to_tuple() # create hypothetical next token and extent to next_input_ids snake_case: Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids snake_case: Optional[int] = ids_tensor((1,) , SCREAMING_SNAKE_CASE__ ).item() + 1 snake_case: Optional[Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) snake_case: str = random_other_next_tokens # append to next input_ids and attn_mask snake_case: Any = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case: Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ )] , dim=1 , ) # get two different outputs snake_case: Optional[int] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ )['last_hidden_state'] snake_case: Optional[Any] = model(SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ )['last_hidden_state'] # select random slice snake_case: Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case: Any = output_from_no_past[:, -1, random_slice_idx].detach() snake_case: Optional[int] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = BioGptModel(config=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ).eval() snake_case: Union[str, Any] = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) # first forward pass snake_case: List[str] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) snake_case , snake_case: Dict = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids snake_case: Dict = ids_tensor((self.batch_size, 3) , config.vocab_size ) snake_case: int = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and snake_case: Any = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case: Optional[int] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) snake_case: Optional[int] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ )['last_hidden_state'] snake_case: Optional[int] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ )[ 'last_hidden_state' ] # select random slice snake_case: str = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case: Optional[int] = output_from_no_past[:, -3:, random_slice_idx].detach() snake_case: List[str] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1E-3 ) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ): '''simple docstring''' snake_case: str = BioGptForCausalLM(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() snake_case: Optional[Any] = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Any = BioGptModel(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.0_01 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[str] = self.num_labels snake_case: Any = BioGptForTokenClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Optional[Any] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.prepare_config_and_inputs() ( ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ): List[str] = config_and_inputs snake_case: int = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) __UpperCamelCase = (BioGptForCausalLM,) if is_torch_available() else () __UpperCamelCase = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = BioGptModelTester(self ) snake_case: Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def _UpperCamelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case: Optional[Any] = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*SCREAMING_SNAKE_CASE__ , gradient_checkpointing=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) snake_case: Optional[int] = 'left' # Define PAD Token = EOS Token = 50256 snake_case: Optional[Any] = tokenizer.eos_token snake_case: Optional[Any] = model.config.eos_token_id # use different length sentences to test batching snake_case: Tuple = [ 'Hello, my dog is a little', 'Today, I', ] snake_case: int = tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors='pt' , padding=SCREAMING_SNAKE_CASE__ ) snake_case: str = inputs['input_ids'].to(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = model.generate( input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=inputs['attention_mask'].to(SCREAMING_SNAKE_CASE__ ) , ) snake_case: Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = model.generate(input_ids=SCREAMING_SNAKE_CASE__ ) snake_case: int = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() snake_case: Tuple = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = model.generate(input_ids=SCREAMING_SNAKE_CASE__ , max_length=model.config.max_length - num_paddings ) snake_case: Union[str, Any] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [non_padded_sentence, padded_sentence] ) @slow def _UpperCamelCase ( self ): '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case: str = BioGptModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case: Dict = self.model_tester.prepare_config_and_inputs_for_common() snake_case: str = 3 snake_case: List[str] = input_dict['input_ids'] snake_case: Any = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) snake_case: Optional[Any] = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: int = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case: Dict = self.model_tester.prepare_config_and_inputs_for_common() snake_case: List[Any] = 3 snake_case: int = 'multi_label_classification' snake_case: Dict = input_dict['input_ids'] snake_case: List[Any] = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE__ ) snake_case: int = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) snake_case: int = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: str = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) snake_case: Any = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) snake_case: List[Any] = model(SCREAMING_SNAKE_CASE__ )[0] snake_case: List[str] = 4_23_84 snake_case: Any = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) snake_case: Dict = torch.tensor( [[[-9.52_36, -9.89_18, 10.45_57], [-11.04_69, -9.64_23, 8.10_22], [-8.86_64, -7.88_26, 5.53_25]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) snake_case: Optional[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(SCREAMING_SNAKE_CASE__ ) torch.manual_seed(0 ) snake_case: Optional[int] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(SCREAMING_SNAKE_CASE__ ) snake_case: int = model.generate( **SCREAMING_SNAKE_CASE__ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=SCREAMING_SNAKE_CASE__ , ) snake_case: str = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
692
'''simple docstring''' import math def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCAmelCase_ ( __A : float = 0.1 ): '''simple docstring''' snake_case: Optional[int] = 3 snake_case: int = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(__A ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available __UpperCAmelCase = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["MLukeTokenizer"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): __UpperCAmelCase = "pt" elif is_tf_available(): __UpperCAmelCase = "tf" else: __UpperCAmelCase = "jax" class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ByTaTokenizer __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: int = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _UpperCamelCase ( self ): '''simple docstring''' return ByTaTokenizer.from_pretrained('google/byt5-small' ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=20 , SCREAMING_SNAKE_CASE__=5 ): '''simple docstring''' snake_case: Optional[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): try: snake_case: Optional[Any] = tokenizer.decode([i] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) except UnicodeDecodeError: pass toks.append((i, tok) ) snake_case: List[str] = list(filter(lambda SCREAMING_SNAKE_CASE__ : re.match(r'^[ a-zA-Z]+$' , t[1] ) , SCREAMING_SNAKE_CASE__ ) ) snake_case: str = list(filter(lambda SCREAMING_SNAKE_CASE__ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) ) if max_length is not None and len(SCREAMING_SNAKE_CASE__ ) > max_length: snake_case: Union[str, Any] = 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: snake_case: Tuple = toks + toks # toks_str = [t[1] for t in toks] snake_case: Dict = [t[0] for t in toks] # Ensure consistency snake_case: int = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) if " " not in output_txt and len(SCREAMING_SNAKE_CASE__ ) > 1: snake_case: str = ( 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: snake_case: Tuple = ' ' + output_txt snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) return output_txt, output_ids def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: str = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) snake_case: List[Any] = tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: Union[str, Any] = 'Unicode €.' snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = [88, 1_13, 1_08, 1_02, 1_14, 1_03, 1_04, 35, 2_29, 1_33, 1_75, 49, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[str] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'Unicode €.</s>' ) snake_case: List[Any] = tokenizer('e è é ê ë' ) snake_case: Optional[Any] = [1_04, 35, 1_98, 1_71, 35, 1_98, 1_72, 35, 1_98, 1_73, 35, 1_98, 1_74, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.ta_base_tokenizer snake_case: Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off snake_case: Optional[int] = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 1, 0] # fmt: on snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if FRAMEWORK != "jax": snake_case: Optional[Any] = list(batch.input_ids.numpy()[0] ) else: snake_case: Dict = list(batch.input_ids.tolist()[0] ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.ta_base_tokenizer snake_case: List[str] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] snake_case: Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertIn('attention_mask' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_attention_mask' , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.ta_base_tokenizer snake_case: str = [ 'Summary of the text.', 'Another summary.', ] snake_case: Dict = tokenizer( text_target=SCREAMING_SNAKE_CASE__ , max_length=32 , padding='max_length' , truncation=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.ta_base_tokenizer snake_case: Optional[int] = ['A long paragraph for summarization. </s>'] snake_case: str = ['Summary of the text. </s>'] # fmt: off snake_case: str = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 35, 1] snake_case: Optional[int] = [86, 1_20, 1_12, 1_12, 1_00, 1_17, 1_24, 35, 1_14, 1_05, 35, 1_19, 1_07, 1_04, 35, 1_19, 1_04, 1_23, 1_19, 49, 35, 1] # fmt: on snake_case: List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ , text_target=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['input_ids'][0] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['labels'][0] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test snake_case: Optional[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: Union[str, Any] = tempfile.mkdtemp() snake_case: Dict = ' He is very happy, UNwant\u00E9d,running' snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Any = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: List[str] = tempfile.mkdtemp() snake_case: str = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) snake_case: List[str] = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) snake_case: int = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) snake_case: Union[str, Any] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: snake_case: Any = json.load(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: snake_case: str = json.load(SCREAMING_SNAKE_CASE__ ) snake_case: int = [F"""<extra_id_{i}>""" for i in range(1_25 )] snake_case: Optional[int] = added_tokens_extra_ids + [ 'an_additional_special_token' ] snake_case: str = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files snake_case: Dict = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained snake_case: Union[str, Any] = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=SCREAMING_SNAKE_CASE__ )] snake_case: Union[str, Any] = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.decode([2_55] ) == '' ) def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_tokenizers(fast=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Union[str, Any] = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] snake_case: List[str] = tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Optional[Any] = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] snake_case: Dict = 0 snake_case: List[Any] = tokenizer.convert_ids_to_tokens( SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) for attr in attributes_list: setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [] ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
692
1
'''simple docstring''' 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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = { 'task_specific_params': { 'summarization': {'length_penalty': 1.0, 'max_length': 1_28, 'min_length': 12, 'num_beams': 4}, 'summarization_cnn': {'length_penalty': 2.0, 'max_length': 1_42, 'min_length': 56, 'num_beams': 4}, 'summarization_xsum': {'length_penalty': 1.0, 'max_length': 62, 'min_length': 11, 'num_beams': 6}, } } snake_case: Union[str, Any] = { 'task_specific_params.summarization.length_penalty': 1.0, 'task_specific_params.summarization.max_length': 1_28, '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': 1_42, '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(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , x.transpose() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = np.random.randn(3 , 4 ) snake_case: Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(3 , 4 , 5 ) snake_case: Optional[int] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Dict = np.random.randn(3 , 4 , 5 ) snake_case: str = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Optional[int] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Optional[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) snake_case: Optional[int] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: str = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: List[str] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.squeeze(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: List[str] = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) snake_case: List[str] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: int = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = np.random.randn(1 , 3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Union[str, Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(1 , 3 , 4 ) snake_case: List[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Tuple = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Tuple = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Any = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Any = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = np.random.randn(3 , 4 ) snake_case: int = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.asarray(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) )
692
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = "layer_norm" , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__() snake_case: List[str] = only_cross_attention snake_case: Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero' snake_case: Tuple = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to""" F""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""" ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: snake_case: List[str] = AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: snake_case: str = AdaLayerNormZero(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: snake_case: int = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = Attention( query_dim=SCREAMING_SNAKE_CASE__ , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. snake_case: Tuple = ( AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) ) snake_case: Any = Attention( query_dim=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # is self-attn if encoder_hidden_states is none else: snake_case: int = None snake_case: Tuple = None # 3. Feed-forward snake_case: Union[str, Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = FeedForward(SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , activation_fn=SCREAMING_SNAKE_CASE__ , final_dropout=SCREAMING_SNAKE_CASE__ ) # let chunk size default to None snake_case: Any = None snake_case: Any = 0 def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = chunk_size snake_case: str = dim def _UpperCamelCase ( 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 , ): '''simple docstring''' if self.use_ada_layer_norm: snake_case: Optional[int] = self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: snake_case , snake_case , snake_case , snake_case , snake_case: int = self.norma( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=hidden_states.dtype ) else: snake_case: List[str] = self.norma(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = cross_attention_kwargs if cross_attention_kwargs is not None else {} snake_case: List[str] = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if self.use_ada_layer_norm_zero: snake_case: Tuple = gate_msa.unsqueeze(1 ) * attn_output snake_case: List[str] = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: snake_case: Dict = ( self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else self.norma(SCREAMING_SNAKE_CASE__ ) ) snake_case: Any = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case: List[str] = attn_output + hidden_states # 3. Feed-forward snake_case: str = self.norma(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: snake_case: str = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""" ) snake_case: List[str] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size snake_case: Optional[Any] = torch.cat( [self.ff(SCREAMING_SNAKE_CASE__ ) for hid_slice in norm_hidden_states.chunk(SCREAMING_SNAKE_CASE__ , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: snake_case: int = self.ff(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: snake_case: Union[str, Any] = gate_mlp.unsqueeze(1 ) * ff_output snake_case: Tuple = ff_output + hidden_states return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 4 , SCREAMING_SNAKE_CASE__ = 0.0 , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__() snake_case: int = int(dim * mult ) snake_case: Optional[Any] = dim_out if dim_out is not None else dim if activation_fn == "gelu": snake_case: int = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if activation_fn == "gelu-approximate": snake_case: Optional[Any] = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , approximate='tanh' ) elif activation_fn == "geglu": snake_case: List[Any] = GEGLU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif activation_fn == "geglu-approximate": snake_case: Optional[int] = ApproximateGELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Any = nn.ModuleList([] ) # project in self.net.append(SCREAMING_SNAKE_CASE__ ) # project dropout self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) # project out self.net.append(nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' for module in self.net: snake_case: Optional[int] = module(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "none" ): '''simple docstring''' super().__init__() snake_case: Optional[int] = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = approximate def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.proj(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = self.gelu(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = nn.Linear(SCREAMING_SNAKE_CASE__ , dim_out * 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case , snake_case: int = self.proj(SCREAMING_SNAKE_CASE__ ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = self.proj(SCREAMING_SNAKE_CASE__ ) return x * torch.sigmoid(1.7_02 * x ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Optional[Any] = nn.Embedding(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = nn.SiLU() snake_case: Union[str, Any] = nn.Linear(SCREAMING_SNAKE_CASE__ , embedding_dim * 2 ) snake_case: int = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ ) ) ) snake_case , snake_case: Dict = torch.chunk(SCREAMING_SNAKE_CASE__ , 2 ) snake_case: str = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale) + shift return x class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = CombinedTimestepLabelEmbeddings(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.SiLU() snake_case: Any = nn.Linear(SCREAMING_SNAKE_CASE__ , 6 * embedding_dim , bias=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ , eps=1E-6 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' snake_case: int = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=SCREAMING_SNAKE_CASE__ ) ) ) snake_case , snake_case , snake_case , snake_case , snake_case , snake_case: str = emb.chunk(6 , dim=1 ) snake_case: Dict = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 1E-5 ): '''simple docstring''' super().__init__() snake_case: str = num_groups snake_case: str = eps if act_fn is None: snake_case: Dict = None else: snake_case: List[str] = get_activation(SCREAMING_SNAKE_CASE__ ) snake_case: Any = nn.Linear(SCREAMING_SNAKE_CASE__ , out_dim * 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.act: snake_case: Optional[Any] = self.act(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.linear(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = emb[:, :, None, None] snake_case , snake_case: List[Any] = emb.chunk(2 , dim=1 ) snake_case: Any = F.group_norm(SCREAMING_SNAKE_CASE__ , self.num_groups , eps=self.eps ) snake_case: Optional[int] = x * (1 + scale) + shift return x
692
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 __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = "beit" def __init__( self , SCREAMING_SNAKE_CASE__=81_92 , SCREAMING_SNAKE_CASE__=7_68 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=30_72 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-12 , SCREAMING_SNAKE_CASE__=2_24 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=[3, 5, 7, 11] , SCREAMING_SNAKE_CASE__=[1, 2, 3, 6] , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=0.4 , SCREAMING_SNAKE_CASE__=2_56 , SCREAMING_SNAKE_CASE__=1 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=2_55 , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = vocab_size snake_case: int = hidden_size snake_case: int = num_hidden_layers snake_case: str = num_attention_heads snake_case: str = intermediate_size snake_case: Union[str, Any] = hidden_act snake_case: List[Any] = hidden_dropout_prob snake_case: Any = attention_probs_dropout_prob snake_case: Union[str, Any] = initializer_range snake_case: List[Any] = layer_norm_eps snake_case: Tuple = image_size snake_case: Dict = patch_size snake_case: List[Any] = num_channels snake_case: List[str] = use_mask_token snake_case: Optional[Any] = use_absolute_position_embeddings snake_case: str = use_relative_position_bias snake_case: List[str] = use_shared_relative_position_bias snake_case: Tuple = layer_scale_init_value snake_case: Dict = drop_path_rate snake_case: Union[str, Any] = use_mean_pooling # decode head attributes (semantic segmentation) snake_case: Any = out_indices snake_case: Union[str, Any] = pool_scales # auxiliary head attributes (semantic segmentation) snake_case: Optional[Any] = use_auxiliary_head snake_case: int = auxiliary_loss_weight snake_case: Union[str, Any] = auxiliary_channels snake_case: Union[str, Any] = auxiliary_num_convs snake_case: Optional[int] = auxiliary_concat_input snake_case: Dict = semantic_loss_ignore_index class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = version.parse("1.11" ) @property def _UpperCamelCase ( self ): '''simple docstring''' return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _UpperCamelCase ( self ): '''simple docstring''' return 1E-4
692
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = RoCBertTokenizer __UpperCamelCase = None __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = filter_non_english def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: Any = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '你', '好', '是', '谁', 'a', 'b', 'c', 'd'] snake_case: List[Any] = {} snake_case: List[str] = {} for i, value in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = i snake_case: Union[str, Any] = i snake_case: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) snake_case: Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] ) snake_case: str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: Dict = tokenizer.tokenize('你好[SEP]你是谁' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['你', '好', '[SEP]', '你', '是', '谁'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] snake_case: Union[str, Any] = {} for i, token in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: str = i snake_case: Optional[int] = RoCBertWordpieceTokenizer(vocab=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) if self.test_rust_tokenizer: snake_case: int = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) def _UpperCamelCase ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" snake_case: List[str] = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , ) snake_case: Optional[int] = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE__ , 'do_lower_case' ) else False snake_case: int = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'Allen'), ((21, 23), '##NL'), ((23, 24), '##P'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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, 15), tokenizer_r.mask_token), ((16, 21), 'allen'), ((21, 23), '##nl'), ((23, 24), '##p'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = ['的', '人', '有'] snake_case: Any = ''.join(SCREAMING_SNAKE_CASE__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = True snake_case: List[Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = False snake_case: Union[str, Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: int = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that only the first Chinese character is not preceded by "##". snake_case: Union[str, Any] = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE__ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: int = tokenizer.encode('你好' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Any = tokenizer.encode('你是谁' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Dict = '你好,你是谁' snake_case: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer.prepare_for_model( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.encode_plus(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
692
1
'''simple docstring''' # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( "pipelines_utils", "0.22.0", "Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.", standard_warn=False, stacklevel=3, )
692
'''simple docstring''' from math import asin, atan, cos, radians, sin, sqrt, tan __UpperCAmelCase = 6378137.0 __UpperCAmelCase = 6356752.314245 __UpperCAmelCase = 6_378_137 def lowerCAmelCase_ ( __A : float , __A : float , __A : float , __A : float ): '''simple docstring''' snake_case: Optional[Any] = (AXIS_A - AXIS_B) / AXIS_A snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: Tuple = radians(__A ) snake_case: Tuple = radians(__A ) # Equation snake_case: List[Any] = sin((phi_a - phi_a) / 2 ) snake_case: Dict = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda snake_case: Union[str, Any] = sqrt(sin_sq_phi + (cos(__A ) * cos(__A ) * sin_sq_lambda) ) return 2 * RADIUS * asin(__A ) if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __UpperCAmelCase = { "configuration_biogpt": ["BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BioGptConfig"], "tokenization_biogpt": ["BioGptTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST", "BioGptForCausalLM", "BioGptForTokenClassification", "BioGptForSequenceClassification", "BioGptModel", "BioGptPreTrainedModel", ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCAmelCase = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
1
'''simple docstring''' import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=8 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=99 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=5 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=36 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=5_12 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=None , ): '''simple docstring''' snake_case: List[str] = parent snake_case: Any = batch_size snake_case: str = seq_length snake_case: Tuple = is_training snake_case: Optional[int] = use_input_mask snake_case: List[str] = use_token_type_ids snake_case: Optional[int] = use_labels snake_case: List[Any] = vocab_size snake_case: Union[str, Any] = hidden_size snake_case: int = num_hidden_layers snake_case: List[str] = num_attention_heads snake_case: Any = intermediate_size snake_case: Tuple = hidden_act snake_case: Tuple = hidden_dropout_prob snake_case: Optional[int] = attention_probs_dropout_prob snake_case: List[Any] = max_position_embeddings snake_case: Union[str, Any] = type_vocab_size snake_case: Any = type_sequence_label_size snake_case: Dict = initializer_range snake_case: Any = num_labels snake_case: str = num_choices snake_case: List[str] = scope def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case: Tuple = None if self.use_input_mask: snake_case: List[str] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case: Dict = None if self.use_token_type_ids: snake_case: Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case: Any = None snake_case: Any = None snake_case: List[str] = None if self.use_labels: snake_case: List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case: Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case: Any = ids_tensor([self.batch_size] , self.num_choices ) snake_case: Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self ): '''simple docstring''' return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_config() snake_case: Any = 3_00 return config def _UpperCamelCase ( self ): '''simple docstring''' ( ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ): Optional[Any] = self.prepare_config_and_inputs() snake_case: List[Any] = True snake_case: Tuple = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) snake_case: str = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = MraModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: str = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) snake_case: int = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: List[str] = True snake_case: Optional[Any] = MraModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: str = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , encoder_attention_mask=SCREAMING_SNAKE_CASE__ , ) snake_case: Optional[int] = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , ) snake_case: Tuple = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[str] = MraForMaskedLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Tuple = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = MraForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Any = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , start_positions=SCREAMING_SNAKE_CASE__ , end_positions=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[Any] = self.num_labels snake_case: Tuple = MraForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Optional[int] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: str = self.num_labels snake_case: List[Any] = MraForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Optional[Any] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Any = self.num_choices snake_case: Tuple = MraForMultipleChoice(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case: Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case: Any = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case: Any = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case: str = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.prepare_config_and_inputs() ( ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ): Union[str, Any] = config_and_inputs snake_case: Any = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = () def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = MraModelTester(self ) snake_case: List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def _UpperCamelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case: int = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case: Tuple = MraModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason='MRA does not output attentions' ) def _UpperCamelCase ( self ): '''simple docstring''' return @require_torch class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = MraModel.from_pretrained('uw-madison/mra-base-512-4' ) snake_case: Dict = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): snake_case: Any = model(SCREAMING_SNAKE_CASE__ )[0] snake_case: Dict = torch.Size((1, 2_56, 7_68) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = torch.tensor( [[[-0.01_40, 0.08_30, -0.03_81], [0.15_46, 0.14_02, 0.02_20], [0.11_62, 0.08_51, 0.01_65]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = MraForMaskedLM.from_pretrained('uw-madison/mra-base-512-4' ) snake_case: Optional[Any] = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): snake_case: int = model(SCREAMING_SNAKE_CASE__ )[0] snake_case: Dict = 5_02_65 snake_case: int = torch.Size((1, 2_56, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = torch.tensor( [[[9.25_95, -3.60_38, 11.88_19], [9.38_69, -3.26_93, 11.09_56], [11.85_24, -3.49_38, 13.12_10]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = MraForMaskedLM.from_pretrained('uw-madison/mra-base-4096-8-d3' ) snake_case: int = torch.arange(40_96 ).unsqueeze(0 ) with torch.no_grad(): snake_case: Dict = model(SCREAMING_SNAKE_CASE__ )[0] snake_case: Union[str, Any] = 5_02_65 snake_case: Optional[Any] = torch.Size((1, 40_96, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) snake_case: str = torch.tensor( [[[5.47_89, -2.35_64, 7.50_64], [7.90_67, -1.33_69, 9.96_68], [9.07_12, -1.81_06, 7.03_80]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) )
692
'''simple docstring''' import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def lowerCAmelCase_ ( __A : Tuple ): '''simple docstring''' snake_case: Tuple = model.config snake_case: str = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=1_28 , ) snake_case: Optional[Any] = MBartConfig( is_decoder=__A , is_encoder_decoder=__A , add_cross_attention=__A , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=__A , add_final_layer_norm=__A , ) return encoder_config, decoder_config def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if "encoder.model" in name: snake_case: Optional[Any] = name.replace('encoder.model' , 'encoder' ) if "decoder.model" in name: snake_case: str = name.replace('decoder.model' , 'decoder' ) if "patch_embed.proj" in name: snake_case: Any = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: snake_case: Optional[int] = name.replace('patch_embed.norm' , 'embeddings.norm' ) if name.startswith('encoder' ): if "layers" in name: snake_case: Tuple = 'encoder.' + name if "attn.proj" in name: snake_case: Optional[int] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name and "mask" not in name: snake_case: Dict = name.replace('attn' , 'attention.self' ) if "norm1" in name: snake_case: Union[str, Any] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: snake_case: Dict = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: snake_case: List[str] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: snake_case: Dict = name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": snake_case: Dict = 'encoder.layernorm.weight' if name == "encoder.norm.bias": snake_case: int = 'encoder.layernorm.bias' return name def lowerCAmelCase_ ( __A : List[Any] , __A : Optional[Any] ): '''simple docstring''' for key in orig_state_dict.copy().keys(): snake_case: List[Any] = orig_state_dict.pop(__A ) if "qkv" in key: snake_case: Union[str, Any] = key.split('.' ) snake_case: Optional[Any] = int(key_split[3] ) snake_case: Any = int(key_split[5] ) snake_case: Union[str, Any] = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: snake_case: Union[str, Any] = val[:dim, :] snake_case: Any = val[dim : dim * 2, :] snake_case: List[str] = val[-dim:, :] else: snake_case: str = val[:dim] snake_case: Union[str, Any] = val[dim : dim * 2] snake_case: List[Any] = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: snake_case: Optional[int] = val return orig_state_dict def lowerCAmelCase_ ( __A : List[Any] , __A : Any=None , __A : List[str]=False ): '''simple docstring''' snake_case: str = DonutModel.from_pretrained(__A ).eval() # load HuggingFace model snake_case , snake_case: Optional[Any] = get_configs(__A ) snake_case: Optional[int] = DonutSwinModel(__A ) snake_case: Tuple = MBartForCausalLM(__A ) snake_case: Optional[Any] = VisionEncoderDecoderModel(encoder=__A , decoder=__A ) model.eval() snake_case: Optional[int] = original_model.state_dict() snake_case: Optional[int] = convert_state_dict(__A , __A ) model.load_state_dict(__A ) # verify results on scanned document snake_case: Union[str, Any] = load_dataset('hf-internal-testing/example-documents' ) snake_case: str = dataset['test'][0]['image'].convert('RGB' ) snake_case: Optional[int] = XLMRobertaTokenizerFast.from_pretrained(__A , from_slow=__A ) snake_case: Any = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) snake_case: Dict = DonutProcessor(__A , __A ) snake_case: Optional[Any] = processor(__A , return_tensors='pt' ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": snake_case: int = '<s_docvqa><s_question>{user_input}</s_question><s_answer>' snake_case: Optional[Any] = 'When is the coffee break?' snake_case: Optional[int] = task_prompt.replace('{user_input}' , __A ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": snake_case: Dict = '<s_rvlcdip>' elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: snake_case: str = '<s_cord>' elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": snake_case: str = 's_cord-v2>' elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": snake_case: int = '<s_zhtrainticket>' elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt snake_case: Optional[Any] = 'hello world' else: raise ValueError('Model name not supported' ) snake_case: Optional[int] = original_model.decoder.tokenizer(__A , add_special_tokens=__A , return_tensors='pt' )[ 'input_ids' ] snake_case: Any = original_model.encoder.model.patch_embed(__A ) snake_case , snake_case: Dict = model.encoder.embeddings(__A ) assert torch.allclose(__A , __A , atol=1E-3 ) # verify encoder hidden states snake_case: Tuple = original_model.encoder(__A ) snake_case: List[str] = model.encoder(__A ).last_hidden_state assert torch.allclose(__A , __A , atol=1E-2 ) # verify decoder hidden states snake_case: List[Any] = original_model(__A , __A , __A ).logits snake_case: List[Any] = model(__A , decoder_input_ids=__A ).logits assert torch.allclose(__A , __A , atol=1E-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(__A ) processor.save_pretrained(__A ) if push_to_hub: model.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) processor.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) __UpperCAmelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
692
1
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=[10, 20, 30, 40] , SCREAMING_SNAKE_CASE__=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__="relu" , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=None , ): '''simple docstring''' snake_case: Dict = parent snake_case: Dict = batch_size snake_case: Optional[Any] = image_size snake_case: Tuple = num_channels snake_case: Optional[Any] = embeddings_size snake_case: int = hidden_sizes snake_case: List[str] = depths snake_case: Optional[int] = is_training snake_case: Union[str, Any] = use_labels snake_case: int = hidden_act snake_case: Tuple = num_labels snake_case: List[str] = scope snake_case: Union[str, Any] = len(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case: Tuple = self.get_config() return config, pixel_values def _UpperCamelCase ( self ): '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = FlaxRegNetModel(config=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Tuple = self.num_labels snake_case: List[Any] = FlaxRegNetForImageClassification(config=SCREAMING_SNAKE_CASE__ ) snake_case: str = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.prepare_config_and_inputs() snake_case , snake_case: Union[str, Any] = config_and_inputs snake_case: Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_flax class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = FlaxRegNetModelTester(self ) snake_case: Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _UpperCamelCase ( self ): '''simple docstring''' return def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason='RegNet does not use inputs_embeds' ) def _UpperCamelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='RegNet does not support input and output embeddings' ) def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case: str = model_class(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case: Any = [*signature.parameters.keys()] snake_case: List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' def check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case: Tuple = model_class(SCREAMING_SNAKE_CASE__ ) snake_case: str = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) snake_case: List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case: Optional[Any] = self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , expected_num_stages + 1 ) snake_case , snake_case: Dict = 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(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case: Optional[int] = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case: Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): snake_case: Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: int = model_class(SCREAMING_SNAKE_CASE__ ) @jax.jit def model_jitted(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): return model(pixel_values=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with self.subTest('JIT Enabled' ): snake_case: List[Any] = model_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): snake_case: Any = model_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_flax class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _UpperCamelCase ( self ): '''simple docstring''' return AutoImageProcessor.from_pretrained('facebook/regnet-y-040' ) if is_vision_available() else None @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040' ) snake_case: Union[str, Any] = self.default_image_processor snake_case: List[str] = prepare_img() snake_case: Optional[Any] = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) snake_case: Any = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits snake_case: Any = (1, 10_00) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) snake_case: int = jnp.array([-0.41_80, -1.50_51, -3.48_36] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) )
692
'''simple docstring''' 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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = { 'task_specific_params': { 'summarization': {'length_penalty': 1.0, 'max_length': 1_28, 'min_length': 12, 'num_beams': 4}, 'summarization_cnn': {'length_penalty': 2.0, 'max_length': 1_42, 'min_length': 56, 'num_beams': 4}, 'summarization_xsum': {'length_penalty': 1.0, 'max_length': 62, 'min_length': 11, 'num_beams': 6}, } } snake_case: Union[str, Any] = { 'task_specific_params.summarization.length_penalty': 1.0, 'task_specific_params.summarization.max_length': 1_28, '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': 1_42, '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(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , x.transpose() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = np.random.randn(3 , 4 ) snake_case: Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(3 , 4 , 5 ) snake_case: Optional[int] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Dict = np.random.randn(3 , 4 , 5 ) snake_case: str = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Optional[int] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Optional[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) snake_case: Optional[int] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: str = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: List[str] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.squeeze(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: List[str] = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) snake_case: List[str] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: int = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = np.random.randn(1 , 3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Union[str, Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(1 , 3 , 4 ) snake_case: List[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Tuple = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Tuple = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Any = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Any = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = np.random.randn(3 , 4 ) snake_case: int = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.asarray(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) )
692
1
'''simple docstring''' import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = TransfoXLTokenizer __UpperCamelCase = False __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: Dict = [ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] snake_case: str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: str = '<unk> UNwanted , running' snake_case: int = '<unk> unwanted, running' return input_text, output_text def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [0, 4, 8, 7] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = TransfoXLTokenizer(lower_case=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = 'Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' snake_case: Optional[int] = [ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_tokenizer() snake_case: List[Any] = len(SCREAMING_SNAKE_CASE__ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
692
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig __UpperCAmelCase = logging.get_logger(__name__) # General docstring __UpperCAmelCase = "PoolFormerConfig" # Base docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = [1, 512, 7, 7] # Image classification docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = "tabby, tabby cat" __UpperCAmelCase = [ "sail/poolformer_s12", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCAmelCase_ ( __A : Tuple , __A : float = 0.0 , __A : bool = False ): '''simple docstring''' if drop_prob == 0.0 or not training: return input snake_case: Union[str, Any] = 1 - drop_prob snake_case: List[Any] = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets snake_case: List[Any] = keep_prob + torch.rand(__A , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize snake_case: Any = input.div(__A ) * random_tensor return output class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' super().__init__() snake_case: List[str] = drop_prob def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return drop_path(SCREAMING_SNAKE_CASE__ , self.drop_prob , self.training ) def _UpperCamelCase ( self ): '''simple docstring''' return "p={}".format(self.drop_prob ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' super().__init__() snake_case: List[str] = patch_size if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (patch_size, patch_size) snake_case: List[str] = stride if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (stride, stride) snake_case: Union[str, Any] = padding if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (padding, padding) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , kernel_size=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = norm_layer(SCREAMING_SNAKE_CASE__ ) if norm_layer else nn.Identity() def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.projection(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.norm(SCREAMING_SNAKE_CASE__ ) return embeddings class SCREAMING_SNAKE_CASE ( nn.GroupNorm ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(1 , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.AvgPoolad(SCREAMING_SNAKE_CASE__ , stride=1 , padding=pool_size // 2 , count_include_pad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.pool(SCREAMING_SNAKE_CASE__ ) - hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: str = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if isinstance(config.hidden_act , SCREAMING_SNAKE_CASE__ ): snake_case: Tuple = ACTaFN[config.hidden_act] else: snake_case: int = config.hidden_act def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.act_fn(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.drop(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: str = self.drop(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = PoolFormerPooling(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerOutput(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) # Useful for training neural nets snake_case: Union[str, Any] = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if drop_path > 0.0 else nn.Identity() snake_case: Optional[Any] = config.use_layer_scale if config.use_layer_scale: snake_case: Any = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.use_layer_scale: snake_case: str = self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Dict = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection snake_case: str = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = () snake_case: Dict = self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Union[str, Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection snake_case: Any = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = (output,) + outputs return outputs else: snake_case: Optional[Any] = self.drop_path(self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) ) # First residual connection snake_case: Union[str, Any] = pooling_output + hidden_states snake_case: List[Any] = () # Second residual connection inside the PoolFormerOutput block snake_case: List[str] = self.drop_path(self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: Dict = hidden_states + layer_output snake_case: Optional[Any] = (output,) + outputs return outputs class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = config # stochastic depth decay rule snake_case: List[Any] = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings snake_case: Union[str, Any] = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) snake_case: List[Any] = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) # Transformer blocks snake_case: str = [] snake_case: int = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers snake_case: List[str] = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( SCREAMING_SNAKE_CASE__ , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(SCREAMING_SNAKE_CASE__ ) ) snake_case: Tuple = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True ): '''simple docstring''' snake_case: str = () if output_hidden_states else None snake_case: Dict = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): snake_case , snake_case: Dict = layers # Get patch embeddings from hidden_states snake_case: int = embedding_layer(SCREAMING_SNAKE_CASE__ ) # Send the embeddings through the blocks for _, blk in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = blk(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = layer_outputs[0] if output_hidden_states: snake_case: List[str] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = PoolFormerConfig __UpperCamelCase = "poolformer" __UpperCamelCase = "pixel_values" __UpperCamelCase = True def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = value __UpperCAmelCase = R"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" __UpperCAmelCase = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n" @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = config snake_case: Tuple = PoolFormerEncoder(SCREAMING_SNAKE_CASE__ ) # Initialize weights and apply final processing self.post_init() def _UpperCamelCase ( self ): '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Optional[int] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case: List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) snake_case: Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: List[Any] = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=encoder_outputs.hidden_states , ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Any = nn.Linear(config.hidden_size , config.hidden_size ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.dense(SCREAMING_SNAKE_CASE__ ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = config.num_labels snake_case: str = PoolFormerModel(SCREAMING_SNAKE_CASE__ ) # Final norm snake_case: int = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head snake_case: Dict = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict snake_case: Optional[Any] = self.poolformer( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: Any = outputs[0] snake_case: str = self.classifier(self.norm(SCREAMING_SNAKE_CASE__ ).mean([-2, -1] ) ) snake_case: Any = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: snake_case: Tuple = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): snake_case: Dict = 'single_label_classification' else: snake_case: List[str] = 'multi_label_classification' if self.config.problem_type == "regression": snake_case: Union[str, Any] = MSELoss() if self.num_labels == 1: snake_case: List[str] = loss_fct(logits.squeeze() , labels.squeeze() ) else: snake_case: int = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.config.problem_type == "single_label_classification": snake_case: Union[str, Any] = CrossEntropyLoss() snake_case: Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": snake_case: int = BCEWithLogitsLoss() snake_case: Optional[int] = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not return_dict: snake_case: str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=SCREAMING_SNAKE_CASE__ , logits=SCREAMING_SNAKE_CASE__ , hidden_states=outputs.hidden_states )
692
1
'''simple docstring''' class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = len(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = [0] * len_array if len_array > 0: snake_case: Optional[int] = array[0] for i in range(1 , SCREAMING_SNAKE_CASE__ ): snake_case: Tuple = self.prefix_sum[i - 1] + array[i] def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(SCREAMING_SNAKE_CASE__ ) return False if __name__ == "__main__": import doctest doctest.testmod()
692
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def lowerCAmelCase_ ( __A : dict , __A : str , __A : set , __A : set , __A : dict , __A : dict , __A : PriorityQueue , __A : dict , __A : float | int , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue snake_case: Any = cst_fwd.get(__A , np.inf ) snake_case: int = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) snake_case: Union[str, Any] = new_cost_f snake_case: Tuple = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: snake_case: List[str] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def lowerCAmelCase_ ( __A : str , __A : str , __A : dict , __A : dict ): '''simple docstring''' snake_case: Optional[Any] = -1 snake_case: Any = set() snake_case: str = set() snake_case: int = {source: 0} snake_case: Dict = {destination: 0} snake_case: int = {source: None} snake_case: Union[str, Any] = {destination: None} snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: Tuple = 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(): snake_case , snake_case: List[str] = queue_forward.get() visited_forward.add(__A ) snake_case , snake_case: int = queue_backward.get() visited_backward.add(__A ) snake_case: str = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) snake_case: Optional[Any] = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: snake_case: Any = shortest_distance return shortest_path_distance __UpperCAmelCase = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } __UpperCAmelCase = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''simple docstring''' from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __UpperCAmelCase = logging.get_logger(__name__) @add_end_docstrings(snake_case ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) requires_backends(self , 'vision' ) requires_backends(self , 'torch' ) if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""" ) self.check_model_type(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Any = {} snake_case: int = {} snake_case: Tuple = {} # preprocess args if "points_per_batch" in kwargs: snake_case: Optional[int] = kwargs['points_per_batch'] if "points_per_crop" in kwargs: snake_case: Any = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: snake_case: Union[str, Any] = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: snake_case: List[str] = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: snake_case: Optional[Any] = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: snake_case: Tuple = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: snake_case: List[Any] = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: snake_case: Tuple = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: snake_case: str = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: snake_case: Tuple = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: snake_case: str = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: snake_case: int = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return super().__call__(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , num_workers=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=64 , SCREAMING_SNAKE_CASE__ = 0 , SCREAMING_SNAKE_CASE__ = 5_12 / 15_00 , SCREAMING_SNAKE_CASE__ = 32 , SCREAMING_SNAKE_CASE__ = 1 , ): '''simple docstring''' snake_case: Tuple = load_image(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.image_processor.size['longest_edge'] snake_case , snake_case , snake_case , snake_case: str = self.image_processor.generate_crop_boxes( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": snake_case: Any = self.get_inference_context() with inference_context(): snake_case: Optional[Any] = self._ensure_tensor_on_device(SCREAMING_SNAKE_CASE__ , device=self.device ) snake_case: Any = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) snake_case: Optional[int] = image_embeddings snake_case: str = grid_points.shape[1] snake_case: Union[str, Any] = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( 'Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ' 'To return all points at once, set points_per_batch to None' ) for i in range(0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case: Dict = grid_points[:, i : i + points_per_batch, :, :] snake_case: Any = input_labels[:, i : i + points_per_batch] snake_case: Optional[int] = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0.88 , SCREAMING_SNAKE_CASE__=0.95 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=1 , ): '''simple docstring''' snake_case: Dict = model_inputs.pop('input_boxes' ) snake_case: Optional[Any] = model_inputs.pop('is_last' ) snake_case: Optional[Any] = model_inputs.pop('original_sizes' ).tolist() snake_case: Tuple = model_inputs.pop('reshaped_input_sizes' ).tolist() snake_case: Any = self.model(**SCREAMING_SNAKE_CASE__ ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks snake_case: Optional[Any] = model_outputs['pred_masks'] snake_case: str = self.image_processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , binarize=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = model_outputs['iou_scores'] snake_case , snake_case , snake_case: str = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=0.7 , ): '''simple docstring''' snake_case: Union[str, Any] = [] snake_case: List[Any] = [] snake_case: Optional[Any] = [] for model_output in model_outputs: all_scores.append(model_output.pop('iou_scores' ) ) all_masks.extend(model_output.pop('masks' ) ) all_boxes.append(model_output.pop('boxes' ) ) snake_case: List[str] = torch.cat(SCREAMING_SNAKE_CASE__ ) snake_case: int = torch.cat(SCREAMING_SNAKE_CASE__ ) snake_case , snake_case , snake_case , snake_case: Dict = self.image_processor.post_process_for_mask_generation( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: int = defaultdict(SCREAMING_SNAKE_CASE__ ) for output in model_outputs: for k, v in output.items(): extra[k].append(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = {} if output_rle_mask: snake_case: int = rle_mask if output_bboxes_mask: snake_case: Optional[Any] = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
692
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = "▁" __UpperCAmelCase = {"vocab_file": "sentencepiece.bpe.model"} __UpperCAmelCase = { "vocab_file": { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model", } } __UpperCAmelCase = { "facebook/xglm-564M": 2_048, } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer snake_case: Optional[Any] = 7 snake_case: List[str] = [F"""<madeupword{i}>""" for i in range(self.num_madeup_words )] snake_case: str = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) snake_case: int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) snake_case: int = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab snake_case: Tuple = 1 # Mimic fairseq token-to-id alignment for the first 4 token snake_case: Optional[Any] = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} snake_case: Union[str, Any] = len(self.sp_model ) snake_case: str = {F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ): '''simple docstring''' snake_case: List[Any] = self.__dict__.copy() snake_case: Union[str, Any] = None snake_case: Union[str, Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): snake_case: Union[str, Any] = {} snake_case: Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a snake_case: Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' snake_case: int = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def _UpperCamelCase ( self ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case: Dict = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip() return out_string def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case: List[str] = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: snake_case: int = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
692
1
'''simple docstring''' import sys __UpperCAmelCase = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def lowerCAmelCase_ ( __A : str ): '''simple docstring''' snake_case: Tuple = 1 for digit in s: product *= int(__A ) return product def lowerCAmelCase_ ( __A : str = N ): '''simple docstring''' snake_case: List[str] = -sys.maxsize - 1 snake_case: int = n[:13] snake_case: Union[str, Any] = 13 while cur_index < len(__A ) - 13: if int(n[cur_index] ) >= int(substr[0] ): snake_case: Optional[Any] = substr[1:] + n[cur_index] cur_index += 1 else: snake_case: Dict = max(__A , str_eval(__A ) ) snake_case: Optional[int] = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(F'{solution() = }')
692
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' return getitem, k def lowerCAmelCase_ ( __A : Any , __A : Optional[int] ): '''simple docstring''' return setitem, k, v def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' return delitem, k def lowerCAmelCase_ ( __A : str , __A : int , *__A : Tuple ): '''simple docstring''' try: return fun(__A , *__A ), None except Exception as e: return None, e __UpperCAmelCase = ( _set("key_a", "val_a"), _set("key_b", "val_b"), ) __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_a", "val_b"), ] __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_b", "val_b"), _del("key_a"), _del("key_b"), _set("key_a", "val_a"), _del("key_a"), ] __UpperCAmelCase = [ _get("key_a"), _del("key_a"), _set("key_a", "val_a"), _del("key_a"), _del("key_a"), _get("key_a"), ] __UpperCAmelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] __UpperCAmelCase = [ *[_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 lowerCAmelCase_ ( __A : str ): '''simple docstring''' snake_case: List[Any] = HashMap(initial_block_size=4 ) snake_case: List[Any] = {} for _, (fun, *args) in enumerate(__A ): snake_case , snake_case: Optional[int] = _run_operation(__A , __A , *__A ) snake_case , snake_case: str = _run_operation(__A , __A , *__A ) assert my_res == py_res assert str(__A ) == str(__A ) assert set(__A ) == set(__A ) assert len(__A ) == len(__A ) assert set(my.items() ) == set(py.items() ) def lowerCAmelCase_ ( ): '''simple docstring''' def is_public(__A : str ) -> bool: return not name.startswith('_' ) snake_case: Dict = {name for name in dir({} ) if is_public(__A )} snake_case: List[str] = {name for name in dir(HashMap() ) if is_public(__A )} assert dict_public_names > hash_public_names
692
1
'''simple docstring''' import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ConsistencyModelPipeline __UpperCamelCase = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __UpperCamelCase = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __UpperCamelCase = frozenset( [ "num_inference_steps", "generator", "latents", "output_type", "return_dict", "callback", "callback_steps", ] ) @property def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__=False ): '''simple docstring''' if class_cond: snake_case: Dict = self.dummy_cond_unet else: snake_case: List[Any] = self.dummy_uncond_unet # Default to CM multistep sampler snake_case: Optional[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_02 , sigma_max=80.0 , ) snake_case: Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0 ): '''simple docstring''' if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): snake_case: Any = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: snake_case: Union[str, Any] = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) snake_case: int = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case: Union[str, Any] = self.get_dummy_components() snake_case: Tuple = ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__ ) snake_case: Any = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: int = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 32, 32, 3) snake_case: str = image[0, -3:, -3:, -1] snake_case: List[str] = np.array([0.35_72, 0.62_73, 0.40_31, 0.39_61, 0.43_21, 0.57_30, 0.52_66, 0.47_80, 0.50_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case: Any = self.get_dummy_components(class_cond=SCREAMING_SNAKE_CASE__ ) snake_case: Any = ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = 0 snake_case: int = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 32, 32, 3) snake_case: Optional[Any] = image[0, -3:, -3:, -1] snake_case: Optional[int] = np.array([0.35_72, 0.62_73, 0.40_31, 0.39_61, 0.43_21, 0.57_30, 0.52_66, 0.47_80, 0.50_04] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case: List[Any] = self.get_dummy_components() snake_case: Dict = ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: str = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = 1 snake_case: Dict = None snake_case: Union[str, Any] = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 32, 32, 3) snake_case: str = image[0, -3:, -3:, -1] snake_case: List[Any] = np.array([0.50_04, 0.50_04, 0.49_94, 0.50_08, 0.49_76, 0.50_18, 0.49_90, 0.49_82, 0.49_87] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator snake_case: Optional[int] = self.get_dummy_components(class_cond=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__ ) snake_case: int = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = 1 snake_case: int = None snake_case: Optional[int] = 0 snake_case: Any = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 32, 32, 3) snake_case: List[str] = image[0, -3:, -3:, -1] snake_case: Optional[int] = np.array([0.50_04, 0.50_04, 0.49_94, 0.50_08, 0.49_76, 0.50_18, 0.49_90, 0.49_82, 0.49_87] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__="cpu" , SCREAMING_SNAKE_CASE__=torch.floataa , SCREAMING_SNAKE_CASE__=(1, 3, 64, 64) ): '''simple docstring''' snake_case: str = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: snake_case: Any = self.get_fixed_latents(seed=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , shape=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = latents return inputs def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__="cpu" , SCREAMING_SNAKE_CASE__=torch.floataa , SCREAMING_SNAKE_CASE__=(1, 3, 64, 64) ): '''simple docstring''' if type(SCREAMING_SNAKE_CASE__ ) == str: snake_case: Optional[int] = torch.device(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = randn_tensor(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ ) return latents def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) snake_case: int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_02 , sigma_max=80.0 , ) snake_case: Optional[int] = ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) pipe.to(torch_device=SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: str = self.get_inputs() snake_case: Optional[int] = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 64, 64, 3) snake_case: Tuple = image[0, -3:, -3:, -1] snake_case: Optional[Any] = np.array([0.08_88, 0.08_81, 0.06_66, 0.04_79, 0.02_92, 0.01_95, 0.02_01, 0.01_63, 0.02_54] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) snake_case: int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_02 , sigma_max=80.0 , ) snake_case: Optional[Any] = ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) pipe.to(torch_device=SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: str = self.get_inputs() snake_case: Union[str, Any] = 1 snake_case: List[str] = None snake_case: int = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 64, 64, 3) snake_case: Optional[int] = image[0, -3:, -3:, -1] snake_case: str = np.array([0.03_40, 0.01_52, 0.00_63, 0.02_67, 0.02_21, 0.01_07, 0.04_16, 0.01_86, 0.02_17] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 @require_torch_a def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) snake_case: Dict = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_02 , sigma_max=80.0 , ) snake_case: str = ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) pipe.to(torch_device=SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.get_inputs(get_fixed_latents=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=SCREAMING_SNAKE_CASE__ , enable_math=SCREAMING_SNAKE_CASE__ , enable_mem_efficient=SCREAMING_SNAKE_CASE__ ): snake_case: List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 64, 64, 3) snake_case: Union[str, Any] = image[0, -3:, -3:, -1] snake_case: Dict = np.array([0.18_75, 0.14_28, 0.12_89, 0.21_51, 0.20_92, 0.14_77, 0.18_77, 0.16_41, 0.13_53] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @require_torch_a def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) snake_case: List[Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_02 , sigma_max=80.0 , ) snake_case: Tuple = ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) pipe.to(torch_device=SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) snake_case: str = self.get_inputs(get_fixed_latents=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = 1 snake_case: Any = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=SCREAMING_SNAKE_CASE__ , enable_math=SCREAMING_SNAKE_CASE__ , enable_mem_efficient=SCREAMING_SNAKE_CASE__ ): snake_case: List[str] = pipe(**SCREAMING_SNAKE_CASE__ ).images assert image.shape == (1, 64, 64, 3) snake_case: List[str] = image[0, -3:, -3:, -1] snake_case: Union[str, Any] = np.array([0.16_63, 0.19_48, 0.22_75, 0.16_80, 0.12_04, 0.12_45, 0.18_58, 0.13_38, 0.20_95] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
692
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "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": "lm_head", "mask_emb": "masked_spec_embed", } __UpperCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def lowerCAmelCase_ ( __A : Any , __A : Optional[Any] , __A : Union[str, Any] , __A : int , __A : Optional[int] ): '''simple docstring''' for attribute in key.split('.' ): snake_case: List[str] = getattr(__A , __A ) if weight_type is not None: snake_case: Optional[int] = getattr(__A , __A ).shape else: snake_case: Optional[int] = 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": snake_case: Optional[int] = value elif weight_type == "weight_g": snake_case: List[str] = value elif weight_type == "weight_v": snake_case: Dict = value elif weight_type == "bias": snake_case: Optional[Any] = value else: snake_case: int = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def lowerCAmelCase_ ( __A : List[Any] , __A : List[str] ): '''simple docstring''' snake_case: List[Any] = [] snake_case: List[Any] = fairseq_model.state_dict() snake_case: Union[str, Any] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight snake_case: Dict = None for name, value in fairseq_dict.items(): snake_case: Tuple = False if "conv_layers" in name: load_conv_layer( __A , __A , __A , __A , hf_model.config.feat_extract_norm == 'group' , ) snake_case: List[Any] = True elif name.split('.' )[0] == "proj": snake_case: List[Any] = fairseq_model.proj snake_case: int = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: snake_case: int = True if "*" in mapped_key: snake_case: List[str] = name.split(__A )[0].split('.' )[-2] snake_case: Dict = mapped_key.replace('*' , __A ) if "weight_g" in name: snake_case: Tuple = 'weight_g' elif "weight_v" in name: snake_case: int = 'weight_v' elif "bias" in name: snake_case: Tuple = 'bias' elif "weight" in name: snake_case: List[Any] = 'weight' else: snake_case: Any = None set_recursively(__A , __A , __A , __A , __A ) continue if not is_used: unused_weights.append(__A ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCAmelCase_ ( __A : List[str] , __A : List[Any] , __A : int , __A : Optional[Any] , __A : Optional[int] ): '''simple docstring''' snake_case: int = full_name.split('conv_layers.' )[-1] snake_case: Tuple = name.split('.' ) snake_case: Any = int(items[0] ) snake_case: Optional[int] = 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.""" ) snake_case: Tuple = 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.""" ) snake_case: int = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) snake_case: Any = 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.""" ) snake_case: str = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__A ) def lowerCAmelCase_ ( __A : Dict ): '''simple docstring''' snake_case , snake_case: List[Any] = emb.weight.shape snake_case: Optional[int] = nn.Linear(__A , __A , bias=__A ) snake_case: Any = emb.weight.data return lin_layer def lowerCAmelCase_ ( __A : Optional[int] ): '''simple docstring''' with open(__A , 'r' , encoding='utf-8' ) as f: snake_case: List[Any] = f.readlines() snake_case: Any = [line.split(' ' )[0] for line in lines] snake_case: int = len(__A ) snake_case: Dict = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(__A , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCAmelCase_ ( __A : Optional[Any] , __A : Union[str, Any] , __A : Dict , __A : Any , __A : List[Any] , __A : int , __A : str , ): '''simple docstring''' snake_case: Union[str, Any] = WavaVecaConfig.from_pretrained(__A ) snake_case: str = SpeechaTextaConfig.from_pretrained( __A , vocab_size=__A , decoder_layers=__A , do_stable_layer_norm=__A ) snake_case: List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=__A , return_attention_mask=__A , ) snake_case , snake_case , snake_case: List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) snake_case: List[Any] = model[0].eval() # set weights for wav2vec2 encoder snake_case: Optional[Any] = WavaVecaModel(__A ) snake_case: Any = recursively_load_weights_wavaveca(model.encoder , __A ) snake_case: Union[str, Any] = SpeechaTextaForCausalLM(__A ) snake_case , snake_case: Optional[Any] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__A ) # set output linear layer unexpected_keys.remove('embed_out' ) snake_case: str = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) snake_case: int = SpeechEncoderDecoderModel(encoder=__A , decoder=__A ) snake_case: List[Any] = False # add projection layer snake_case: Union[str, Any] = nn.Parameter(projection_layer.weight ) snake_case: Union[str, Any] = nn.Parameter(projection_layer.bias ) snake_case: List[Any] = create_vocab_dict(__A ) with open(os.path.join(__A , 'vocab.json' ) , 'w' ) as fp: json.dump(__A , __A ) snake_case: Union[str, Any] = SpeechaTextaTokenizer(os.path.join(__A , 'vocab.json' ) ) tokenizer.save_pretrained(__A ) snake_case: Tuple = hf_wavavec.config.to_dict() snake_case: int = tokenizer.pad_token_id snake_case: Dict = tokenizer.bos_token_id snake_case: Optional[int] = tokenizer.eos_token_id snake_case: Dict = 'speech_to_text_2' snake_case: Optional[Any] = 'wav2vec2' snake_case: Tuple = SpeechEncoderDecoderConfig.from_dict(__A ) hf_wavavec.save_pretrained(__A ) feature_extractor.save_pretrained(__A ) if __name__ == "__main__": __UpperCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") __UpperCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
692
1
'''simple docstring''' __UpperCAmelCase = [ "DownloadConfig", "DownloadManager", "DownloadMode", "StreamingDownloadManager", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
692
'''simple docstring''' def lowerCAmelCase_ ( __A : int = 1_00 ): '''simple docstring''' snake_case: List[str] = n * (n + 1) * (2 * n + 1) / 6 snake_case: List[Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F'{solution() = }')
692
1
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow __UpperCAmelCase = logging.getLogger() @unittest.skip("Temporarily disable the doc tests." ) @require_torch @require_tf @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = True , ): '''simple docstring''' snake_case: Optional[Any] = [file for file in os.listdir(SCREAMING_SNAKE_CASE__ ) if os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )] if identifier is not None: snake_case: Dict = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for n_ in n_identifier: snake_case: List[Any] = [file for file in files if n_ not in file] else: snake_case: Tuple = [file for file in files if n_identifier not in file] snake_case: Dict = ignore_files or [] ignore_files.append('__init__.py' ) snake_case: Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' , SCREAMING_SNAKE_CASE__ ) if only_modules: snake_case: Optional[int] = file.split('.' )[0] try: snake_case: Dict = getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: str = doctest.DocTestSuite(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = unittest.TextTestRunner().run(SCREAMING_SNAKE_CASE__ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: snake_case: List[str] = doctest.testfile(str('..' / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = Path('src/transformers' ) snake_case: Optional[int] = 'modeling' snake_case: List[Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(SCREAMING_SNAKE_CASE__ , identifier=SCREAMING_SNAKE_CASE__ , ignore_files=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = Path('src/transformers' ) snake_case: str = 'tokenization' self.analyze_directory(SCREAMING_SNAKE_CASE__ , identifier=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = Path('src/transformers' ) snake_case: Any = 'configuration' self.analyze_directory(SCREAMING_SNAKE_CASE__ , identifier=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = Path('src/transformers' ) snake_case: str = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(SCREAMING_SNAKE_CASE__ , n_identifier=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = Path('docs/source' ) snake_case: Any = ['favicon.ico'] self.analyze_directory(SCREAMING_SNAKE_CASE__ , ignore_files=SCREAMING_SNAKE_CASE__ , only_modules=SCREAMING_SNAKE_CASE__ )
692
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration __UpperCAmelCase = [ # tf -> hf ("/", "."), ("layer_", "layers."), ("kernel", "weight"), ("beta", "bias"), ("gamma", "weight"), ("pegasus", "model"), ] __UpperCAmelCase = [ (".output.dense", ".fc2"), ("intermediate.LayerNorm", "final_layer_norm"), ("intermediate.dense", "fc1"), ] __UpperCAmelCase = ( INIT_COMMON + [ ("attention.self.LayerNorm", "self_attn_layer_norm"), ("attention.output.dense", "self_attn.out_proj"), ("attention.self", "self_attn"), ("attention.encdec.LayerNorm", "encoder_attn_layer_norm"), ("attention.encdec_output.dense", "encoder_attn.out_proj"), ("attention.encdec", "encoder_attn"), ("key", "k_proj"), ("value", "v_proj"), ("query", "q_proj"), ("decoder.LayerNorm", "decoder.layernorm_embedding"), ] + END_COMMON ) __UpperCAmelCase = ( INIT_COMMON + [ ("embeddings.word_embeddings", "shared.weight"), ("embeddings.position_embeddings", "embed_positions.weight"), ("attention.self.LayerNorm", "self_attn_layer_norm"), ("attention.output.dense", "self_attn.output"), ("attention.self", "self_attn.self"), ("encoder.LayerNorm", "encoder.layernorm_embedding"), ] + END_COMMON ) __UpperCAmelCase = [ "encdec/key/bias", "encdec/query/bias", "encdec/value/bias", "self/key/bias", "self/query/bias", "self/value/bias", "encdec_output/dense/bias", "attention/output/dense/bias", ] def lowerCAmelCase_ ( __A : Dict , __A : List[Any] ): '''simple docstring''' for tf_name, hf_name in patterns: snake_case: List[Any] = k.replace(__A , __A ) return k def lowerCAmelCase_ ( __A : dict , __A : dict ): '''simple docstring''' snake_case: Optional[int] = BigBirdPegasusConfig(**__A ) snake_case: List[Any] = BigBirdPegasusForConditionalGeneration(__A ) snake_case: Any = torch_model.state_dict() snake_case: Any = {} # separating decoder weights snake_case: Optional[Any] = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder' )} snake_case: Any = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder' )} for k, v in tqdm(decoder_weights.items() , 'tf -> hf conversion' ): snake_case: List[str] = [k.endswith(__A ) for ending in KEYS_TO_IGNORE] if any(__A ): continue snake_case: Any = DECODER_PATTERNS snake_case: int = rename_state_dict_key(__A , __A ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): snake_case: Optional[Any] = v.T snake_case: Any = torch.from_numpy(__A ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items() , 'tf -> hf conversion' ): snake_case: List[Any] = [k.endswith(__A ) for ending in KEYS_TO_IGNORE] if any(__A ): continue snake_case: Union[str, Any] = REMAINING_PATTERNS snake_case: str = rename_state_dict_key(__A , __A ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): snake_case: int = v.T snake_case: Any = torch.from_numpy(__A ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" snake_case: str = mapping['model.embed_positions.weight'] snake_case: Any = mapping.pop('model.embed_positions.weight' ) snake_case , snake_case: Union[str, Any] = torch_model.load_state_dict(__A , strict=__A ) snake_case: Optional[int] = [ k for k in missing if k not in [ 'final_logits_bias', 'model.encoder.embed_tokens.weight', 'model.decoder.embed_tokens.weight', 'lm_head.weight', ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def lowerCAmelCase_ ( __A : Optional[int] ): '''simple docstring''' snake_case: Tuple = tf.train.list_variables(__A ) snake_case: str = {} snake_case: List[str] = ['global_step'] for name, shape in tqdm(__A , desc='converting tf checkpoint to dict' ): snake_case: str = any(pat in name for pat in ignore_name ) if skip_key: continue snake_case: Any = tf.train.load_variable(__A , __A ) snake_case: Optional[int] = array return tf_weights def lowerCAmelCase_ ( __A : str , __A : str , __A : dict ): '''simple docstring''' snake_case: int = get_tf_weights_as_numpy(__A ) snake_case: int = convert_bigbird_pegasus(__A , __A ) torch_model.save_pretrained(__A ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("--tf_ckpt_path", type=str, help="passed to tf.train.list_variables") parser.add_argument("--save_dir", default=None, type=str, help="Path to the output PyTorch model.") __UpperCAmelCase = parser.parse_args() __UpperCAmelCase = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
692
1
'''simple docstring''' __UpperCAmelCase = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def lowerCAmelCase_ ( __A : str , __A : Dict , __A : Dict , __A : Any ): '''simple docstring''' snake_case: str = [False] * len(__A ) snake_case: Any = [s] snake_case: int = True while queue: snake_case: Optional[Any] = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(__A ) snake_case: List[str] = True snake_case: str = u return visited[t] def lowerCAmelCase_ ( __A : List[str] , __A : List[Any] , __A : Dict ): '''simple docstring''' snake_case: List[Any] = [-1] * (len(__A )) snake_case: Any = 0 snake_case: Tuple = [] snake_case: Any = [i[:] for i in graph] # Record original cut, copy. while bfs(__A , __A , __A , __A ): snake_case: int = float('Inf' ) snake_case: Any = sink while s != source: # Find the minimum value in select path snake_case: str = min(__A , graph[parent[s]][s] ) snake_case: Dict = parent[s] max_flow += path_flow snake_case: Optional[Any] = sink while v != source: snake_case: Dict = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow snake_case: Optional[Any] = parent[v] for i in range(len(__A ) ): for j in range(len(graph[0] ) ): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j) ) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
692
'''simple docstring''' def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' snake_case: str = [0] * len(__A ) snake_case: Tuple = [] snake_case: Tuple = [1] * len(__A ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__A ) ): if indegree[i] == 0: queue.append(__A ) while queue: snake_case: int = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: snake_case: Any = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(__A ) print(max(__A ) ) # Adjacency list of Graph __UpperCAmelCase = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
692
1
'''simple docstring''' def lowerCAmelCase_ ( __A : int = 10**9 ): '''simple docstring''' snake_case: int = 1 snake_case: List[Any] = 2 snake_case: str = 0 snake_case: Optional[Any] = 0 snake_case: List[Any] = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value snake_case: Tuple = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(F'{solution() = }')
692
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = tempfile.mkdtemp() snake_case: Optional[Any] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '的', '价', '格', '是', '15', '便', 'alex', '##andra', ',', '。', '-', 't', 'shirt', ] snake_case: Optional[Any] = 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] ) ) snake_case: Optional[int] = { 'do_resize': True, 'size': {'height': 2_24, 'width': 2_24}, 'do_center_crop': True, 'crop_size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], 'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], 'do_convert_rgb': True, } snake_case: Union[str, Any] = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] snake_case: Tuple = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_tokenizer() snake_case: Union[str, Any] = self.get_rust_tokenizer() snake_case: Union[str, Any] = self.get_image_processor() snake_case: List[str] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) snake_case: List[str] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) snake_case: Any = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) snake_case: Optional[int] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case: Optional[int] = self.get_tokenizer(cls_token='(CLS)' , sep_token='(SEP)' ) snake_case: Union[str, Any] = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='(CLS)' , sep_token='(SEP)' , do_normalize=SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.get_image_processor() snake_case: Tuple = self.get_tokenizer() snake_case: Optional[Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.prepare_image_inputs() snake_case: List[Any] = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) snake_case: Dict = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_image_processor() snake_case: Optional[int] = self.get_tokenizer() snake_case: List[Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = 'Alexandra,T-shirt的价格是15便士。' snake_case: Union[str, Any] = processor(text=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer(SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_image_processor() snake_case: Dict = self.get_tokenizer() snake_case: Optional[int] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Dict = 'Alexandra,T-shirt的价格是15便士。' snake_case: Tuple = self.prepare_image_inputs() snake_case: Any = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.get_image_processor() snake_case: str = self.get_tokenizer() snake_case: Union[str, Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] snake_case: int = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_image_processor() snake_case: Dict = self.get_tokenizer() snake_case: Optional[int] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = 'Alexandra,T-shirt的价格是15便士。' snake_case: List[Any] = self.prepare_image_inputs() snake_case: Dict = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
692
1
'''simple docstring''' import argparse import torch from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCAmelCase_ ( __A : Any , __A : Union[str, Any] , __A : List[str] ): '''simple docstring''' if openai_config_file == "": snake_case: str = OpenAIGPTConfig() else: snake_case: Tuple = OpenAIGPTConfig.from_json_file(__A ) snake_case: Union[str, Any] = OpenAIGPTModel(__A ) # Load weights from numpy load_tf_weights_in_openai_gpt(__A , __A , __A ) # Save pytorch-model snake_case: Optional[int] = pytorch_dump_folder_path + '/' + WEIGHTS_NAME snake_case: Union[str, Any] = pytorch_dump_folder_path + '/' + CONFIG_NAME print(f"""Save PyTorch model to {pytorch_weights_dump_path}""" ) torch.save(model.state_dict() , __A ) print(f"""Save configuration file to {pytorch_config_dump_path}""" ) with open(__A , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--openai_checkpoint_folder_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--openai_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained OpenAI model. \n" "This specifies the model architecture." ), ) __UpperCAmelCase = parser.parse_args() convert_openai_checkpoint_to_pytorch( args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path )
692
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "microsoft/swinv2-tiny-patch4-window8-256": ( "https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json" ), } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = "swinv2" __UpperCamelCase = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , SCREAMING_SNAKE_CASE__=2_24 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=96 , SCREAMING_SNAKE_CASE__=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE__=[3, 6, 12, 24] , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=4.0 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=32 , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case: int = image_size snake_case: Union[str, Any] = patch_size snake_case: List[str] = num_channels snake_case: Tuple = embed_dim snake_case: str = depths snake_case: Any = len(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = num_heads snake_case: Optional[int] = window_size snake_case: Any = mlp_ratio snake_case: Optional[int] = qkv_bias snake_case: Union[str, Any] = hidden_dropout_prob snake_case: List[str] = attention_probs_dropout_prob snake_case: Dict = drop_path_rate snake_case: List[str] = hidden_act snake_case: int = use_absolute_embeddings snake_case: Any = layer_norm_eps snake_case: Dict = initializer_range snake_case: List[Any] = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model snake_case: Tuple = int(embed_dim * 2 ** (len(SCREAMING_SNAKE_CASE__ ) - 1) ) snake_case: Union[str, Any] = (0, 0, 0, 0)
692
1
'''simple docstring''' import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __UpperCAmelCase = 16 __UpperCAmelCase = 32 def lowerCAmelCase_ ( __A : Accelerator , __A : DatasetDict , __A : List[int] , __A : List[int] , __A : int = 16 ): '''simple docstring''' snake_case: int = AutoTokenizer.from_pretrained('bert-base-cased' ) snake_case: Tuple = DatasetDict( { 'train': dataset['train'].select(__A ), 'validation': dataset['train'].select(__A ), 'test': dataset['validation'], } ) def tokenize_function(__A : List[Any] ): # max_length=None => use the model max length (it's actually the default) snake_case: Any = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=__A , max_length=__A ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): snake_case: Union[str, Any] = datasets.map( __A , batched=__A , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library snake_case: Optional[Any] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(__A : List[str] ): # On TPU it's best to pad everything to the same length or training will be very slow. snake_case: Tuple = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": snake_case: Union[str, Any] = 16 elif accelerator.mixed_precision != "no": snake_case: List[str] = 8 else: snake_case: List[str] = None return tokenizer.pad( __A , padding='longest' , max_length=__A , pad_to_multiple_of=__A , return_tensors='pt' , ) # Instantiate dataloaders. snake_case: int = DataLoader( tokenized_datasets['train'] , shuffle=__A , collate_fn=__A , batch_size=__A ) snake_case: Union[str, Any] = DataLoader( tokenized_datasets['validation'] , shuffle=__A , collate_fn=__A , batch_size=__A ) snake_case: Union[str, Any] = DataLoader( tokenized_datasets['test'] , shuffle=__A , collate_fn=__A , batch_size=__A ) return train_dataloader, eval_dataloader, test_dataloader def lowerCAmelCase_ ( __A : List[Any] , __A : Optional[int] ): '''simple docstring''' snake_case: List[Any] = [] # Download the dataset snake_case: Optional[Any] = load_dataset('glue' , 'mrpc' ) # Create our splits snake_case: Dict = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator snake_case: Optional[int] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs snake_case: List[Any] = config['lr'] snake_case: Any = int(config['num_epochs'] ) snake_case: List[str] = int(config['seed'] ) snake_case: int = int(config['batch_size'] ) snake_case: List[Any] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation snake_case: int = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: snake_case: str = batch_size // MAX_GPU_BATCH_SIZE snake_case: Optional[int] = MAX_GPU_BATCH_SIZE set_seed(__A ) # New Code # # Create our folds: snake_case: int = kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] ) snake_case: Tuple = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(__A ): snake_case , snake_case , snake_case: List[str] = get_fold_dataloaders( __A , __A , __A , __A , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) snake_case: List[str] = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=__A ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). snake_case: Any = model.to(accelerator.device ) # Instantiate optimizer snake_case: Dict = AdamW(params=model.parameters() , lr=__A ) # Instantiate scheduler snake_case: Any = get_linear_schedule_with_warmup( optimizer=__A , num_warmup_steps=1_00 , num_training_steps=(len(__A ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. snake_case , snake_case , snake_case , snake_case , snake_case: Optional[int] = accelerator.prepare( __A , __A , __A , __A , __A ) # Now we train the model for epoch in range(__A ): model.train() for step, batch in enumerate(__A ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) snake_case: List[Any] = model(**__A ) snake_case: List[str] = outputs.loss snake_case: List[Any] = loss / gradient_accumulation_steps accelerator.backward(__A ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__A ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): snake_case: Any = model(**__A ) snake_case: Tuple = outputs.logits.argmax(dim=-1 ) snake_case , snake_case: Optional[int] = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=__A , references=__A , ) snake_case: int = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __A ) # New Code # # We also run predictions on the test set at the very end snake_case: str = [] for step, batch in enumerate(__A ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): snake_case: Any = model(**__A ) snake_case: Union[str, Any] = outputs.logits snake_case , snake_case: Dict = accelerator.gather_for_metrics((predictions, batch['labels']) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(__A , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: snake_case: Optional[int] = torch.cat(__A , dim=0 ) snake_case: List[str] = torch.stack(__A , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) snake_case: Dict = metric.compute(predictions=__A , references=__A ) accelerator.print('Average test metrics from all folds:' , __A ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Any = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=__A , default=__A , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) # New Code # parser.add_argument('--num_folds' , type=__A , default=3 , help='The number of splits to perform across the dataset' ) snake_case: Optional[Any] = parser.parse_args() snake_case: Union[str, Any] = {'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(__A , __A ) if __name__ == "__main__": main()
692
'''simple docstring''' import os import sys import unittest __UpperCAmelCase = 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_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __UpperCAmelCase = os.path.join(git_repo_path, "src", "transformers") __UpperCAmelCase = "\n{0} = None\n" __UpperCAmelCase = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n" __UpperCAmelCase = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n" class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = find_backend(' _import_structure["models.albert"].append("AlbertTokenizerFast")' ) self.assertIsNone(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = find_backend(' if not is_tokenizers_available():' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'tokenizers' ) snake_case: List[Any] = find_backend(' if not is_tensorflow_text_available():' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'tensorflow_text' ) snake_case: int = find_backend(' if not (is_sentencepiece_available() and is_tokenizers_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tokenizers' ) snake_case: Optional[Any] = find_backend( ' if not (is_sentencepiece_available() and is_tensorflow_text_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tensorflow_text' ) snake_case: Dict = find_backend( ' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tokenizers_and_vision' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('torch' , SCREAMING_SNAKE_CASE__ ) self.assertIn('tensorflow_text' , SCREAMING_SNAKE_CASE__ ) self.assertIn('sentencepiece_and_tokenizers' , SCREAMING_SNAKE_CASE__ ) # Likewise, we can't assert on the exact content of a key self.assertIn('BertModel' , objects['torch'] ) self.assertIn('TFBertModel' , objects['tf'] ) self.assertIn('FlaxBertModel' , objects['flax'] ) self.assertIn('BertModel' , objects['torch'] ) self.assertIn('TFBertTokenizer' , objects['tensorflow_text'] ) self.assertIn('convert_slow_tokenizer' , objects['sentencepiece_and_tokenizers'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = create_dummy_object('CONSTANT' , '\'torch\'' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , '\nCONSTANT = None\n' ) snake_case: Any = create_dummy_object('function' , '\'torch\'' ) self.assertEqual( SCREAMING_SNAKE_CASE__ , '\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n' ) snake_case: Optional[int] = '\nclass FakeClass(metaclass=DummyObject):\n _backends = \'torch\'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, \'torch\')\n' snake_case: Tuple = create_dummy_object('FakeClass' , '\'torch\'' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = ["torch"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, ["torch"])\n' snake_case: Optional[int] = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} ) self.assertEqual(dummy_files['torch'] , SCREAMING_SNAKE_CASE__ )
692
1
'''simple docstring''' import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = FlaxAutoencoderKL @property def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = 4 snake_case: Optional[int] = 3 snake_case: List[Any] = (32, 32) snake_case: List[Any] = jax.random.PRNGKey(0 ) snake_case: Dict = jax.random.uniform(SCREAMING_SNAKE_CASE__ , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 4, } snake_case: Any = self.dummy_input return init_dict, inputs_dict
692
'''simple docstring''' import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig __UpperCAmelCase = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = question_encoder snake_case: Union[str, Any] = generator snake_case: Optional[int] = self.question_encoder def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if os.path.isfile(SCREAMING_SNAKE_CASE__ ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , 'question_encoder_tokenizer' ) snake_case: Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , 'generator_tokenizer' ) self.question_encoder.save_pretrained(SCREAMING_SNAKE_CASE__ ) self.generator.save_pretrained(SCREAMING_SNAKE_CASE__ ) @classmethod def _UpperCamelCase ( cls , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer snake_case: int = kwargs.pop('config' , SCREAMING_SNAKE_CASE__ ) if config is None: snake_case: str = RagConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE__ , config=config.question_encoder , subfolder='question_encoder_tokenizer' ) snake_case: Dict = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE__ , config=config.generator , subfolder='generator_tokenizer' ) return cls(question_encoder=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) def __call__( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.current_tokenizer(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.generator.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.generator.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.question_encoder def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.generator def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "longest" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = True , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' warnings.warn( '`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ' 'regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ' 'context manager to prepare your targets. See the documentation of your specific tokenizer for more ' 'details' , SCREAMING_SNAKE_CASE__ , ) if max_length is None: snake_case: Optional[Any] = self.current_tokenizer.model_max_length snake_case: int = self( SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: snake_case: Any = self.current_tokenizer.model_max_length snake_case: List[str] = self( text_target=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case: Dict = labels['input_ids'] return model_inputs
692
1
'''simple docstring''' __UpperCAmelCase = { "joule": 1.0, "kilojoule": 1_000, "megajoule": 1_000_000, "gigajoule": 1_000_000_000, "wattsecond": 1.0, "watthour": 3_600, "kilowatthour": 3_600_000, "newtonmeter": 1.0, "calorie_nutr": 4_186.8, "kilocalorie_nutr": 4_186_800.00, "electronvolt": 1.6_02_17_66_34E-19, "britishthermalunit_it": 1_055.05_585, "footpound": 1.355818, } def lowerCAmelCase_ ( __A : str , __A : str , __A : float ): '''simple docstring''' if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION: snake_case: List[str] = ( f"""Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n""" f"""Valid values are: {', '.join(__A )}""" ) raise ValueError(__A ) return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type] if __name__ == "__main__": import doctest doctest.testmod()
692
'''simple docstring''' 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_ ( __A : Tuple ): '''simple docstring''' assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ): '''simple docstring''' assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Union[str, Any] = 'mock-s3-bucket' snake_case: int = f"""s3://{mock_bucket}""" snake_case: Any = extract_path_from_uri(__A ) assert dataset_path.startswith('s3://' ) is False snake_case: Union[str, Any] = './local/path' snake_case: Union[str, Any] = extract_path_from_uri(__A ) assert dataset_path == new_dataset_path def lowerCAmelCase_ ( __A : Any ): '''simple docstring''' snake_case: List[str] = is_remote_filesystem(__A ) assert is_remote is True snake_case: int = fsspec.filesystem('file' ) snake_case: int = is_remote_filesystem(__A ) assert is_remote is False @pytest.mark.parametrize('compression_fs_class' , __A ) def lowerCAmelCase_ ( __A : Optional[int] , __A : int , __A : str , __A : Optional[Any] , __A : List[str] , __A : Optional[Any] , __A : Optional[int] ): '''simple docstring''' snake_case: Optional[Any] = {'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_file, 'bz2': bza_file, 'lz4': lza_file} snake_case: Optional[int] = input_paths[compression_fs_class.protocol] if input_path is None: snake_case: str = 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(__A ) snake_case: List[str] = fsspec.filesystem(compression_fs_class.protocol , fo=__A ) assert isinstance(__A , __A ) snake_case: Any = os.path.basename(__A ) snake_case: int = expected_filename[: expected_filename.rindex('.' )] assert fs.glob('*' ) == [expected_filename] with fs.open(__A , 'r' , encoding='utf-8' ) as f, open(__A , encoding='utf-8' ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize('protocol' , ['zip', 'gzip'] ) def lowerCAmelCase_ ( __A : Any , __A : int , __A : int ): '''simple docstring''' snake_case: List[str] = {'zip': zip_jsonl_path, 'gzip': jsonl_gz_path} snake_case: str = compressed_file_paths[protocol] snake_case: Dict = 'dataset.jsonl' snake_case: Optional[Any] = f"""{protocol}://{member_file_path}::{compressed_file_path}""" snake_case , *snake_case: List[Any] = fsspec.get_fs_token_paths(__A ) assert fs.isfile(__A ) assert not fs.isfile('non_existing_' + member_file_path ) @pytest.mark.integration def lowerCAmelCase_ ( __A : Optional[Any] , __A : Union[str, Any] , __A : Union[str, Any] , __A : List[Any] ): '''simple docstring''' snake_case: Tuple = hf_api.dataset_info(__A , token=__A ) snake_case: List[str] = HfFileSystem(repo_info=__A , token=__A ) assert sorted(hffs.glob('*' ) ) == [".gitattributes", "data"] assert hffs.isdir('data' ) assert hffs.isfile('.gitattributes' ) and hffs.isfile('data/text_data.txt' ) with open(__A ) as f: assert hffs.open('data/text_data.txt' , 'r' ).read() == f.read() def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Union[str, Any] = 'bz2' # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(__A , __A , clobber=__A ) with pytest.warns(__A ) as warning_info: importlib.reload(datasets.filesystems ) assert len(__A ) == 1 assert ( str(warning_info[0].message ) == f"""A filesystem protocol was already set for {protocol} and will be overwritten.""" )
692
1
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCAmelCase = { "configuration_vivit": ["VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "VivitConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["VivitImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "VivitModel", "VivitPreTrainedModel", "VivitForVideoClassification", ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
'''simple docstring''' import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.17.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") __UpperCAmelCase = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = field( default="tab_fact" , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) __UpperCamelCase = field( default="tab_fact" , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} , ) __UpperCamelCase = field( default=1024 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "A csv or a json file containing the training data."} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "A csv or a json file containing the validation data."} ) __UpperCamelCase = field(default=snake_case , metadata={"help": "A csv or a json file containing the test data."} ) def _UpperCamelCase ( self ): '''simple docstring''' if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError('Need either a GLUE task, a training/validation file or a dataset name.' ) else: snake_case: str = self.train_file.split('.' )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." snake_case: Optional[Any] = self.validation_file.split('.' )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = field( default=snake_case , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) __UpperCamelCase = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case , snake_case , snake_case: Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case , snake_case , snake_case: str = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) snake_case: Tuple = training_args.get_process_log_level() logger.setLevel(__A ) datasets.utils.logging.set_verbosity(__A ) transformers.utils.logging.set_verbosity(__A ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. snake_case: Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case: List[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. snake_case: int = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. snake_case: Optional[int] = {'train': data_args.train_file, 'validation': data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: snake_case: Tuple = data_args.train_file.split('.' )[-1] snake_case: Union[str, Any] = data_args.test_file.split('.' )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." snake_case: Union[str, Any] = data_args.test_file else: raise ValueError('Need either a GLUE task or a test file for `do_predict`.' ) for key in data_files.keys(): logger.info(f"""load a local file for {key}: {data_files[key]}""" ) if data_args.train_file.endswith('.csv' ): # Loading a dataset from local csv files snake_case: List[Any] = load_dataset('csv' , data_files=__A , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files snake_case: Optional[Any] = load_dataset('json' , data_files=__A , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels snake_case: Tuple = raw_datasets['train'].features['label'].names snake_case: List[str] = len(__A ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case: Tuple = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer snake_case: List[str] = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=__A , ) snake_case: Union[str, Any] = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=__A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: snake_case: int = 'max_length' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch snake_case: Union[str, Any] = False # Some models have set the order of the labels to use, so let's make sure we do use it. snake_case: Optional[Any] = {'Refused': 0, 'Entailed': 1} snake_case: List[Any] = {0: 'Refused', 1: 'Entailed'} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) snake_case: List[str] = min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(__A : Any ): # Tokenize the texts def _convert_table_text_to_pandas(__A : Dict ): snake_case: str = [_table_row.split('#' ) for _table_row in _table_text.strip('\n' ).split('\n' )] snake_case: List[str] = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd snake_case: str = examples['statement'] snake_case: int = list(map(_convert_table_text_to_pandas , examples['table_text'] ) ) snake_case: List[Any] = tokenizer(__A , __A , padding=__A , max_length=__A , truncation=__A ) snake_case: List[Any] = examples['label'] return result with training_args.main_process_first(desc='dataset map pre-processing' ): snake_case: int = raw_datasets.map( __A , batched=__A , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on dataset' , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError('--do_train requires a train dataset' ) snake_case: List[str] = raw_datasets['train'] if data_args.max_train_samples is not None: snake_case: Tuple = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError('--do_eval requires a validation dataset' ) snake_case: Any = raw_datasets['validation'] if data_args.max_eval_samples is not None: snake_case: Optional[int] = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError('--do_predict requires a test dataset' ) snake_case: str = raw_datasets['test'] if data_args.max_predict_samples is not None: snake_case: List[str] = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(__A ) ) , 3 ): logger.info(f"""Sample {index} of the training set: {train_dataset[index]}.""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__A : EvalPrediction ): snake_case: int = p.predictions[0] if isinstance(p.predictions , __A ) else p.predictions snake_case: List[str] = np.argmax(__A , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: snake_case: str = default_data_collator elif training_args.fpaa: snake_case: List[str] = DataCollatorWithPadding(__A , pad_to_multiple_of=8 ) else: snake_case: List[Any] = None # Initialize our Trainer snake_case: List[str] = Trainer( model=__A , args=__A , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__A , tokenizer=__A , data_collator=__A , ) # Training if training_args.do_train: snake_case: Optional[int] = None if training_args.resume_from_checkpoint is not None: snake_case: str = training_args.resume_from_checkpoint elif last_checkpoint is not None: snake_case: Optional[Any] = last_checkpoint snake_case: Union[str, Any] = trainer.train(resume_from_checkpoint=__A ) snake_case: List[Any] = train_result.metrics snake_case: List[Any] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__A ) ) snake_case: Optional[Any] = min(__A , len(__A ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('train' , __A ) trainer.save_metrics('train' , __A ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) snake_case: Dict = trainer.evaluate(eval_dataset=__A ) snake_case: Optional[int] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__A ) snake_case: Dict = min(__A , len(__A ) ) trainer.log_metrics('eval' , __A ) trainer.save_metrics('eval' , __A ) if training_args.do_predict: logger.info('*** Predict ***' ) # Removing the `label` columns because it contains -1 and Trainer won't like that. snake_case: Optional[int] = predict_dataset.remove_columns('label' ) snake_case: str = trainer.predict(__A , metric_key_prefix='predict' ).predictions snake_case: Any = np.argmax(__A , axis=1 ) snake_case: int = os.path.join(training_args.output_dir , 'predict_results_tabfact.txt' ) if trainer.is_world_process_zero(): with open(__A , 'w' ) as writer: logger.info('***** Predict Results *****' ) writer.write('index\tprediction\n' ) for index, item in enumerate(__A ): snake_case: int = label_list[item] writer.write(f"""{index}\t{item}\n""" ) snake_case: Optional[int] = {'finetuned_from': model_args.model_name_or_path, 'tasks': 'text-classification'} if training_args.push_to_hub: trainer.push_to_hub(**__A ) else: trainer.create_model_card(**__A ) def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' main() if __name__ == "__main__": main()
692
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import 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 numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=13 , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=99 , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=2 , 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__=5_12 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=0 , ): '''simple docstring''' snake_case: int = parent snake_case: List[str] = batch_size snake_case: Optional[Any] = seq_length snake_case: Any = is_training snake_case: Optional[Any] = use_input_mask snake_case: List[str] = use_token_type_ids snake_case: Any = use_labels snake_case: Dict = vocab_size snake_case: str = hidden_size snake_case: str = num_hidden_layers snake_case: Union[str, Any] = num_attention_heads snake_case: Optional[Any] = intermediate_size snake_case: Union[str, Any] = hidden_act snake_case: List[Any] = hidden_dropout_prob snake_case: Any = attention_probs_dropout_prob snake_case: List[Any] = max_position_embeddings snake_case: Union[str, Any] = type_vocab_size snake_case: Any = type_sequence_label_size snake_case: Dict = initializer_range snake_case: List[str] = num_labels snake_case: Tuple = num_choices snake_case: Union[str, Any] = scope snake_case: Dict = projection_dim def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case: Optional[Any] = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py snake_case: List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case: Tuple = None if self.use_token_type_ids: snake_case: List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case: int = None snake_case: Optional[Any] = None snake_case: List[str] = None if self.use_labels: snake_case: int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case: str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case: Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) snake_case: List[str] = BertConfig( 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 , ) snake_case: List[str] = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = TFDPRContextEncoder(config=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) snake_case: str = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Union[str, Any] = TFDPRQuestionEncoder(config=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) snake_case: int = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[Any] = TFDPRReader(config=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = model(SCREAMING_SNAKE_CASE__ , attention_mask=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) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = self.prepare_config_and_inputs() ( ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ( snake_case ) , ): List[str] = config_and_inputs snake_case: Dict = {'input_ids': input_ids} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) __UpperCamelCase = {"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {} __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = TFDPRModelTester(self ) snake_case: Tuple = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def _UpperCamelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case: Optional[int] = TFDPRContextEncoder.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case: int = TFDPRContextEncoder.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case: Tuple = TFDPRQuestionEncoder.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case: List[str] = TFDPRReader.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = TFDPRQuestionEncoder.from_pretrained('facebook/dpr-question_encoder-single-nq-base' ) snake_case: Dict = tf.constant( [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]] ) # [CLS] hello, is my dog cute? [SEP] snake_case: List[Any] = model(SCREAMING_SNAKE_CASE__ )[0] # embedding shape = (1, 768) # compare the actual values for a slice. snake_case: str = tf.constant( [ [ 0.03_23_62_53, 0.12_75_33_35, 0.16_81_85_09, 0.00_27_97_86, 0.3_89_69_33, 0.24_26_49_45, 0.2_17_89_71, -0.02_33_52_27, -0.08_48_19_59, -0.14_32_41_17, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
692
'''simple docstring''' import math def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCAmelCase_ ( __A : float = 0.1 ): '''simple docstring''' snake_case: Optional[int] = 3 snake_case: int = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(__A ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''simple docstring''' from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow 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 TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=13 , SCREAMING_SNAKE_CASE__=30 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=2 , 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__=10 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=0.6 , SCREAMING_SNAKE_CASE__=None , ): '''simple docstring''' snake_case: Optional[int] = parent snake_case: List[Any] = batch_size snake_case: int = image_size snake_case: Optional[Any] = patch_size snake_case: str = num_channels snake_case: Optional[int] = is_training snake_case: Dict = use_labels snake_case: List[Any] = hidden_size snake_case: Optional[Any] = num_hidden_layers snake_case: Tuple = num_attention_heads snake_case: List[Any] = intermediate_size snake_case: List[str] = hidden_act snake_case: str = hidden_dropout_prob snake_case: Union[str, Any] = attention_probs_dropout_prob snake_case: Dict = type_sequence_label_size snake_case: str = initializer_range snake_case: Union[str, Any] = mask_ratio snake_case: Dict = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) snake_case: List[Any] = (image_size // patch_size) ** 2 snake_case: Optional[int] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case: List[Any] = None if self.use_labels: snake_case: Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case: List[Any] = self.get_config() return config, pixel_values, labels def _UpperCamelCase ( self ): '''simple docstring''' return ViTMAEConfig( 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 , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = TFViTMAEModel(config=SCREAMING_SNAKE_CASE__ ) snake_case: Any = model(SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = TFViTMAEForPreTraining(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = model(SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) # expected sequence length = num_patches snake_case: Any = (self.image_size // self.patch_size) ** 2 snake_case: Union[str, Any] = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images snake_case: Optional[int] = 1 snake_case: Union[str, Any] = TFViTMAEForPreTraining(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case: int = model(SCREAMING_SNAKE_CASE__ , training=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.prepare_config_and_inputs() ((snake_case) , (snake_case) , (snake_case)): int = config_and_inputs snake_case: str = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE ( snake_case , snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () __UpperCamelCase = {"feature-extraction": TFViTMAEModel} if is_tf_available() else {} __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = TFViTMAEModelTester(self ) snake_case: Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def _UpperCamelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='ViTMAE does not use inputs_embeds' ) def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case: Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case: Optional[int] = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) snake_case: Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , tf.keras.layers.Layer ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case , snake_case: Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case: Union[str, Any] = model_class(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case: Union[str, Any] = [*signature.parameters.keys()] snake_case: List[str] = ['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' np.random.seed(2 ) snake_case , snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case: List[str] = int((config.image_size // config.patch_size) ** 2 ) snake_case: List[str] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: snake_case: Optional[Any] = model_class(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = model(SCREAMING_SNAKE_CASE__ , noise=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = copy.deepcopy(self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) snake_case: Optional[Any] = model(**SCREAMING_SNAKE_CASE__ , noise=SCREAMING_SNAKE_CASE__ ) snake_case: Dict = outputs_dict[0].numpy() snake_case: Optional[int] = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1E-6 ) def _UpperCamelCase ( self ): '''simple docstring''' np.random.seed(2 ) snake_case , snake_case: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case: List[Any] = int((config.image_size // config.patch_size) ** 2 ) snake_case: int = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(SCREAMING_SNAKE_CASE__ ): snake_case: List[str] = {} for k, v in inputs_dict.items(): if tf.is_tensor(SCREAMING_SNAKE_CASE__ ): snake_case: Optional[Any] = v.numpy() else: snake_case: Tuple = np.array(SCREAMING_SNAKE_CASE__ ) return inputs_np_dict for model_class in self.all_model_classes: snake_case: Optional[int] = model_class(SCREAMING_SNAKE_CASE__ ) snake_case: str = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = prepare_numpy_arrays(SCREAMING_SNAKE_CASE__ ) snake_case: int = model(SCREAMING_SNAKE_CASE__ , noise=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = model(**SCREAMING_SNAKE_CASE__ , noise=SCREAMING_SNAKE_CASE__ ) self.assert_outputs_same(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' np.random.seed(2 ) snake_case: Optional[Any] = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) snake_case: Any = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) snake_case: str = tf.constant(SCREAMING_SNAKE_CASE__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument snake_case: Tuple = tf_noise super().check_pt_tf_models(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' np.random.seed(2 ) snake_case , snake_case: int = self.model_tester.prepare_config_and_inputs_for_common() snake_case: List[str] = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(SCREAMING_SNAKE_CASE__ ) if module_member_name.endswith('MainLayer' ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len('MainLayer' )] == model_class.__name__[: -len('Model' )] for module_member in (getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ),) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(SCREAMING_SNAKE_CASE__ , '_keras_serializable' , SCREAMING_SNAKE_CASE__ ) } snake_case: List[str] = int((config.image_size // config.patch_size) ** 2 ) snake_case: str = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) snake_case: Tuple = tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) inputs_dict.update({'noise': noise} ) for main_layer_class in tf_main_layer_classes: snake_case: Optional[int] = main_layer_class(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } snake_case: List[str] = tf.keras.Model(SCREAMING_SNAKE_CASE__ , outputs=main_layer(SCREAMING_SNAKE_CASE__ ) ) snake_case: Optional[Any] = model(SCREAMING_SNAKE_CASE__ ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case: Optional[int] = os.path.join(SCREAMING_SNAKE_CASE__ , 'keras_model.h5' ) model.save(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = tf.keras.models.load_model( SCREAMING_SNAKE_CASE__ , custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(SCREAMING_SNAKE_CASE__ , tf.keras.Model ) snake_case: Any = model(SCREAMING_SNAKE_CASE__ ) self.assert_outputs_same(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' np.random.seed(2 ) snake_case , snake_case: List[str] = self.model_tester.prepare_config_and_inputs_for_common() snake_case: Optional[int] = int((config.image_size // config.patch_size) ** 2 ) snake_case: Union[str, Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: snake_case: Dict = model_class(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = model(SCREAMING_SNAKE_CASE__ , noise=SCREAMING_SNAKE_CASE__ ) if model_class.__name__ == "TFViTMAEModel": snake_case: int = outputs.last_hidden_state.numpy() snake_case: Any = 0 else: snake_case: Any = outputs.logits.numpy() snake_case: Union[str, Any] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(SCREAMING_SNAKE_CASE__ , saved_model=SCREAMING_SNAKE_CASE__ ) snake_case: str = model_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Any = model(SCREAMING_SNAKE_CASE__ , noise=SCREAMING_SNAKE_CASE__ ) if model_class.__name__ == "TFViTMAEModel": snake_case: List[str] = after_outputs['last_hidden_state'].numpy() snake_case: Optional[Any] = 0 else: snake_case: Union[str, Any] = after_outputs['logits'].numpy() snake_case: List[Any] = 0 snake_case: Optional[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1E-5 ) def _UpperCamelCase ( self ): '''simple docstring''' np.random.seed(2 ) snake_case , snake_case: List[str] = self.model_tester.prepare_config_and_inputs_for_common() snake_case: str = int((config.image_size // config.patch_size) ** 2 ) snake_case: Union[str, Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: snake_case: Optional[Any] = model_class(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = model(SCREAMING_SNAKE_CASE__ , noise=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(SCREAMING_SNAKE_CASE__ ) snake_case: str = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config snake_case: str = model_class.from_config(model.config ) snake_case: Union[str, Any] = new_model(SCREAMING_SNAKE_CASE__ ) # Build model new_model.set_weights(model.get_weights() ) snake_case: Optional[Any] = new_model(SCREAMING_SNAKE_CASE__ , noise=SCREAMING_SNAKE_CASE__ ) self.assert_outputs_same(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @unittest.skip( reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results.' ) def _UpperCamelCase ( self ): '''simple docstring''' pass @unittest.skip(reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load' ) def _UpperCamelCase ( self ): '''simple docstring''' pass @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = TFViTMAEModel.from_pretrained('google/vit-base-patch16-224' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _UpperCamelCase ( self ): '''simple docstring''' return ViTImageProcessor.from_pretrained('facebook/vit-mae-base' ) if is_vision_available() else None @slow def _UpperCamelCase ( self ): '''simple docstring''' np.random.seed(2 ) snake_case: int = TFViTMAEForPreTraining.from_pretrained('facebook/vit-mae-base' ) snake_case: Dict = self.default_image_processor snake_case: Optional[Any] = prepare_img() snake_case: int = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) snake_case: Optional[int] = ViTMAEConfig() snake_case: Any = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) snake_case: int = np.random.uniform(size=(1, num_patches) ) # forward pass snake_case: Union[str, Any] = model(**SCREAMING_SNAKE_CASE__ , noise=SCREAMING_SNAKE_CASE__ ) # verify the logits snake_case: List[Any] = tf.convert_to_tensor([1, 1_96, 7_68] ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) snake_case: int = tf.convert_to_tensor( [[-0.05_48, -1.70_23, -0.93_25], [0.37_21, -0.56_70, -0.22_33], [0.82_35, -1.38_78, -0.35_24]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 )
692
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): __UpperCAmelCase = "pt" elif is_tf_available(): __UpperCAmelCase = "tf" else: __UpperCAmelCase = "jax" class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ByTaTokenizer __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: int = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _UpperCamelCase ( self ): '''simple docstring''' return ByTaTokenizer.from_pretrained('google/byt5-small' ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=20 , SCREAMING_SNAKE_CASE__=5 ): '''simple docstring''' snake_case: Optional[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): try: snake_case: Optional[Any] = tokenizer.decode([i] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) except UnicodeDecodeError: pass toks.append((i, tok) ) snake_case: List[str] = list(filter(lambda SCREAMING_SNAKE_CASE__ : re.match(r'^[ a-zA-Z]+$' , t[1] ) , SCREAMING_SNAKE_CASE__ ) ) snake_case: str = list(filter(lambda SCREAMING_SNAKE_CASE__ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) ) if max_length is not None and len(SCREAMING_SNAKE_CASE__ ) > max_length: snake_case: Union[str, Any] = 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: snake_case: Tuple = toks + toks # toks_str = [t[1] for t in toks] snake_case: Dict = [t[0] for t in toks] # Ensure consistency snake_case: int = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) if " " not in output_txt and len(SCREAMING_SNAKE_CASE__ ) > 1: snake_case: str = ( 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: snake_case: Tuple = ' ' + output_txt snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) return output_txt, output_ids def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: str = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) snake_case: List[Any] = tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: Union[str, Any] = 'Unicode €.' snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = [88, 1_13, 1_08, 1_02, 1_14, 1_03, 1_04, 35, 2_29, 1_33, 1_75, 49, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[str] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'Unicode €.</s>' ) snake_case: List[Any] = tokenizer('e è é ê ë' ) snake_case: Optional[Any] = [1_04, 35, 1_98, 1_71, 35, 1_98, 1_72, 35, 1_98, 1_73, 35, 1_98, 1_74, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.ta_base_tokenizer snake_case: Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off snake_case: Optional[int] = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 1, 0] # fmt: on snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if FRAMEWORK != "jax": snake_case: Optional[Any] = list(batch.input_ids.numpy()[0] ) else: snake_case: Dict = list(batch.input_ids.tolist()[0] ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.ta_base_tokenizer snake_case: List[str] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] snake_case: Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertIn('attention_mask' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_attention_mask' , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.ta_base_tokenizer snake_case: str = [ 'Summary of the text.', 'Another summary.', ] snake_case: Dict = tokenizer( text_target=SCREAMING_SNAKE_CASE__ , max_length=32 , padding='max_length' , truncation=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.ta_base_tokenizer snake_case: Optional[int] = ['A long paragraph for summarization. </s>'] snake_case: str = ['Summary of the text. </s>'] # fmt: off snake_case: str = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 35, 1] snake_case: Optional[int] = [86, 1_20, 1_12, 1_12, 1_00, 1_17, 1_24, 35, 1_14, 1_05, 35, 1_19, 1_07, 1_04, 35, 1_19, 1_04, 1_23, 1_19, 49, 35, 1] # fmt: on snake_case: List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ , text_target=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['input_ids'][0] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['labels'][0] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test snake_case: Optional[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: Union[str, Any] = tempfile.mkdtemp() snake_case: Dict = ' He is very happy, UNwant\u00E9d,running' snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Any = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: List[str] = tempfile.mkdtemp() snake_case: str = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) snake_case: List[str] = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) snake_case: int = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) snake_case: Union[str, Any] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: snake_case: Any = json.load(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: snake_case: str = json.load(SCREAMING_SNAKE_CASE__ ) snake_case: int = [F"""<extra_id_{i}>""" for i in range(1_25 )] snake_case: Optional[int] = added_tokens_extra_ids + [ 'an_additional_special_token' ] snake_case: str = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files snake_case: Dict = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained snake_case: Union[str, Any] = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=SCREAMING_SNAKE_CASE__ )] snake_case: Union[str, Any] = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.decode([2_55] ) == '' ) def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_tokenizers(fast=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Union[str, Any] = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] snake_case: List[str] = tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Optional[Any] = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] snake_case: Dict = 0 snake_case: List[Any] = tokenizer.convert_ids_to_tokens( SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) for attr in attributes_list: setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [] ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
692
1
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = RoCBertTokenizer __UpperCamelCase = None __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = filter_non_english def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: Any = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '你', '好', '是', '谁', 'a', 'b', 'c', 'd'] snake_case: List[Any] = {} snake_case: List[str] = {} for i, value in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = i snake_case: Union[str, Any] = i snake_case: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) snake_case: Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] ) snake_case: str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: Dict = tokenizer.tokenize('你好[SEP]你是谁' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['你', '好', '[SEP]', '你', '是', '谁'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] snake_case: Union[str, Any] = {} for i, token in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: str = i snake_case: Optional[int] = RoCBertWordpieceTokenizer(vocab=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) if self.test_rust_tokenizer: snake_case: int = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) def _UpperCamelCase ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" snake_case: List[str] = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , ) snake_case: Optional[int] = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE__ , 'do_lower_case' ) else False snake_case: int = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'Allen'), ((21, 23), '##NL'), ((23, 24), '##P'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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, 15), tokenizer_r.mask_token), ((16, 21), 'allen'), ((21, 23), '##nl'), ((23, 24), '##p'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = ['的', '人', '有'] snake_case: Any = ''.join(SCREAMING_SNAKE_CASE__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = True snake_case: List[Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = False snake_case: Union[str, Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: int = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that only the first Chinese character is not preceded by "##". snake_case: Union[str, Any] = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE__ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: int = tokenizer.encode('你好' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Any = tokenizer.encode('你是谁' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Dict = '你好,你是谁' snake_case: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer.prepare_for_model( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.encode_plus(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
692
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = "layer_norm" , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__() snake_case: List[str] = only_cross_attention snake_case: Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero' snake_case: Tuple = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to""" F""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""" ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: snake_case: List[str] = AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: snake_case: str = AdaLayerNormZero(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: snake_case: int = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = Attention( query_dim=SCREAMING_SNAKE_CASE__ , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. snake_case: Tuple = ( AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) ) snake_case: Any = Attention( query_dim=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # is self-attn if encoder_hidden_states is none else: snake_case: int = None snake_case: Tuple = None # 3. Feed-forward snake_case: Union[str, Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = FeedForward(SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , activation_fn=SCREAMING_SNAKE_CASE__ , final_dropout=SCREAMING_SNAKE_CASE__ ) # let chunk size default to None snake_case: Any = None snake_case: Any = 0 def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = chunk_size snake_case: str = dim def _UpperCamelCase ( 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 , ): '''simple docstring''' if self.use_ada_layer_norm: snake_case: Optional[int] = self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: snake_case , snake_case , snake_case , snake_case , snake_case: int = self.norma( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=hidden_states.dtype ) else: snake_case: List[str] = self.norma(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = cross_attention_kwargs if cross_attention_kwargs is not None else {} snake_case: List[str] = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if self.use_ada_layer_norm_zero: snake_case: Tuple = gate_msa.unsqueeze(1 ) * attn_output snake_case: List[str] = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: snake_case: Dict = ( self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else self.norma(SCREAMING_SNAKE_CASE__ ) ) snake_case: Any = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case: List[str] = attn_output + hidden_states # 3. Feed-forward snake_case: str = self.norma(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: snake_case: str = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""" ) snake_case: List[str] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size snake_case: Optional[Any] = torch.cat( [self.ff(SCREAMING_SNAKE_CASE__ ) for hid_slice in norm_hidden_states.chunk(SCREAMING_SNAKE_CASE__ , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: snake_case: int = self.ff(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: snake_case: Union[str, Any] = gate_mlp.unsqueeze(1 ) * ff_output snake_case: Tuple = ff_output + hidden_states return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 4 , SCREAMING_SNAKE_CASE__ = 0.0 , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__() snake_case: int = int(dim * mult ) snake_case: Optional[Any] = dim_out if dim_out is not None else dim if activation_fn == "gelu": snake_case: int = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if activation_fn == "gelu-approximate": snake_case: Optional[Any] = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , approximate='tanh' ) elif activation_fn == "geglu": snake_case: List[Any] = GEGLU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif activation_fn == "geglu-approximate": snake_case: Optional[int] = ApproximateGELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Any = nn.ModuleList([] ) # project in self.net.append(SCREAMING_SNAKE_CASE__ ) # project dropout self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) # project out self.net.append(nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' for module in self.net: snake_case: Optional[int] = module(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "none" ): '''simple docstring''' super().__init__() snake_case: Optional[int] = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = approximate def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.proj(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = self.gelu(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = nn.Linear(SCREAMING_SNAKE_CASE__ , dim_out * 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case , snake_case: int = self.proj(SCREAMING_SNAKE_CASE__ ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = self.proj(SCREAMING_SNAKE_CASE__ ) return x * torch.sigmoid(1.7_02 * x ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Optional[Any] = nn.Embedding(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = nn.SiLU() snake_case: Union[str, Any] = nn.Linear(SCREAMING_SNAKE_CASE__ , embedding_dim * 2 ) snake_case: int = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ ) ) ) snake_case , snake_case: Dict = torch.chunk(SCREAMING_SNAKE_CASE__ , 2 ) snake_case: str = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale) + shift return x class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = CombinedTimestepLabelEmbeddings(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.SiLU() snake_case: Any = nn.Linear(SCREAMING_SNAKE_CASE__ , 6 * embedding_dim , bias=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ , eps=1E-6 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' snake_case: int = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=SCREAMING_SNAKE_CASE__ ) ) ) snake_case , snake_case , snake_case , snake_case , snake_case , snake_case: str = emb.chunk(6 , dim=1 ) snake_case: Dict = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 1E-5 ): '''simple docstring''' super().__init__() snake_case: str = num_groups snake_case: str = eps if act_fn is None: snake_case: Dict = None else: snake_case: List[str] = get_activation(SCREAMING_SNAKE_CASE__ ) snake_case: Any = nn.Linear(SCREAMING_SNAKE_CASE__ , out_dim * 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.act: snake_case: Optional[Any] = self.act(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.linear(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = emb[:, :, None, None] snake_case , snake_case: List[Any] = emb.chunk(2 , dim=1 ) snake_case: Any = F.group_norm(SCREAMING_SNAKE_CASE__ , self.num_groups , eps=self.eps ) snake_case: Optional[int] = x * (1 + scale) + shift return x
692
1
'''simple docstring''' from math import asin, atan, cos, radians, sin, sqrt, tan __UpperCAmelCase = 6378137.0 __UpperCAmelCase = 6356752.314245 __UpperCAmelCase = 6_378_137 def lowerCAmelCase_ ( __A : float , __A : float , __A : float , __A : float ): '''simple docstring''' snake_case: Optional[Any] = (AXIS_A - AXIS_B) / AXIS_A snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: Tuple = radians(__A ) snake_case: Tuple = radians(__A ) # Equation snake_case: List[Any] = sin((phi_a - phi_a) / 2 ) snake_case: Dict = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda snake_case: Union[str, Any] = sqrt(sin_sq_phi + (cos(__A ) * cos(__A ) * sin_sq_lambda) ) return 2 * RADIUS * asin(__A ) if __name__ == "__main__": import doctest doctest.testmod()
692
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = RoCBertTokenizer __UpperCamelCase = None __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = filter_non_english def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: Any = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '你', '好', '是', '谁', 'a', 'b', 'c', 'd'] snake_case: List[Any] = {} snake_case: List[str] = {} for i, value in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = i snake_case: Union[str, Any] = i snake_case: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) snake_case: Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] ) snake_case: str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: Dict = tokenizer.tokenize('你好[SEP]你是谁' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['你', '好', '[SEP]', '你', '是', '谁'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] snake_case: Union[str, Any] = {} for i, token in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: str = i snake_case: Optional[int] = RoCBertWordpieceTokenizer(vocab=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) if self.test_rust_tokenizer: snake_case: int = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) def _UpperCamelCase ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" snake_case: List[str] = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , ) snake_case: Optional[int] = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE__ , 'do_lower_case' ) else False snake_case: int = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'Allen'), ((21, 23), '##NL'), ((23, 24), '##P'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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, 15), tokenizer_r.mask_token), ((16, 21), 'allen'), ((21, 23), '##nl'), ((23, 24), '##p'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = ['的', '人', '有'] snake_case: Any = ''.join(SCREAMING_SNAKE_CASE__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = True snake_case: List[Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = False snake_case: Union[str, Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: int = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that only the first Chinese character is not preceded by "##". snake_case: Union[str, Any] = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE__ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: int = tokenizer.encode('你好' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Any = tokenizer.encode('你是谁' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Dict = '你好,你是谁' snake_case: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer.prepare_for_model( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.encode_plus(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
692
1
'''simple docstring''' from sklearn.metrics import mean_squared_error import datasets __UpperCAmelCase = "\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n" __UpperCAmelCase = "\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n" __UpperCAmelCase = "\nArgs:\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n sample_weight: array-like of shape (n_samples,), default=None\n Sample weights.\n multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n \"raw_values\" : Returns a full set of errors in case of multioutput input.\n\n \"uniform_average\" : Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n mse : mean squared error.\nExamples:\n\n >>> mse_metric = datasets.load_metric(\"mse\")\n >>> predictions = [2.5, 0.0, 2, 8]\n >>> references = [3, -0.5, 2, 7]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'mse': 0.375}\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n >>> print(rmse_result)\n {'mse': 0.6123724356957945}\n\n If you're using multi-dimensional lists, then set the config as follows :\n\n >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n >>> references = [[0, 2], [-1, 2], [8, -5]]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'mse': 0.7083333333333334}\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {'mse': array([0.41666667, 1. ])}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ 'https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html' ] , ) def _UpperCamelCase ( self ): '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('float' ) ), "references": datasets.Sequence(datasets.Value('float' ) ), } else: return { "predictions": datasets.Value('float' ), "references": datasets.Value('float' ), } def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__="uniform_average" , SCREAMING_SNAKE_CASE__=True ): '''simple docstring''' snake_case: Optional[Any] = mean_squared_error( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , sample_weight=SCREAMING_SNAKE_CASE__ , multioutput=SCREAMING_SNAKE_CASE__ , squared=SCREAMING_SNAKE_CASE__ ) return {"mse": mse}
692
'''simple docstring''' from math import asin, atan, cos, radians, sin, sqrt, tan __UpperCAmelCase = 6378137.0 __UpperCAmelCase = 6356752.314245 __UpperCAmelCase = 6_378_137 def lowerCAmelCase_ ( __A : float , __A : float , __A : float , __A : float ): '''simple docstring''' snake_case: Optional[Any] = (AXIS_A - AXIS_B) / AXIS_A snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: Tuple = radians(__A ) snake_case: Tuple = radians(__A ) # Equation snake_case: List[Any] = sin((phi_a - phi_a) / 2 ) snake_case: Dict = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda snake_case: Union[str, Any] = sqrt(sin_sq_phi + (cos(__A ) * cos(__A ) * sin_sq_lambda) ) return 2 * RADIUS * asin(__A ) if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''simple docstring''' def lowerCAmelCase_ ( __A : int = 3 , __A : int = 7 , __A : int = 1_00_00_00 ): '''simple docstring''' snake_case: Optional[int] = 0 snake_case: Optional[int] = 1 for current_denominator in range(1 , limit + 1 ): snake_case: List[Any] = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: snake_case: Any = current_numerator snake_case: str = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1_000_000))
692
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCAmelCase = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' warnings.warn( 'The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use DeformableDetrImageProcessor instead.' , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
692
'''simple docstring''' import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def lowerCAmelCase_ ( __A : Tuple ): '''simple docstring''' snake_case: Tuple = model.config snake_case: str = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=1_28 , ) snake_case: Optional[Any] = MBartConfig( is_decoder=__A , is_encoder_decoder=__A , add_cross_attention=__A , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=__A , add_final_layer_norm=__A , ) return encoder_config, decoder_config def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if "encoder.model" in name: snake_case: Optional[Any] = name.replace('encoder.model' , 'encoder' ) if "decoder.model" in name: snake_case: str = name.replace('decoder.model' , 'decoder' ) if "patch_embed.proj" in name: snake_case: Any = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: snake_case: Optional[int] = name.replace('patch_embed.norm' , 'embeddings.norm' ) if name.startswith('encoder' ): if "layers" in name: snake_case: Tuple = 'encoder.' + name if "attn.proj" in name: snake_case: Optional[int] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name and "mask" not in name: snake_case: Dict = name.replace('attn' , 'attention.self' ) if "norm1" in name: snake_case: Union[str, Any] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: snake_case: Dict = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: snake_case: List[str] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: snake_case: Dict = name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": snake_case: Dict = 'encoder.layernorm.weight' if name == "encoder.norm.bias": snake_case: int = 'encoder.layernorm.bias' return name def lowerCAmelCase_ ( __A : List[Any] , __A : Optional[Any] ): '''simple docstring''' for key in orig_state_dict.copy().keys(): snake_case: List[Any] = orig_state_dict.pop(__A ) if "qkv" in key: snake_case: Union[str, Any] = key.split('.' ) snake_case: Optional[Any] = int(key_split[3] ) snake_case: Any = int(key_split[5] ) snake_case: Union[str, Any] = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: snake_case: Union[str, Any] = val[:dim, :] snake_case: Any = val[dim : dim * 2, :] snake_case: List[str] = val[-dim:, :] else: snake_case: str = val[:dim] snake_case: Union[str, Any] = val[dim : dim * 2] snake_case: List[Any] = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: snake_case: Optional[int] = val return orig_state_dict def lowerCAmelCase_ ( __A : List[Any] , __A : Any=None , __A : List[str]=False ): '''simple docstring''' snake_case: str = DonutModel.from_pretrained(__A ).eval() # load HuggingFace model snake_case , snake_case: Optional[Any] = get_configs(__A ) snake_case: Optional[int] = DonutSwinModel(__A ) snake_case: Tuple = MBartForCausalLM(__A ) snake_case: Optional[Any] = VisionEncoderDecoderModel(encoder=__A , decoder=__A ) model.eval() snake_case: Optional[int] = original_model.state_dict() snake_case: Optional[int] = convert_state_dict(__A , __A ) model.load_state_dict(__A ) # verify results on scanned document snake_case: Union[str, Any] = load_dataset('hf-internal-testing/example-documents' ) snake_case: str = dataset['test'][0]['image'].convert('RGB' ) snake_case: Optional[int] = XLMRobertaTokenizerFast.from_pretrained(__A , from_slow=__A ) snake_case: Any = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) snake_case: Dict = DonutProcessor(__A , __A ) snake_case: Optional[Any] = processor(__A , return_tensors='pt' ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": snake_case: int = '<s_docvqa><s_question>{user_input}</s_question><s_answer>' snake_case: Optional[Any] = 'When is the coffee break?' snake_case: Optional[int] = task_prompt.replace('{user_input}' , __A ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": snake_case: Dict = '<s_rvlcdip>' elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: snake_case: str = '<s_cord>' elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": snake_case: str = 's_cord-v2>' elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": snake_case: int = '<s_zhtrainticket>' elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt snake_case: Optional[Any] = 'hello world' else: raise ValueError('Model name not supported' ) snake_case: Optional[int] = original_model.decoder.tokenizer(__A , add_special_tokens=__A , return_tensors='pt' )[ 'input_ids' ] snake_case: Any = original_model.encoder.model.patch_embed(__A ) snake_case , snake_case: Dict = model.encoder.embeddings(__A ) assert torch.allclose(__A , __A , atol=1E-3 ) # verify encoder hidden states snake_case: Tuple = original_model.encoder(__A ) snake_case: List[str] = model.encoder(__A ).last_hidden_state assert torch.allclose(__A , __A , atol=1E-2 ) # verify decoder hidden states snake_case: List[Any] = original_model(__A , __A , __A ).logits snake_case: List[Any] = model(__A , decoder_input_ids=__A ).logits assert torch.allclose(__A , __A , atol=1E-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(__A ) processor.save_pretrained(__A ) if push_to_hub: model.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) processor.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) __UpperCAmelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
692
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json", } class SCREAMING_SNAKE_CASE ( snake_case , snake_case ): '''simple docstring''' __UpperCamelCase = "focalnet" def __init__( self , SCREAMING_SNAKE_CASE__=2_24 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=96 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=[1_92, 3_84, 7_68, 7_68] , SCREAMING_SNAKE_CASE__=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE__=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE__=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=4.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=1E-4 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = image_size snake_case: Tuple = patch_size snake_case: str = num_channels snake_case: Dict = embed_dim snake_case: str = use_conv_embed snake_case: Tuple = hidden_sizes snake_case: int = depths snake_case: List[str] = focal_levels snake_case: Any = focal_windows snake_case: Any = hidden_act snake_case: Optional[int] = mlp_ratio snake_case: List[str] = hidden_dropout_prob snake_case: Optional[Any] = drop_path_rate snake_case: Dict = use_layerscale snake_case: Union[str, Any] = layerscale_value snake_case: List[Any] = use_post_layernorm snake_case: int = use_post_layernorm_in_modulation snake_case: Optional[Any] = normalize_modulator snake_case: int = initializer_range snake_case: Union[str, Any] = layer_norm_eps snake_case: Optional[int] = encoder_stride snake_case: Any = ['stem'] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] snake_case , snake_case: List[str] = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE__ , out_indices=SCREAMING_SNAKE_CASE__ , stage_names=self.stage_names )
692
'''simple docstring''' 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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = { 'task_specific_params': { 'summarization': {'length_penalty': 1.0, 'max_length': 1_28, 'min_length': 12, 'num_beams': 4}, 'summarization_cnn': {'length_penalty': 2.0, 'max_length': 1_42, 'min_length': 56, 'num_beams': 4}, 'summarization_xsum': {'length_penalty': 1.0, 'max_length': 62, 'min_length': 11, 'num_beams': 6}, } } snake_case: Union[str, Any] = { 'task_specific_params.summarization.length_penalty': 1.0, 'task_specific_params.summarization.max_length': 1_28, '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': 1_42, '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(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , x.transpose() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = np.random.randn(3 , 4 ) snake_case: Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(3 , 4 , 5 ) snake_case: Optional[int] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Dict = np.random.randn(3 , 4 , 5 ) snake_case: str = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Optional[int] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Optional[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) snake_case: Optional[int] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: str = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: List[str] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.squeeze(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: List[str] = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) snake_case: List[str] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: int = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = np.random.randn(1 , 3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Union[str, Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(1 , 3 , 4 ) snake_case: List[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Tuple = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Tuple = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Any = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Any = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = np.random.randn(3 , 4 ) snake_case: int = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.asarray(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) )
692
1
'''simple docstring''' def lowerCAmelCase_ ( __A : Any=2_81_23 ): '''simple docstring''' snake_case: Optional[int] = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i snake_case: Dict = set() snake_case: Tuple = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(__A ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
692
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig __UpperCAmelCase = logging.get_logger(__name__) # General docstring __UpperCAmelCase = "PoolFormerConfig" # Base docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = [1, 512, 7, 7] # Image classification docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = "tabby, tabby cat" __UpperCAmelCase = [ "sail/poolformer_s12", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCAmelCase_ ( __A : Tuple , __A : float = 0.0 , __A : bool = False ): '''simple docstring''' if drop_prob == 0.0 or not training: return input snake_case: Union[str, Any] = 1 - drop_prob snake_case: List[Any] = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets snake_case: List[Any] = keep_prob + torch.rand(__A , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize snake_case: Any = input.div(__A ) * random_tensor return output class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' super().__init__() snake_case: List[str] = drop_prob def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return drop_path(SCREAMING_SNAKE_CASE__ , self.drop_prob , self.training ) def _UpperCamelCase ( self ): '''simple docstring''' return "p={}".format(self.drop_prob ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' super().__init__() snake_case: List[str] = patch_size if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (patch_size, patch_size) snake_case: List[str] = stride if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (stride, stride) snake_case: Union[str, Any] = padding if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (padding, padding) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , kernel_size=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = norm_layer(SCREAMING_SNAKE_CASE__ ) if norm_layer else nn.Identity() def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.projection(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.norm(SCREAMING_SNAKE_CASE__ ) return embeddings class SCREAMING_SNAKE_CASE ( nn.GroupNorm ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(1 , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.AvgPoolad(SCREAMING_SNAKE_CASE__ , stride=1 , padding=pool_size // 2 , count_include_pad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.pool(SCREAMING_SNAKE_CASE__ ) - hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: str = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if isinstance(config.hidden_act , SCREAMING_SNAKE_CASE__ ): snake_case: Tuple = ACTaFN[config.hidden_act] else: snake_case: int = config.hidden_act def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.act_fn(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.drop(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: str = self.drop(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = PoolFormerPooling(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerOutput(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) # Useful for training neural nets snake_case: Union[str, Any] = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if drop_path > 0.0 else nn.Identity() snake_case: Optional[Any] = config.use_layer_scale if config.use_layer_scale: snake_case: Any = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.use_layer_scale: snake_case: str = self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Dict = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection snake_case: str = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = () snake_case: Dict = self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Union[str, Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection snake_case: Any = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = (output,) + outputs return outputs else: snake_case: Optional[Any] = self.drop_path(self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) ) # First residual connection snake_case: Union[str, Any] = pooling_output + hidden_states snake_case: List[Any] = () # Second residual connection inside the PoolFormerOutput block snake_case: List[str] = self.drop_path(self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: Dict = hidden_states + layer_output snake_case: Optional[Any] = (output,) + outputs return outputs class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = config # stochastic depth decay rule snake_case: List[Any] = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings snake_case: Union[str, Any] = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) snake_case: List[Any] = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) # Transformer blocks snake_case: str = [] snake_case: int = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers snake_case: List[str] = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( SCREAMING_SNAKE_CASE__ , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(SCREAMING_SNAKE_CASE__ ) ) snake_case: Tuple = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True ): '''simple docstring''' snake_case: str = () if output_hidden_states else None snake_case: Dict = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): snake_case , snake_case: Dict = layers # Get patch embeddings from hidden_states snake_case: int = embedding_layer(SCREAMING_SNAKE_CASE__ ) # Send the embeddings through the blocks for _, blk in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = blk(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = layer_outputs[0] if output_hidden_states: snake_case: List[str] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = PoolFormerConfig __UpperCamelCase = "poolformer" __UpperCamelCase = "pixel_values" __UpperCamelCase = True def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = value __UpperCAmelCase = R"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" __UpperCAmelCase = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n" @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = config snake_case: Tuple = PoolFormerEncoder(SCREAMING_SNAKE_CASE__ ) # Initialize weights and apply final processing self.post_init() def _UpperCamelCase ( self ): '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Optional[int] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case: List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) snake_case: Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: List[Any] = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=encoder_outputs.hidden_states , ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Any = nn.Linear(config.hidden_size , config.hidden_size ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.dense(SCREAMING_SNAKE_CASE__ ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = config.num_labels snake_case: str = PoolFormerModel(SCREAMING_SNAKE_CASE__ ) # Final norm snake_case: int = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head snake_case: Dict = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict snake_case: Optional[Any] = self.poolformer( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: Any = outputs[0] snake_case: str = self.classifier(self.norm(SCREAMING_SNAKE_CASE__ ).mean([-2, -1] ) ) snake_case: Any = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: snake_case: Tuple = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): snake_case: Dict = 'single_label_classification' else: snake_case: List[str] = 'multi_label_classification' if self.config.problem_type == "regression": snake_case: Union[str, Any] = MSELoss() if self.num_labels == 1: snake_case: List[str] = loss_fct(logits.squeeze() , labels.squeeze() ) else: snake_case: int = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.config.problem_type == "single_label_classification": snake_case: Union[str, Any] = CrossEntropyLoss() snake_case: Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": snake_case: int = BCEWithLogitsLoss() snake_case: Optional[int] = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not return_dict: snake_case: str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=SCREAMING_SNAKE_CASE__ , logits=SCREAMING_SNAKE_CASE__ , hidden_states=outputs.hidden_states )
692
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCAmelCase = { "configuration_rag": ["RagConfig"], "retrieval_rag": ["RagRetriever"], "tokenization_rag": ["RagTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "RagModel", "RagPreTrainedModel", "RagSequenceForGeneration", "RagTokenForGeneration", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "TFRagModel", "TFRagPreTrainedModel", "TFRagSequenceForGeneration", "TFRagTokenForGeneration", ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def lowerCAmelCase_ ( __A : dict , __A : str , __A : set , __A : set , __A : dict , __A : dict , __A : PriorityQueue , __A : dict , __A : float | int , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue snake_case: Any = cst_fwd.get(__A , np.inf ) snake_case: int = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) snake_case: Union[str, Any] = new_cost_f snake_case: Tuple = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: snake_case: List[str] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def lowerCAmelCase_ ( __A : str , __A : str , __A : dict , __A : dict ): '''simple docstring''' snake_case: Optional[Any] = -1 snake_case: Any = set() snake_case: str = set() snake_case: int = {source: 0} snake_case: Dict = {destination: 0} snake_case: int = {source: None} snake_case: Union[str, Any] = {destination: None} snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: Tuple = 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(): snake_case , snake_case: List[str] = queue_forward.get() visited_forward.add(__A ) snake_case , snake_case: int = queue_backward.get() visited_backward.add(__A ) snake_case: str = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) snake_case: Optional[Any] = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: snake_case: Any = shortest_distance return shortest_path_distance __UpperCAmelCase = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } __UpperCAmelCase = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
692
1
'''simple docstring''' import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = CanineTokenizer __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: List[Any] = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _UpperCamelCase ( self ): '''simple docstring''' return CanineTokenizer.from_pretrained('google/canine-s' ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) snake_case: Any = 10_24 return tokenizer @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.canine_tokenizer snake_case: Union[str, Any] = ['Life is like a box of chocolates.', 'You never know what you\'re gonna get.'] # fmt: off snake_case: Any = [5_73_44, 76, 1_05, 1_02, 1_01, 32, 1_05, 1_15, 32, 1_08, 1_05, 1_07, 1_01, 32, 97, 32, 98, 1_11, 1_20, 32, 1_11, 1_02, 32, 99, 1_04, 1_11, 99, 1_11, 1_08, 97, 1_16, 1_01, 1_15, 46, 5_73_45, 0, 0, 0, 0] # fmt: on snake_case: List[str] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.canine_tokenizer snake_case: Optional[Any] = ['Once there was a man.', 'He wrote a test in HuggingFace Tranformers.'] snake_case: Optional[Any] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn('input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertIn('attention_mask' , SCREAMING_SNAKE_CASE__ ) self.assertIn('token_type_ids' , SCREAMING_SNAKE_CASE__ ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.canine_tokenizer snake_case: List[str] = [ 'What\'s the weater?', 'It\'s about 25 degrees.', ] snake_case: int = tokenizer( text_target=SCREAMING_SNAKE_CASE__ , max_length=32 , padding='max_length' , truncation=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test snake_case: str = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: List[str] = tempfile.mkdtemp() snake_case: Union[str, Any] = ' He is very happy, UNwant\u00E9d,running' snake_case: Dict = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: int = tempfile.mkdtemp() snake_case: Tuple = ' He is very happy, UNwant\u00E9d,running' snake_case: str = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: snake_case: Optional[int] = chr(0xe_007 ) additional_special_tokens.append(SCREAMING_SNAKE_CASE__ ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) snake_case: Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertIn(SCREAMING_SNAKE_CASE__ , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) snake_case: Tuple = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case , snake_case: Any = self.get_clean_sequence(SCREAMING_SNAKE_CASE__ ) # a special token for Canine can be defined as follows: snake_case: Optional[int] = 0xe_005 snake_case: List[str] = chr(SCREAMING_SNAKE_CASE__ ) tokenizer.add_special_tokens({'cls_token': special_token} ) snake_case: Dict = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1 ) snake_case: List[Any] = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , input_encoded + special_token_id ) snake_case: Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertTrue(special_token not in decoded ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Union[str, Any] = chr(0xe_005 ) snake_case: Optional[int] = chr(0xe_006 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=SCREAMING_SNAKE_CASE__ ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({'additional_special_tokens': [SPECIAL_TOKEN_2]} ) snake_case: Optional[Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1 ) self.assertEqual(token_a[0] , SCREAMING_SNAKE_CASE__ ) self.assertEqual(token_a[0] , SCREAMING_SNAKE_CASE__ ) @require_tokenizers def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # a special token for Canine can be defined as follows: snake_case: Union[str, Any] = 0xe_006 snake_case: Tuple = chr(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ ) tokenizer.add_special_tokens({'additional_special_tokens': [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) tokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: snake_case: int = json.load(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: snake_case: Any = json.load(SCREAMING_SNAKE_CASE__ ) # a special token for Canine can be defined as follows: snake_case: Union[str, Any] = 0xe_006 snake_case: int = chr(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = [new_token_a] snake_case: Dict = [new_token_a] with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files snake_case: Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , extra_ids=0 ) self.assertIn(SCREAMING_SNAKE_CASE__ , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) snake_case: Optional[Any] = 0xe_007 snake_case: Dict = chr(SCREAMING_SNAKE_CASE__ ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained snake_case: int = [AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ )] snake_case: str = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , extra_ids=0 ) self.assertIn(SCREAMING_SNAKE_CASE__ , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: List[Any] = 'hello world' if self.space_between_special_tokens: snake_case: List[str] = '[CLS] hello world [SEP]' else: snake_case: Dict = input snake_case: Union[str, Any] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.decode(SCREAMING_SNAKE_CASE__ , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(SCREAMING_SNAKE_CASE__ , [output, output.lower()] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: str = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] snake_case: Optional[Any] = 'a' snake_case: List[str] = ord(SCREAMING_SNAKE_CASE__ ) for attr in attributes_list: setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [] ) snake_case: List[Any] = 0xe_006 snake_case: List[Any] = chr(SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [additional_special_token_id] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [additional_special_token] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [additional_special_token_id] ) def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass
692
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = "▁" __UpperCAmelCase = {"vocab_file": "sentencepiece.bpe.model"} __UpperCAmelCase = { "vocab_file": { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model", } } __UpperCAmelCase = { "facebook/xglm-564M": 2_048, } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer snake_case: Optional[Any] = 7 snake_case: List[str] = [F"""<madeupword{i}>""" for i in range(self.num_madeup_words )] snake_case: str = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) snake_case: int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) snake_case: int = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab snake_case: Tuple = 1 # Mimic fairseq token-to-id alignment for the first 4 token snake_case: Optional[Any] = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} snake_case: Union[str, Any] = len(self.sp_model ) snake_case: str = {F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ): '''simple docstring''' snake_case: List[Any] = self.__dict__.copy() snake_case: Union[str, Any] = None snake_case: Union[str, Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): snake_case: Union[str, Any] = {} snake_case: Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a snake_case: Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' snake_case: int = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def _UpperCamelCase ( self ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case: Dict = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip() return out_string def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case: List[str] = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: snake_case: int = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
692
1
'''simple docstring''' import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer __UpperCAmelCase = "bart" __UpperCAmelCase = True @st.cache(allow_output_mutation=__A ) def lowerCAmelCase_ ( ): '''simple docstring''' if LOAD_DENSE_INDEX: snake_case: Any = AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased' ) snake_case: Any = AutoModel.from_pretrained('yjernite/retribert-base-uncased' ).to('cuda:0' ) snake_case: List[str] = qar_model.eval() else: snake_case , snake_case: Dict = (None, None) if MODEL_TYPE == "bart": snake_case: List[Any] = AutoTokenizer.from_pretrained('yjernite/bart_eli5' ) snake_case: Optional[int] = AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5' ).to('cuda:0' ) snake_case: str = torch.load('seq2seq_models/eli5_bart_model_blm_2.pth' ) sas_model.load_state_dict(save_dict['model'] ) snake_case: Dict = sas_model.eval() else: snake_case , snake_case: str = make_qa_sas_model( model_name='t5-small' , from_file='seq2seq_models/eli5_t5_model_1024_4.pth' , device='cuda:0' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=__A ) def lowerCAmelCase_ ( ): '''simple docstring''' if LOAD_DENSE_INDEX: snake_case: Tuple = faiss.StandardGpuResources() snake_case: List[Any] = datasets.load_dataset(path='wiki_snippets' , name='wiki40b_en_100_0' )['train'] snake_case: int = np.memmap( 'wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat' , dtype='float32' , mode='r' , shape=(wikiaab_passages.num_rows, 1_28) , ) snake_case: List[str] = faiss.IndexFlatIP(1_28 ) snake_case: List[Any] = faiss.index_cpu_to_gpu(__A , 1 , __A ) wikiaab_gpu_index_flat.add(__A ) # TODO fix for larger GPU else: snake_case , snake_case: Optional[Any] = (None, None) snake_case: List[Any] = Elasticsearch([{'host': 'localhost', 'port': '9200'}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=__A ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: str = datasets.load_dataset('eli5' , name='LFQA_reddit' ) snake_case: Optional[int] = elia['train_eli5'] snake_case: Optional[Any] = np.memmap( 'eli5_questions_reps.dat' , dtype='float32' , mode='r' , shape=(elia_train.num_rows, 1_28) ) snake_case: List[str] = faiss.IndexFlatIP(1_28 ) eli5_train_q_index.add(__A ) return (elia_train, eli5_train_q_index) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = load_indexes() __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = load_models() __UpperCAmelCase , __UpperCAmelCase = load_train_data() def lowerCAmelCase_ ( __A : Union[str, Any] , __A : List[Any]=10 ): '''simple docstring''' snake_case: List[Any] = embed_questions_for_retrieval([question] , __A , __A ) snake_case , snake_case: Optional[int] = eli5_train_q_index.search(__A , __A ) snake_case: Optional[int] = [elia_train[int(__A )] for i in I[0]] return nn_examples def lowerCAmelCase_ ( __A : List[str] , __A : Dict="wiki40b" , __A : Optional[Any]="dense" , __A : Union[str, Any]=10 ): '''simple docstring''' if source == "none": snake_case , snake_case: List[str] = (' <P> '.join(['' for _ in range(11 )] ).strip(), []) else: if method == "dense": snake_case , snake_case: Optional[Any] = query_qa_dense_index( __A , __A , __A , __A , __A , __A ) else: snake_case , snake_case: Any = query_es_index( __A , __A , index_name='english_wiki40b_snippets_100w' , n_results=__A , ) snake_case: Union[str, Any] = [ (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst ] snake_case: Dict = 'question: {} context: {}'.format(__A , __A ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda __A : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda __A : None), } ) def lowerCAmelCase_ ( __A : Tuple , __A : Optional[int] , __A : str , __A : List[str]=64 , __A : Any=2_56 , __A : Dict=False , __A : Optional[Any]=2 , __A : List[str]=0.95 , __A : Any=0.8 ): '''simple docstring''' with torch.no_grad(): snake_case: Optional[Any] = qa_sas_generate( __A , __A , __A , num_answers=1 , num_beams=__A , min_len=__A , max_len=__A , do_sample=__A , temp=__A , top_p=__A , top_k=__A , max_input_length=10_24 , device='cuda:0' , )[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar __UpperCAmelCase = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" __UpperCAmelCase = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia __UpperCAmelCase = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) __UpperCAmelCase = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] __UpperCAmelCase = st.sidebar.checkbox("Demo options") if demo_options: __UpperCAmelCase = st.sidebar.selectbox( "", action_list, index=3, ) __UpperCAmelCase = action_list.index(action_st) __UpperCAmelCase = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) __UpperCAmelCase = show_type == "Show full text of passages" else: __UpperCAmelCase = 3 __UpperCAmelCase = True __UpperCAmelCase = st.sidebar.checkbox("Retrieval options") if retrieval_options: __UpperCAmelCase = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) __UpperCAmelCase = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) __UpperCAmelCase = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: __UpperCAmelCase = "wiki40b" __UpperCAmelCase = "dense" __UpperCAmelCase = "beam" __UpperCAmelCase = 2 __UpperCAmelCase = 64 __UpperCAmelCase = 256 __UpperCAmelCase = None __UpperCAmelCase = None __UpperCAmelCase = st.sidebar.checkbox("Generation options") if generate_options: __UpperCAmelCase = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) __UpperCAmelCase = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) __UpperCAmelCase = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) __UpperCAmelCase = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": __UpperCAmelCase = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: __UpperCAmelCase = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) __UpperCAmelCase = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) __UpperCAmelCase = None # start main text __UpperCAmelCase = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] __UpperCAmelCase = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": __UpperCAmelCase = st.text_input("Enter your question here:", "") else: __UpperCAmelCase = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": __UpperCAmelCase , __UpperCAmelCase = make_support(question, source=wiki_source, method="dense", n_results=10) __UpperCAmelCase , __UpperCAmelCase = make_support(question, source=wiki_source, method="sparse", n_results=10) __UpperCAmelCase = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] __UpperCAmelCase = support_list[:10] __UpperCAmelCase = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: __UpperCAmelCase , __UpperCAmelCase = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: __UpperCAmelCase , __UpperCAmelCase = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): __UpperCAmelCase = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) __UpperCAmelCase = res[1].strip() if sec_titles == "": __UpperCAmelCase = "[{}]({})".format(res[0], wiki_url) else: __UpperCAmelCase = sec_titles.split(" & ") __UpperCAmelCase = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: __UpperCAmelCase = find_nearest_training(question) __UpperCAmelCase = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) __UpperCAmelCase = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) __UpperCAmelCase = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
692
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' return getitem, k def lowerCAmelCase_ ( __A : Any , __A : Optional[int] ): '''simple docstring''' return setitem, k, v def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' return delitem, k def lowerCAmelCase_ ( __A : str , __A : int , *__A : Tuple ): '''simple docstring''' try: return fun(__A , *__A ), None except Exception as e: return None, e __UpperCAmelCase = ( _set("key_a", "val_a"), _set("key_b", "val_b"), ) __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_a", "val_b"), ] __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_b", "val_b"), _del("key_a"), _del("key_b"), _set("key_a", "val_a"), _del("key_a"), ] __UpperCAmelCase = [ _get("key_a"), _del("key_a"), _set("key_a", "val_a"), _del("key_a"), _del("key_a"), _get("key_a"), ] __UpperCAmelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] __UpperCAmelCase = [ *[_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 lowerCAmelCase_ ( __A : str ): '''simple docstring''' snake_case: List[Any] = HashMap(initial_block_size=4 ) snake_case: List[Any] = {} for _, (fun, *args) in enumerate(__A ): snake_case , snake_case: Optional[int] = _run_operation(__A , __A , *__A ) snake_case , snake_case: str = _run_operation(__A , __A , *__A ) assert my_res == py_res assert str(__A ) == str(__A ) assert set(__A ) == set(__A ) assert len(__A ) == len(__A ) assert set(my.items() ) == set(py.items() ) def lowerCAmelCase_ ( ): '''simple docstring''' def is_public(__A : str ) -> bool: return not name.startswith('_' ) snake_case: Dict = {name for name in dir({} ) if is_public(__A )} snake_case: List[str] = {name for name in dir(HashMap() ) if is_public(__A )} assert dict_public_names > hash_public_names
692
1
'''simple docstring''' def lowerCAmelCase_ ( __A : str , __A : list[str] ): '''simple docstring''' snake_case: Optional[int] = '' for word_or_phrase in separated: if not isinstance(__A , __A ): raise Exception('join() accepts only strings to be joined' ) joined += word_or_phrase + separator return joined.strip(__A ) if __name__ == "__main__": from doctest import testmod testmod()
692
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "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": "lm_head", "mask_emb": "masked_spec_embed", } __UpperCAmelCase = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def lowerCAmelCase_ ( __A : Any , __A : Optional[Any] , __A : Union[str, Any] , __A : int , __A : Optional[int] ): '''simple docstring''' for attribute in key.split('.' ): snake_case: List[str] = getattr(__A , __A ) if weight_type is not None: snake_case: Optional[int] = getattr(__A , __A ).shape else: snake_case: Optional[int] = 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": snake_case: Optional[int] = value elif weight_type == "weight_g": snake_case: List[str] = value elif weight_type == "weight_v": snake_case: Dict = value elif weight_type == "bias": snake_case: Optional[Any] = value else: snake_case: int = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def lowerCAmelCase_ ( __A : List[Any] , __A : List[str] ): '''simple docstring''' snake_case: List[Any] = [] snake_case: List[Any] = fairseq_model.state_dict() snake_case: Union[str, Any] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight snake_case: Dict = None for name, value in fairseq_dict.items(): snake_case: Tuple = False if "conv_layers" in name: load_conv_layer( __A , __A , __A , __A , hf_model.config.feat_extract_norm == 'group' , ) snake_case: List[Any] = True elif name.split('.' )[0] == "proj": snake_case: List[Any] = fairseq_model.proj snake_case: int = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: snake_case: int = True if "*" in mapped_key: snake_case: List[str] = name.split(__A )[0].split('.' )[-2] snake_case: Dict = mapped_key.replace('*' , __A ) if "weight_g" in name: snake_case: Tuple = 'weight_g' elif "weight_v" in name: snake_case: int = 'weight_v' elif "bias" in name: snake_case: Tuple = 'bias' elif "weight" in name: snake_case: List[Any] = 'weight' else: snake_case: Any = None set_recursively(__A , __A , __A , __A , __A ) continue if not is_used: unused_weights.append(__A ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCAmelCase_ ( __A : List[str] , __A : List[Any] , __A : int , __A : Optional[Any] , __A : Optional[int] ): '''simple docstring''' snake_case: int = full_name.split('conv_layers.' )[-1] snake_case: Tuple = name.split('.' ) snake_case: Any = int(items[0] ) snake_case: Optional[int] = 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.""" ) snake_case: Tuple = 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.""" ) snake_case: int = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) snake_case: Any = 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.""" ) snake_case: str = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__A ) def lowerCAmelCase_ ( __A : Dict ): '''simple docstring''' snake_case , snake_case: List[Any] = emb.weight.shape snake_case: Optional[int] = nn.Linear(__A , __A , bias=__A ) snake_case: Any = emb.weight.data return lin_layer def lowerCAmelCase_ ( __A : Optional[int] ): '''simple docstring''' with open(__A , 'r' , encoding='utf-8' ) as f: snake_case: List[Any] = f.readlines() snake_case: Any = [line.split(' ' )[0] for line in lines] snake_case: int = len(__A ) snake_case: Dict = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(__A , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCAmelCase_ ( __A : Optional[Any] , __A : Union[str, Any] , __A : Dict , __A : Any , __A : List[Any] , __A : int , __A : str , ): '''simple docstring''' snake_case: Union[str, Any] = WavaVecaConfig.from_pretrained(__A ) snake_case: str = SpeechaTextaConfig.from_pretrained( __A , vocab_size=__A , decoder_layers=__A , do_stable_layer_norm=__A ) snake_case: List[str] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=__A , return_attention_mask=__A , ) snake_case , snake_case , snake_case: List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) snake_case: List[Any] = model[0].eval() # set weights for wav2vec2 encoder snake_case: Optional[Any] = WavaVecaModel(__A ) snake_case: Any = recursively_load_weights_wavaveca(model.encoder , __A ) snake_case: Union[str, Any] = SpeechaTextaForCausalLM(__A ) snake_case , snake_case: Optional[Any] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__A ) # set output linear layer unexpected_keys.remove('embed_out' ) snake_case: str = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) snake_case: int = SpeechEncoderDecoderModel(encoder=__A , decoder=__A ) snake_case: List[Any] = False # add projection layer snake_case: Union[str, Any] = nn.Parameter(projection_layer.weight ) snake_case: Union[str, Any] = nn.Parameter(projection_layer.bias ) snake_case: List[Any] = create_vocab_dict(__A ) with open(os.path.join(__A , 'vocab.json' ) , 'w' ) as fp: json.dump(__A , __A ) snake_case: Union[str, Any] = SpeechaTextaTokenizer(os.path.join(__A , 'vocab.json' ) ) tokenizer.save_pretrained(__A ) snake_case: Tuple = hf_wavavec.config.to_dict() snake_case: int = tokenizer.pad_token_id snake_case: Dict = tokenizer.bos_token_id snake_case: Optional[int] = tokenizer.eos_token_id snake_case: Dict = 'speech_to_text_2' snake_case: Optional[Any] = 'wav2vec2' snake_case: Tuple = SpeechEncoderDecoderConfig.from_dict(__A ) hf_wavavec.save_pretrained(__A ) feature_extractor.save_pretrained(__A ) if __name__ == "__main__": __UpperCAmelCase = 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( "--encoder_config_path", default="facebook/wav2vec2-large-lv60", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/s2t-small-mustc-en-fr-st", type=str, help="Path to hf decoder s2t checkpoint config", ) parser.add_argument("--vocab_size", default=10_224, type=int, help="Vocab size of decoder") parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers") __UpperCAmelCase = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
692
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version __UpperCAmelCase = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt") __UpperCAmelCase = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) __UpperCAmelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = field( default="cifar10" , metadata={"help": "Name of a dataset from the datasets package"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "The column name of the images in the files. If not set, will try to use 'image' or 'img'."} , ) __UpperCamelCase = field(default=snake_case , metadata={"help": "A folder containing the training data."} ) __UpperCamelCase = field(default=snake_case , metadata={"help": "A folder containing the validation data."} ) __UpperCamelCase = field( default=0.15 , metadata={"help": "Percent to split off of train for validation."} ) __UpperCamelCase = field(default=32 , metadata={"help": "The size of the square patches to use for masking."} ) __UpperCamelCase = field( default=0.6 , metadata={"help": "Percentage of patches to mask."} , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = {} if self.train_dir is not None: snake_case: Tuple = self.train_dir if self.validation_dir is not None: snake_case: str = self.validation_dir snake_case: int = data_files if data_files else None @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a " "checkpoint identifier on the hub. " "Don't set if you want to train a model from scratch." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(snake_case )} , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "Override some existing default config settings when a model is trained from scratch. Example: " "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index" ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Where do you want to store (cache) the pretrained models/datasets downloaded from the hub"} , ) __UpperCamelCase = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __UpperCamelCase = field(default=snake_case , metadata={"help": "Name or path of preprocessor config."} ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "The size (resolution) of each image. If not specified, will use `image_size` of the configuration." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Stride to use for the encoder."} , ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__=1_92 , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=0.6 ): '''simple docstring''' snake_case: str = input_size snake_case: Dict = mask_patch_size snake_case: List[str] = model_patch_size snake_case: List[Any] = mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError('Input size must be divisible by mask patch size' ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError('Mask patch size must be divisible by model patch size' ) snake_case: Union[str, Any] = self.input_size // self.mask_patch_size snake_case: Dict = self.mask_patch_size // self.model_patch_size snake_case: str = self.rand_size**2 snake_case: Optional[int] = int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self ): '''simple docstring''' snake_case: Tuple = np.random.permutation(self.token_count )[: self.mask_count] snake_case: List[Any] = np.zeros(self.token_count , dtype=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = 1 snake_case: Optional[int] = mask.reshape((self.rand_size, self.rand_size) ) snake_case: int = mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def lowerCAmelCase_ ( __A : int ): '''simple docstring''' snake_case: Union[str, Any] = torch.stack([example['pixel_values'] for example in examples] ) snake_case: List[str] = torch.stack([example['mask'] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: int = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case , snake_case , snake_case: Tuple = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case , snake_case , snake_case: Any = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_mim' , __A , __A ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() snake_case: Optional[int] = training_args.get_process_log_level() logger.setLevel(__A ) transformers.utils.logging.set_verbosity(__A ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. snake_case: Optional[Any] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case: int = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Initialize our dataset. snake_case: List[str] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. snake_case: int = None if 'validation' in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __A ) and data_args.train_val_split > 0.0: snake_case: List[Any] = ds['train'].train_test_split(data_args.train_val_split ) snake_case: str = split['train'] snake_case: Optional[int] = split['test'] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case: Optional[int] = { 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name_or_path: snake_case: List[str] = AutoConfig.from_pretrained(model_args.config_name_or_path , **__A ) elif model_args.model_name_or_path: snake_case: int = AutoConfig.from_pretrained(model_args.model_name_or_path , **__A ) else: snake_case: Any = CONFIG_MAPPING[model_args.model_type]() logger.warning('You are instantiating a new config instance from scratch.' ) if model_args.config_overrides is not None: logger.info(f"""Overriding config: {model_args.config_overrides}""" ) config.update_from_string(model_args.config_overrides ) logger.info(f"""New config: {config}""" ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(__A , 'decoder_type' ): snake_case: int = 'simmim' # adapt config snake_case: int = model_args.image_size if model_args.image_size is not None else config.image_size snake_case: Union[str, Any] = model_args.patch_size if model_args.patch_size is not None else config.patch_size snake_case: Optional[Any] = ( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { 'image_size': model_args.image_size, 'patch_size': model_args.patch_size, 'encoder_stride': model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: snake_case: Union[str, Any] = AutoImageProcessor.from_pretrained(model_args.image_processor_name , **__A ) elif model_args.model_name_or_path: snake_case: str = AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **__A ) else: snake_case: Dict = { conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } snake_case: Optional[int] = IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: snake_case: Optional[Any] = AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=__A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info('Training new model from scratch' ) snake_case: int = AutoModelForMaskedImageModeling.from_config(__A ) if training_args.do_train: snake_case: Any = ds['train'].column_names else: snake_case: str = ds['validation'].column_names if data_args.image_column_name is not None: snake_case: Tuple = data_args.image_column_name elif "image" in column_names: snake_case: List[Any] = 'image' elif "img" in column_names: snake_case: Optional[int] = 'img' else: snake_case: Optional[Any] = column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py snake_case: List[Any] = Compose( [ Lambda(lambda __A : img.convert('RGB' ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.67, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator snake_case: List[Any] = MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(__A : str ): snake_case: Optional[Any] = [transforms(__A ) for image in examples[image_column_name]] snake_case: Optional[Any] = [mask_generator() for i in range(len(examples[image_column_name] ) )] return examples if training_args.do_train: if "train" not in ds: raise ValueError('--do_train requires a train dataset' ) if data_args.max_train_samples is not None: snake_case: Any = ds['train'].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__A ) if training_args.do_eval: if "validation" not in ds: raise ValueError('--do_eval requires a validation dataset' ) if data_args.max_eval_samples is not None: snake_case: Optional[Any] = ( ds['validation'].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__A ) # Initialize our trainer snake_case: Optional[int] = Trainer( model=__A , args=__A , train_dataset=ds['train'] if training_args.do_train else None , eval_dataset=ds['validation'] if training_args.do_eval else None , tokenizer=__A , data_collator=__A , ) # Training if training_args.do_train: snake_case: Dict = None if training_args.resume_from_checkpoint is not None: snake_case: Union[str, Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: snake_case: Optional[Any] = last_checkpoint snake_case: int = trainer.train(resume_from_checkpoint=__A ) trainer.save_model() trainer.log_metrics('train' , train_result.metrics ) trainer.save_metrics('train' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: snake_case: Dict = trainer.evaluate() trainer.log_metrics('eval' , __A ) trainer.save_metrics('eval' , __A ) # Write model card and (optionally) push to hub snake_case: str = { 'finetuned_from': model_args.model_name_or_path, 'tasks': 'masked-image-modeling', 'dataset': data_args.dataset_name, 'tags': ['masked-image-modeling'], } if training_args.push_to_hub: trainer.push_to_hub(**__A ) else: trainer.create_model_card(**__A ) if __name__ == "__main__": main()
692
'''simple docstring''' def lowerCAmelCase_ ( __A : int = 1_00 ): '''simple docstring''' snake_case: List[str] = n * (n + 1) * (2 * n + 1) / 6 snake_case: List[Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F'{solution() = }')
692
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 __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "sail/poolformer_s12": "https://huggingface.co/sail/poolformer_s12/resolve/main/config.json", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = "poolformer" def __init__( self , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=4.0 , SCREAMING_SNAKE_CASE__=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE__=[64, 1_28, 3_20, 5_12] , SCREAMING_SNAKE_CASE__=[7, 3, 3, 3] , SCREAMING_SNAKE_CASE__=[4, 2, 2, 2] , SCREAMING_SNAKE_CASE__=[2, 1, 1, 1] , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=0.02 , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: Optional[Any] = num_channels snake_case: Optional[Any] = patch_size snake_case: Union[str, Any] = stride snake_case: List[str] = padding snake_case: List[Any] = pool_size snake_case: str = hidden_sizes snake_case: int = mlp_ratio snake_case: Optional[Any] = depths snake_case: Tuple = patch_sizes snake_case: Dict = strides snake_case: List[str] = num_encoder_blocks snake_case: List[Any] = drop_path_rate snake_case: int = hidden_act snake_case: List[Any] = use_layer_scale snake_case: Any = layer_scale_init_value snake_case: Dict = initializer_range super().__init__(**SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = version.parse("1.11" ) @property def _UpperCamelCase ( self ): '''simple docstring''' return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _UpperCamelCase ( self ): '''simple docstring''' return 2E-3
692
'''simple docstring''' import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration __UpperCAmelCase = [ # tf -> hf ("/", "."), ("layer_", "layers."), ("kernel", "weight"), ("beta", "bias"), ("gamma", "weight"), ("pegasus", "model"), ] __UpperCAmelCase = [ (".output.dense", ".fc2"), ("intermediate.LayerNorm", "final_layer_norm"), ("intermediate.dense", "fc1"), ] __UpperCAmelCase = ( INIT_COMMON + [ ("attention.self.LayerNorm", "self_attn_layer_norm"), ("attention.output.dense", "self_attn.out_proj"), ("attention.self", "self_attn"), ("attention.encdec.LayerNorm", "encoder_attn_layer_norm"), ("attention.encdec_output.dense", "encoder_attn.out_proj"), ("attention.encdec", "encoder_attn"), ("key", "k_proj"), ("value", "v_proj"), ("query", "q_proj"), ("decoder.LayerNorm", "decoder.layernorm_embedding"), ] + END_COMMON ) __UpperCAmelCase = ( INIT_COMMON + [ ("embeddings.word_embeddings", "shared.weight"), ("embeddings.position_embeddings", "embed_positions.weight"), ("attention.self.LayerNorm", "self_attn_layer_norm"), ("attention.output.dense", "self_attn.output"), ("attention.self", "self_attn.self"), ("encoder.LayerNorm", "encoder.layernorm_embedding"), ] + END_COMMON ) __UpperCAmelCase = [ "encdec/key/bias", "encdec/query/bias", "encdec/value/bias", "self/key/bias", "self/query/bias", "self/value/bias", "encdec_output/dense/bias", "attention/output/dense/bias", ] def lowerCAmelCase_ ( __A : Dict , __A : List[Any] ): '''simple docstring''' for tf_name, hf_name in patterns: snake_case: List[Any] = k.replace(__A , __A ) return k def lowerCAmelCase_ ( __A : dict , __A : dict ): '''simple docstring''' snake_case: Optional[int] = BigBirdPegasusConfig(**__A ) snake_case: List[Any] = BigBirdPegasusForConditionalGeneration(__A ) snake_case: Any = torch_model.state_dict() snake_case: Any = {} # separating decoder weights snake_case: Optional[Any] = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder' )} snake_case: Any = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder' )} for k, v in tqdm(decoder_weights.items() , 'tf -> hf conversion' ): snake_case: List[str] = [k.endswith(__A ) for ending in KEYS_TO_IGNORE] if any(__A ): continue snake_case: Any = DECODER_PATTERNS snake_case: int = rename_state_dict_key(__A , __A ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): snake_case: Optional[Any] = v.T snake_case: Any = torch.from_numpy(__A ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items() , 'tf -> hf conversion' ): snake_case: List[Any] = [k.endswith(__A ) for ending in KEYS_TO_IGNORE] if any(__A ): continue snake_case: Union[str, Any] = REMAINING_PATTERNS snake_case: str = rename_state_dict_key(__A , __A ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): snake_case: int = v.T snake_case: Any = torch.from_numpy(__A ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" snake_case: str = mapping['model.embed_positions.weight'] snake_case: Any = mapping.pop('model.embed_positions.weight' ) snake_case , snake_case: Union[str, Any] = torch_model.load_state_dict(__A , strict=__A ) snake_case: Optional[int] = [ k for k in missing if k not in [ 'final_logits_bias', 'model.encoder.embed_tokens.weight', 'model.decoder.embed_tokens.weight', 'lm_head.weight', ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def lowerCAmelCase_ ( __A : Optional[int] ): '''simple docstring''' snake_case: Tuple = tf.train.list_variables(__A ) snake_case: str = {} snake_case: List[str] = ['global_step'] for name, shape in tqdm(__A , desc='converting tf checkpoint to dict' ): snake_case: str = any(pat in name for pat in ignore_name ) if skip_key: continue snake_case: Any = tf.train.load_variable(__A , __A ) snake_case: Optional[int] = array return tf_weights def lowerCAmelCase_ ( __A : str , __A : str , __A : dict ): '''simple docstring''' snake_case: int = get_tf_weights_as_numpy(__A ) snake_case: int = convert_bigbird_pegasus(__A , __A ) torch_model.save_pretrained(__A ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("--tf_ckpt_path", type=str, help="passed to tf.train.list_variables") parser.add_argument("--save_dir", default=None, type=str, help="Path to the output PyTorch model.") __UpperCAmelCase = parser.parse_args() __UpperCAmelCase = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
692
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __UpperCAmelCase = { "configuration_vision_encoder_decoder": ["VisionEncoderDecoderConfig", "VisionEncoderDecoderOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["VisionEncoderDecoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["TFVisionEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["FlaxVisionEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
'''simple docstring''' def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' snake_case: str = [0] * len(__A ) snake_case: Tuple = [] snake_case: Tuple = [1] * len(__A ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__A ) ): if indegree[i] == 0: queue.append(__A ) while queue: snake_case: int = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: snake_case: Any = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(__A ) print(max(__A ) ) # Adjacency list of Graph __UpperCAmelCase = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
692
1
'''simple docstring''' from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = ["image_processor", "tokenizer"] __UpperCamelCase = "BlipImageProcessor" __UpperCamelCase = "AutoTokenizer" def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Dict = self.image_processor def __call__( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 0 , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None: snake_case: List[Any] = self.tokenizer snake_case: List[str] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) return text_encoding # add pixel_values snake_case: int = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) if text is not None: snake_case: Tuple = self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) else: snake_case: Any = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__ ) return encoding_image_processor def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.tokenizer.model_input_names snake_case: Union[str, Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
692
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = tempfile.mkdtemp() snake_case: Optional[Any] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '的', '价', '格', '是', '15', '便', 'alex', '##andra', ',', '。', '-', 't', 'shirt', ] snake_case: Optional[Any] = 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] ) ) snake_case: Optional[int] = { 'do_resize': True, 'size': {'height': 2_24, 'width': 2_24}, 'do_center_crop': True, 'crop_size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], 'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], 'do_convert_rgb': True, } snake_case: Union[str, Any] = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE__ ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] snake_case: Tuple = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_tokenizer() snake_case: Union[str, Any] = self.get_rust_tokenizer() snake_case: Union[str, Any] = self.get_image_processor() snake_case: List[str] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_slow.save_pretrained(self.tmpdirname ) snake_case: List[str] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE__ ) snake_case: Any = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) processor_fast.save_pretrained(self.tmpdirname ) snake_case: Optional[int] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case: Optional[int] = self.get_tokenizer(cls_token='(CLS)' , sep_token='(SEP)' ) snake_case: Union[str, Any] = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='(CLS)' , sep_token='(SEP)' , do_normalize=SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.get_image_processor() snake_case: Tuple = self.get_tokenizer() snake_case: Optional[Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.prepare_image_inputs() snake_case: List[Any] = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) snake_case: Dict = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_image_processor() snake_case: Optional[int] = self.get_tokenizer() snake_case: List[Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = 'Alexandra,T-shirt的价格是15便士。' snake_case: Union[str, Any] = processor(text=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer(SCREAMING_SNAKE_CASE__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_image_processor() snake_case: Dict = self.get_tokenizer() snake_case: Optional[int] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Dict = 'Alexandra,T-shirt的价格是15便士。' snake_case: Tuple = self.prepare_image_inputs() snake_case: Any = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE__ ): processor() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.get_image_processor() snake_case: str = self.get_tokenizer() snake_case: Union[str, Any] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] snake_case: int = processor.batch_decode(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_image_processor() snake_case: Dict = self.get_tokenizer() snake_case: Optional[int] = ChineseCLIPProcessor(tokenizer=SCREAMING_SNAKE_CASE__ , image_processor=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = 'Alexandra,T-shirt的价格是15便士。' snake_case: List[Any] = self.prepare_image_inputs() snake_case: Dict = processor(text=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
692
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor __UpperCAmelCase = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' warnings.warn( 'The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use ChineseCLIPImageProcessor instead.' , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
692
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "microsoft/swinv2-tiny-patch4-window8-256": ( "https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json" ), } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = "swinv2" __UpperCamelCase = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , SCREAMING_SNAKE_CASE__=2_24 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=96 , SCREAMING_SNAKE_CASE__=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE__=[3, 6, 12, 24] , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=4.0 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-5 , SCREAMING_SNAKE_CASE__=32 , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case: int = image_size snake_case: Union[str, Any] = patch_size snake_case: List[str] = num_channels snake_case: Tuple = embed_dim snake_case: str = depths snake_case: Any = len(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = num_heads snake_case: Optional[int] = window_size snake_case: Any = mlp_ratio snake_case: Optional[int] = qkv_bias snake_case: Union[str, Any] = hidden_dropout_prob snake_case: List[str] = attention_probs_dropout_prob snake_case: Dict = drop_path_rate snake_case: List[str] = hidden_act snake_case: int = use_absolute_embeddings snake_case: Any = layer_norm_eps snake_case: Dict = initializer_range snake_case: List[Any] = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model snake_case: Tuple = int(embed_dim * 2 ** (len(SCREAMING_SNAKE_CASE__ ) - 1) ) snake_case: Union[str, Any] = (0, 0, 0, 0)
692
1
'''simple docstring''' import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) set_seed(770) __UpperCAmelCase = { "c_attn": "att_proj", "c_proj": "out_proj", "c_fc": "in_proj", "transformer.": "", "h.": "layers.", "ln_1": "layernorm_1", "ln_2": "layernorm_2", "ln_f": "layernorm_final", "wpe": "position_embeds_layer", "wte": "input_embeds_layer", } __UpperCAmelCase = { "text_small": { "repo_id": "suno/bark", "file_name": "text.pt", }, "coarse_small": { "repo_id": "suno/bark", "file_name": "coarse.pt", }, "fine_small": { "repo_id": "suno/bark", "file_name": "fine.pt", }, "text": { "repo_id": "suno/bark", "file_name": "text_2.pt", }, "coarse": { "repo_id": "suno/bark", "file_name": "coarse_2.pt", }, "fine": { "repo_id": "suno/bark", "file_name": "fine_2.pt", }, } __UpperCAmelCase = os.path.dirname(os.path.abspath(__file__)) __UpperCAmelCase = os.path.join(os.path.expanduser("~"), ".cache") __UpperCAmelCase = os.path.join(os.getenv("XDG_CACHE_HOME", default_cache_dir), "suno", "bark_v0") def lowerCAmelCase_ ( __A : List[str] , __A : Tuple=False ): '''simple docstring''' snake_case: str = model_type if use_small: key += "_small" return os.path.join(__A , REMOTE_MODEL_PATHS[key]['file_name'] ) def lowerCAmelCase_ ( __A : Dict , __A : str ): '''simple docstring''' os.makedirs(__A , exist_ok=__A ) hf_hub_download(repo_id=__A , filename=__A , local_dir=__A ) def lowerCAmelCase_ ( __A : str , __A : Optional[Any] , __A : Union[str, Any]=False , __A : Union[str, Any]="text" ): '''simple docstring''' if model_type == "text": snake_case: Union[str, Any] = BarkSemanticModel snake_case: str = BarkSemanticConfig snake_case: Union[str, Any] = BarkSemanticGenerationConfig elif model_type == "coarse": snake_case: Any = BarkCoarseModel snake_case: Tuple = BarkCoarseConfig snake_case: List[Any] = BarkCoarseGenerationConfig elif model_type == "fine": snake_case: Union[str, Any] = BarkFineModel snake_case: Union[str, Any] = BarkFineConfig snake_case: str = BarkFineGenerationConfig else: raise NotImplementedError() snake_case: int = f"""{model_type}_small""" if use_small else model_type snake_case: List[Any] = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(__A ): logger.info(f"""{model_type} model not found, downloading into `{CACHE_DIR}`.""" ) _download(model_info['repo_id'] , model_info['file_name'] ) snake_case: Dict = torch.load(__A , map_location=__A ) # this is a hack snake_case: Tuple = checkpoint['model_args'] if "input_vocab_size" not in model_args: snake_case: List[Any] = model_args['vocab_size'] snake_case: int = model_args['vocab_size'] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments snake_case: Dict = model_args.pop('n_head' ) snake_case: Tuple = model_args.pop('n_embd' ) snake_case: List[Any] = model_args.pop('n_layer' ) snake_case: Any = ConfigClass(**checkpoint['model_args'] ) snake_case: Tuple = ModelClass(config=__A ) snake_case: int = GenerationConfigClass() snake_case: List[str] = model_generation_config snake_case: Optional[Any] = checkpoint['model'] # fixup checkpoint snake_case: List[Any] = '_orig_mod.' for k, v in list(state_dict.items() ): if k.startswith(__A ): # replace part of the key with corresponding layer name in HF implementation snake_case: Union[str, Any] = k[len(__A ) :] for old_layer_name in new_layer_name_dict: snake_case: Optional[int] = new_k.replace(__A , new_layer_name_dict[old_layer_name] ) snake_case: Optional[int] = state_dict.pop(__A ) snake_case: Union[str, Any] = set(state_dict.keys() ) - set(model.state_dict().keys() ) snake_case: List[Any] = {k for k in extra_keys if not k.endswith('.attn.bias' )} snake_case: Dict = set(model.state_dict().keys() ) - set(state_dict.keys() ) snake_case: Tuple = {k for k in missing_keys if not k.endswith('.attn.bias' )} if len(__A ) != 0: raise ValueError(f"""extra keys found: {extra_keys}""" ) if len(__A ) != 0: raise ValueError(f"""missing keys: {missing_keys}""" ) model.load_state_dict(__A , strict=__A ) snake_case: int = model.num_parameters(exclude_embeddings=__A ) snake_case: int = checkpoint['best_val_loss'].item() logger.info(f"""model loaded: {round(n_params/1E6 , 1 )}M params, {round(__A , 3 )} loss""" ) model.eval() model.to(__A ) del checkpoint, state_dict return model def lowerCAmelCase_ ( __A : str , __A : int=False , __A : Union[str, Any]="text" ): '''simple docstring''' if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() snake_case: Dict = 'cpu' # do conversion on cpu snake_case: List[Any] = _get_ckpt_path(__A , use_small=__A ) snake_case: Tuple = _load_model(__A , __A , model_type=__A , use_small=__A ) # load bark initial model snake_case: List[str] = _bark_load_model(__A , 'cpu' , model_type=__A , use_small=__A ) if model_type == "text": snake_case: str = bark_model['model'] if model.num_parameters(exclude_embeddings=__A ) != bark_model.get_num_params(): raise ValueError('initial and new models don\'t have the same number of parameters' ) # check if same output as the bark model snake_case: List[Any] = 5 snake_case: str = 10 if model_type in ["text", "coarse"]: snake_case: List[Any] = torch.randint(2_56 , (batch_size, sequence_length) , dtype=torch.int ) snake_case: List[Any] = bark_model(__A )[0] snake_case: Optional[Any] = model(__A ) # take last logits snake_case: Optional[Any] = output_new_model_total.logits[:, [-1], :] else: snake_case: Optional[int] = 3 snake_case: str = 8 snake_case: Optional[Any] = torch.randint(2_56 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) snake_case: Optional[int] = model(__A , __A ) snake_case: Dict = bark_model(__A , __A ) snake_case: Any = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError('initial and new outputs don\'t have the same shape' ) if (output_new_model - output_old_model).abs().max().item() > 1E-3: raise ValueError('initial and new outputs are not equal' ) Path(__A ).mkdir(exist_ok=__A ) model.save_pretrained(__A ) def lowerCAmelCase_ ( __A : Optional[int] , __A : str , __A : int , __A : str , __A : Tuple , __A : Dict , ): '''simple docstring''' snake_case: List[Any] = os.path.join(__A , __A ) snake_case: List[Any] = BarkSemanticConfig.from_pretrained(os.path.join(__A , 'config.json' ) ) snake_case: Dict = BarkCoarseConfig.from_pretrained(os.path.join(__A , 'config.json' ) ) snake_case: Tuple = BarkFineConfig.from_pretrained(os.path.join(__A , 'config.json' ) ) snake_case: Tuple = EncodecConfig.from_pretrained('facebook/encodec_24khz' ) snake_case: Tuple = BarkSemanticModel.from_pretrained(__A ) snake_case: int = BarkCoarseModel.from_pretrained(__A ) snake_case: str = BarkFineModel.from_pretrained(__A ) snake_case: Tuple = EncodecModel.from_pretrained('facebook/encodec_24khz' ) snake_case: Optional[Any] = BarkConfig.from_sub_model_configs( __A , __A , __A , __A ) snake_case: Optional[Any] = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) snake_case: List[Any] = BarkModel(__A ) snake_case: Any = semantic snake_case: Union[str, Any] = coarseAcoustic snake_case: Tuple = fineAcoustic snake_case: Any = codec snake_case: str = bark_generation_config Path(__A ).mkdir(exist_ok=__A ) bark.save_pretrained(__A , repo_id=__A , push_to_hub=__A ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument("model_type", type=str, help="text, coarse or fine.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--is_small", action="store_true", help="convert the small version instead of the large.") __UpperCAmelCase = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
692
'''simple docstring''' import os import sys import unittest __UpperCAmelCase = 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_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __UpperCAmelCase = os.path.join(git_repo_path, "src", "transformers") __UpperCAmelCase = "\n{0} = None\n" __UpperCAmelCase = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n" __UpperCAmelCase = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n" class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = find_backend(' _import_structure["models.albert"].append("AlbertTokenizerFast")' ) self.assertIsNone(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = find_backend(' if not is_tokenizers_available():' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'tokenizers' ) snake_case: List[Any] = find_backend(' if not is_tensorflow_text_available():' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'tensorflow_text' ) snake_case: int = find_backend(' if not (is_sentencepiece_available() and is_tokenizers_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tokenizers' ) snake_case: Optional[Any] = find_backend( ' if not (is_sentencepiece_available() and is_tensorflow_text_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tensorflow_text' ) snake_case: Dict = find_backend( ' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'sentencepiece_and_tokenizers_and_vision' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('torch' , SCREAMING_SNAKE_CASE__ ) self.assertIn('tensorflow_text' , SCREAMING_SNAKE_CASE__ ) self.assertIn('sentencepiece_and_tokenizers' , SCREAMING_SNAKE_CASE__ ) # Likewise, we can't assert on the exact content of a key self.assertIn('BertModel' , objects['torch'] ) self.assertIn('TFBertModel' , objects['tf'] ) self.assertIn('FlaxBertModel' , objects['flax'] ) self.assertIn('BertModel' , objects['torch'] ) self.assertIn('TFBertTokenizer' , objects['tensorflow_text'] ) self.assertIn('convert_slow_tokenizer' , objects['sentencepiece_and_tokenizers'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = create_dummy_object('CONSTANT' , '\'torch\'' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , '\nCONSTANT = None\n' ) snake_case: Any = create_dummy_object('function' , '\'torch\'' ) self.assertEqual( SCREAMING_SNAKE_CASE__ , '\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n' ) snake_case: Optional[int] = '\nclass FakeClass(metaclass=DummyObject):\n _backends = \'torch\'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, \'torch\')\n' snake_case: Tuple = create_dummy_object('FakeClass' , '\'torch\'' ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = ["torch"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, ["torch"])\n' snake_case: Optional[int] = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} ) self.assertEqual(dummy_files['torch'] , SCREAMING_SNAKE_CASE__ )
692
1
'''simple docstring''' import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging __UpperCAmelCase = logging.get_logger(__name__) logging.set_verbosity_info() def lowerCAmelCase_ ( __A : str , __A : str ): '''simple docstring''' if "xprophetnet" in prophetnet_checkpoint_path: snake_case: Union[str, Any] = XLMProphetNetForConditionalGenerationOld.from_pretrained(__A ) snake_case , snake_case: Tuple = XLMProphetNetForConditionalGeneration.from_pretrained( __A , output_loading_info=__A ) else: snake_case: Optional[int] = ProphetNetForConditionalGenerationOld.from_pretrained(__A ) snake_case , snake_case: List[Any] = ProphetNetForConditionalGeneration.from_pretrained( __A , output_loading_info=__A ) snake_case: Optional[int] = ['key_proj', 'value_proj', 'query_proj'] snake_case: Optional[Any] = { 'self_attn': 'ngram_self_attn', 'cross_attn': 'encoder_attn', 'cross_attn_layer_norm': 'encoder_attn_layer_norm', 'feed_forward_layer_norm': 'final_layer_norm', 'feed_forward': '', 'intermediate': 'fc1', 'output': 'fc2', 'key_proj': 'k_proj', 'query_proj': 'q_proj', 'value_proj': 'v_proj', 'word_embeddings': 'embed_tokens', 'embeddings_layer_norm': 'emb_layer_norm', 'relative_pos_embeddings': 'relative_linear', 'ngram_embeddings': 'ngram_input_embed', 'position_embeddings': 'embed_positions', } for key in loading_info["missing_keys"]: snake_case: int = key.split('.' ) if attributes[0] == "lm_head": snake_case: List[str] = prophet snake_case: Any = prophet_old else: snake_case: str = prophet.prophetnet snake_case: List[str] = prophet_old.model snake_case: int = False for attribute in attributes: if attribute in mapping: snake_case: Optional[Any] = mapping[attribute] if not hasattr(__A , __A ) and len(__A ) > 0: snake_case: List[str] = attribute elif hasattr(__A , __A ): snake_case: Any = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" snake_case: int = old_model.weight logger.info(f"""{attribute} is initialized.""" ) snake_case: Dict = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" snake_case: int = old_model.bias logger.info(f"""{attribute} is initialized""" ) snake_case: List[str] = True break elif attribute in special_keys and hasattr(__A , 'in_proj_weight' ): snake_case: Tuple = old_model.in_proj_weight.shape[0] // 3 snake_case: Any = getattr(__A , __A ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": snake_case: Optional[Any] = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) snake_case: Optional[int] = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": snake_case: Optional[int] = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) snake_case: Union[str, Any] = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": snake_case: str = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) snake_case: Optional[int] = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) snake_case: Optional[int] = True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 5_12, "We want 512 position_embeddings." snake_case: Union[str, Any] = nn.Parameter(old_model.embed_positions.weight[:5_12, :] ) snake_case: Dict = True break if attribute.isdigit(): snake_case: Any = model[int(__A )] snake_case: Optional[Any] = old_model[int(__A )] else: snake_case: Dict = getattr(__A , __A ) if old_attribute == "": snake_case: str = old_model else: if not hasattr(__A , __A ): raise ValueError(f"""{old_model} does not have {old_attribute}""" ) snake_case: Any = getattr(__A , __A ) if not is_key_init: raise ValueError(f"""{key} was not correctly initialized!""" ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) prophet.save_pretrained(__A ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--prophetnet_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) __UpperCAmelCase = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
692
'''simple docstring''' import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig __UpperCAmelCase = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = question_encoder snake_case: Union[str, Any] = generator snake_case: Optional[int] = self.question_encoder def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if os.path.isfile(SCREAMING_SNAKE_CASE__ ): raise ValueError(F"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , 'question_encoder_tokenizer' ) snake_case: Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , 'generator_tokenizer' ) self.question_encoder.save_pretrained(SCREAMING_SNAKE_CASE__ ) self.generator.save_pretrained(SCREAMING_SNAKE_CASE__ ) @classmethod def _UpperCamelCase ( cls , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer snake_case: int = kwargs.pop('config' , SCREAMING_SNAKE_CASE__ ) if config is None: snake_case: str = RagConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE__ , config=config.question_encoder , subfolder='question_encoder_tokenizer' ) snake_case: Dict = AutoTokenizer.from_pretrained( SCREAMING_SNAKE_CASE__ , config=config.generator , subfolder='generator_tokenizer' ) return cls(question_encoder=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) def __call__( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.current_tokenizer(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.generator.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.generator.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.question_encoder def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.generator def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "longest" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = True , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' warnings.warn( '`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ' 'regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ' 'context manager to prepare your targets. See the documentation of your specific tokenizer for more ' 'details' , SCREAMING_SNAKE_CASE__ , ) if max_length is None: snake_case: Optional[Any] = self.current_tokenizer.model_max_length snake_case: int = self( SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: snake_case: Any = self.current_tokenizer.model_max_length snake_case: List[str] = self( text_target=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case: Dict = labels['input_ids'] return model_inputs
692
1
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs __UpperCAmelCase = imread(R"digital_image_processing/image_data/lena_small.jpg") __UpperCAmelCase = cvtColor(img, COLOR_BGR2GRAY) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Dict = cn.convert_to_negative(__A ) # assert negative_img array for at least one True assert negative_img.any() def lowerCAmelCase_ ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(__A , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Any = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Any = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() snake_case: Any = canny.canny(__A ) # assert canny array for at least one True assert canny_array.any() def lowerCAmelCase_ ( ): '''simple docstring''' assert gg.gaussian_filter(__A , 5 , sigma=0.9 ).all() def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Tuple = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) snake_case: int = conv.img_convolve(__A , __A ).astype(__A ) assert res.any() def lowerCAmelCase_ ( ): '''simple docstring''' assert med.median_filter(__A , 3 ).any() def lowerCAmelCase_ ( ): '''simple docstring''' snake_case , snake_case: str = sob.sobel_filter(__A ) assert grad.any() and theta.any() def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Any = sp.make_sepia(__A , 20 ) assert sepia.all() def lowerCAmelCase_ ( __A : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' snake_case: int = bs.Burkes(imread(__A , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def lowerCAmelCase_ ( __A : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' snake_case: List[Any] = rs.NearestNeighbour(imread(__A , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Optional[Any] = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. snake_case: Optional[int] = imread(__A , 0 ) # Test for get_neighbors_pixel function() return not None snake_case: Tuple = 0 snake_case: Optional[int] = 0 snake_case: Union[str, Any] = image[x_coordinate][y_coordinate] snake_case: int = lbp.get_neighbors_pixel( __A , __A , __A , __A ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image snake_case: Dict = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): snake_case: List[Any] = lbp.local_binary_value(__A , __A , __A ) assert lbp_image.any()
692
'''simple docstring''' 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_ ( __A : Tuple ): '''simple docstring''' assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ): '''simple docstring''' assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Union[str, Any] = 'mock-s3-bucket' snake_case: int = f"""s3://{mock_bucket}""" snake_case: Any = extract_path_from_uri(__A ) assert dataset_path.startswith('s3://' ) is False snake_case: Union[str, Any] = './local/path' snake_case: Union[str, Any] = extract_path_from_uri(__A ) assert dataset_path == new_dataset_path def lowerCAmelCase_ ( __A : Any ): '''simple docstring''' snake_case: List[str] = is_remote_filesystem(__A ) assert is_remote is True snake_case: int = fsspec.filesystem('file' ) snake_case: int = is_remote_filesystem(__A ) assert is_remote is False @pytest.mark.parametrize('compression_fs_class' , __A ) def lowerCAmelCase_ ( __A : Optional[int] , __A : int , __A : str , __A : Optional[Any] , __A : List[str] , __A : Optional[Any] , __A : Optional[int] ): '''simple docstring''' snake_case: Optional[Any] = {'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_file, 'bz2': bza_file, 'lz4': lza_file} snake_case: Optional[int] = input_paths[compression_fs_class.protocol] if input_path is None: snake_case: str = 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(__A ) snake_case: List[str] = fsspec.filesystem(compression_fs_class.protocol , fo=__A ) assert isinstance(__A , __A ) snake_case: Any = os.path.basename(__A ) snake_case: int = expected_filename[: expected_filename.rindex('.' )] assert fs.glob('*' ) == [expected_filename] with fs.open(__A , 'r' , encoding='utf-8' ) as f, open(__A , encoding='utf-8' ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize('protocol' , ['zip', 'gzip'] ) def lowerCAmelCase_ ( __A : Any , __A : int , __A : int ): '''simple docstring''' snake_case: List[str] = {'zip': zip_jsonl_path, 'gzip': jsonl_gz_path} snake_case: str = compressed_file_paths[protocol] snake_case: Dict = 'dataset.jsonl' snake_case: Optional[Any] = f"""{protocol}://{member_file_path}::{compressed_file_path}""" snake_case , *snake_case: List[Any] = fsspec.get_fs_token_paths(__A ) assert fs.isfile(__A ) assert not fs.isfile('non_existing_' + member_file_path ) @pytest.mark.integration def lowerCAmelCase_ ( __A : Optional[Any] , __A : Union[str, Any] , __A : Union[str, Any] , __A : List[Any] ): '''simple docstring''' snake_case: Tuple = hf_api.dataset_info(__A , token=__A ) snake_case: List[str] = HfFileSystem(repo_info=__A , token=__A ) assert sorted(hffs.glob('*' ) ) == [".gitattributes", "data"] assert hffs.isdir('data' ) assert hffs.isfile('.gitattributes' ) and hffs.isfile('data/text_data.txt' ) with open(__A ) as f: assert hffs.open('data/text_data.txt' , 'r' ).read() == f.read() def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Union[str, Any] = 'bz2' # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(__A , __A , clobber=__A ) with pytest.warns(__A ) as warning_info: importlib.reload(datasets.filesystems ) assert len(__A ) == 1 assert ( str(warning_info[0].message ) == f"""A filesystem protocol was already set for {protocol} and will be overwritten.""" )
692
1
import argparse import copy def lowerCAmelCase_ ( __A : Dict ): '''simple docstring''' snake_case: Union[str, Any] = {} with open(SCREAMING_SNAKE_CASE_ ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: snake_case: List[Any] = [] _list.append([line.split()[1], line.split()[2]] ) snake_case: int = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: snake_case: Dict = [] _list.append([line.split()[0], line.split()[2]] ) snake_case: Optional[Any] = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def lowerCAmelCase_ ( __A : Union[str, Any] , __A : List[str] ): '''simple docstring''' with open(SCREAMING_SNAKE_CASE_ ) as f: snake_case: List[Any] = f.read(1 ) snake_case: Union[str, Any] = start_node snake_case: List[str] = [] snake_case: int = start_node snake_case: List[Any] = 0 while visiting not in first_solution: snake_case: List[str] = 1_00_00 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(SCREAMING_SNAKE_CASE_ ) and k[0] not in first_solution: snake_case: Dict = k[1] snake_case: List[Any] = k[0] first_solution.append(SCREAMING_SNAKE_CASE_ ) snake_case: Tuple = distance_of_first_solution + int(SCREAMING_SNAKE_CASE_ ) snake_case: List[str] = best_node first_solution.append(SCREAMING_SNAKE_CASE_ ) snake_case: Optional[Any] = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 snake_case: Optional[int] = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_00_00 ) return first_solution, distance_of_first_solution def lowerCAmelCase_ ( __A : Dict , __A : Dict ): '''simple docstring''' snake_case: Any = [] for n in solution[1:-1]: snake_case: Dict = solution.index(SCREAMING_SNAKE_CASE_ ) for kn in solution[1:-1]: snake_case: Optional[Any] = solution.index(SCREAMING_SNAKE_CASE_ ) if n == kn: continue snake_case: int = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) snake_case: Dict = kn snake_case: Optional[int] = n snake_case: Optional[int] = 0 for k in _tmp[:-1]: snake_case: str = _tmp[_tmp.index(SCREAMING_SNAKE_CASE_ ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: snake_case: int = distance + int(i[1] ) _tmp.append(SCREAMING_SNAKE_CASE_ ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) snake_case: str = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __A : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def lowerCAmelCase_ ( __A : str , __A : Tuple , __A : Union[str, Any] , __A : Union[str, Any] , __A : Optional[int] ): '''simple docstring''' snake_case: int = 1 snake_case: Any = first_solution snake_case: Optional[int] = [] snake_case: int = distance_of_first_solution snake_case: Optional[Any] = solution while count <= iters: snake_case: Dict = find_neighborhood(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) snake_case: Tuple = 0 snake_case: List[Any] = neighborhood[index_of_best_solution] snake_case: Tuple = len(SCREAMING_SNAKE_CASE_ ) - 1 snake_case: Any = False while not found: snake_case: List[str] = 0 while i < len(SCREAMING_SNAKE_CASE_ ): if best_solution[i] != solution[i]: snake_case: List[Any] = best_solution[i] snake_case: Optional[Any] = solution[i] break snake_case: int = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) snake_case: Optional[Any] = True snake_case: Optional[Any] = best_solution[:-1] snake_case: Any = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: snake_case: int = cost snake_case: Optional[int] = solution else: snake_case: Union[str, Any] = index_of_best_solution + 1 snake_case: Optional[int] = neighborhood[index_of_best_solution] if len(SCREAMING_SNAKE_CASE_ ) >= size: tabu_list.pop(0 ) snake_case: str = count + 1 return best_solution_ever, best_cost def lowerCAmelCase_ ( __A : Optional[int]=None ): '''simple docstring''' snake_case: Any = generate_neighbours(args.File ) snake_case , snake_case: int = generate_first_solution( args.File , SCREAMING_SNAKE_CASE_ ) snake_case , snake_case: Union[str, Any] = tabu_search( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , args.Iterations , args.Size , ) print(f"""Best solution: {best_sol}, with total distance: {best_cost}.""" ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser(description="Tabu Search") parser.add_argument( "-f", "--File", type=str, help="Path to the file containing the data", required=True, ) parser.add_argument( "-i", "--Iterations", type=int, help="How many iterations the algorithm should perform", required=True, ) parser.add_argument( "-s", "--Size", type=int, help="Size of the tabu list", required=True ) # Pass the arguments to main method main(parser.parse_args())
700
'''simple docstring''' import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.17.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") __UpperCAmelCase = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = field( default="tab_fact" , metadata={"help": "The name of the dataset to use (via the datasets library)."} ) __UpperCamelCase = field( default="tab_fact" , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} , ) __UpperCamelCase = field( default=1024 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "A csv or a json file containing the training data."} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "A csv or a json file containing the validation data."} ) __UpperCamelCase = field(default=snake_case , metadata={"help": "A csv or a json file containing the test data."} ) def _UpperCamelCase ( self ): '''simple docstring''' if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError('Need either a GLUE task, a training/validation file or a dataset name.' ) else: snake_case: str = self.train_file.split('.' )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." snake_case: Optional[Any] = self.validation_file.split('.' )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class SCREAMING_SNAKE_CASE : '''simple docstring''' __UpperCamelCase = field( default=snake_case , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __UpperCamelCase = field( default=snake_case , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) __UpperCamelCase = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __UpperCamelCase = field( default=snake_case , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Dict = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case , snake_case , snake_case: Union[str, Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case , snake_case , snake_case: str = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) snake_case: Tuple = training_args.get_process_log_level() logger.setLevel(__A ) datasets.utils.logging.set_verbosity(__A ) transformers.utils.logging.set_verbosity(__A ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Detecting last checkpoint. snake_case: Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case: List[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. snake_case: int = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. snake_case: Optional[int] = {'train': data_args.train_file, 'validation': data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: snake_case: Tuple = data_args.train_file.split('.' )[-1] snake_case: Union[str, Any] = data_args.test_file.split('.' )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." snake_case: Union[str, Any] = data_args.test_file else: raise ValueError('Need either a GLUE task or a test file for `do_predict`.' ) for key in data_files.keys(): logger.info(f"""load a local file for {key}: {data_files[key]}""" ) if data_args.train_file.endswith('.csv' ): # Loading a dataset from local csv files snake_case: List[Any] = load_dataset('csv' , data_files=__A , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files snake_case: Optional[Any] = load_dataset('json' , data_files=__A , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels snake_case: Tuple = raw_datasets['train'].features['label'].names snake_case: List[str] = len(__A ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case: Tuple = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer snake_case: List[str] = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=__A , ) snake_case: Union[str, Any] = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=__A , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: snake_case: int = 'max_length' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch snake_case: Union[str, Any] = False # Some models have set the order of the labels to use, so let's make sure we do use it. snake_case: Optional[Any] = {'Refused': 0, 'Entailed': 1} snake_case: List[Any] = {0: 'Refused', 1: 'Entailed'} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the""" f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) snake_case: List[str] = min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(__A : Any ): # Tokenize the texts def _convert_table_text_to_pandas(__A : Dict ): snake_case: str = [_table_row.split('#' ) for _table_row in _table_text.strip('\n' ).split('\n' )] snake_case: List[str] = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd snake_case: str = examples['statement'] snake_case: int = list(map(_convert_table_text_to_pandas , examples['table_text'] ) ) snake_case: List[Any] = tokenizer(__A , __A , padding=__A , max_length=__A , truncation=__A ) snake_case: List[Any] = examples['label'] return result with training_args.main_process_first(desc='dataset map pre-processing' ): snake_case: int = raw_datasets.map( __A , batched=__A , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on dataset' , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError('--do_train requires a train dataset' ) snake_case: List[str] = raw_datasets['train'] if data_args.max_train_samples is not None: snake_case: Tuple = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError('--do_eval requires a validation dataset' ) snake_case: Any = raw_datasets['validation'] if data_args.max_eval_samples is not None: snake_case: Optional[int] = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError('--do_predict requires a test dataset' ) snake_case: str = raw_datasets['test'] if data_args.max_predict_samples is not None: snake_case: List[str] = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(__A ) ) , 3 ): logger.info(f"""Sample {index} of the training set: {train_dataset[index]}.""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__A : EvalPrediction ): snake_case: int = p.predictions[0] if isinstance(p.predictions , __A ) else p.predictions snake_case: List[str] = np.argmax(__A , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: snake_case: str = default_data_collator elif training_args.fpaa: snake_case: List[str] = DataCollatorWithPadding(__A , pad_to_multiple_of=8 ) else: snake_case: List[Any] = None # Initialize our Trainer snake_case: List[str] = Trainer( model=__A , args=__A , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__A , tokenizer=__A , data_collator=__A , ) # Training if training_args.do_train: snake_case: Optional[int] = None if training_args.resume_from_checkpoint is not None: snake_case: str = training_args.resume_from_checkpoint elif last_checkpoint is not None: snake_case: Optional[Any] = last_checkpoint snake_case: Union[str, Any] = trainer.train(resume_from_checkpoint=__A ) snake_case: List[Any] = train_result.metrics snake_case: List[Any] = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__A ) ) snake_case: Optional[Any] = min(__A , len(__A ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('train' , __A ) trainer.save_metrics('train' , __A ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) snake_case: Dict = trainer.evaluate(eval_dataset=__A ) snake_case: Optional[int] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__A ) snake_case: Dict = min(__A , len(__A ) ) trainer.log_metrics('eval' , __A ) trainer.save_metrics('eval' , __A ) if training_args.do_predict: logger.info('*** Predict ***' ) # Removing the `label` columns because it contains -1 and Trainer won't like that. snake_case: Optional[int] = predict_dataset.remove_columns('label' ) snake_case: str = trainer.predict(__A , metric_key_prefix='predict' ).predictions snake_case: Any = np.argmax(__A , axis=1 ) snake_case: int = os.path.join(training_args.output_dir , 'predict_results_tabfact.txt' ) if trainer.is_world_process_zero(): with open(__A , 'w' ) as writer: logger.info('***** Predict Results *****' ) writer.write('index\tprediction\n' ) for index, item in enumerate(__A ): snake_case: int = label_list[item] writer.write(f"""{index}\t{item}\n""" ) snake_case: Optional[int] = {'finetuned_from': model_args.model_name_or_path, 'tasks': 'text-classification'} if training_args.push_to_hub: trainer.push_to_hub(**__A ) else: trainer.create_model_card(**__A ) def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' main() if __name__ == "__main__": main()
692
0
'''simple docstring''' import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class SCREAMING_SNAKE_CASE ( _snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ = "▁" , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = "<unk>" , SCREAMING_SNAKE_CASE__ = "</s>" , SCREAMING_SNAKE_CASE__ = "<pad>" , ): '''simple docstring''' snake_case: List[Any] = { 'pad': {'id': 0, 'token': pad_token}, 'eos': {'id': 1, 'token': eos_token}, 'unk': {'id': 2, 'token': unk_token}, } snake_case: Optional[Any] = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): snake_case: int = token_dict['token'] snake_case: int = Tokenizer(Unigram() ) snake_case: Dict = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(' {2,}' ) , ' ' ), normalizers.Lowercase(), ] ) snake_case: Any = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ ), pre_tokenizers.Digits(individual_digits=lowerCAmelCase__ ), pre_tokenizers.Punctuation(), ] ) snake_case: List[Any] = decoders.Metaspace(replacement=lowerCAmelCase__ , add_prefix_space=lowerCAmelCase__ ) snake_case: int = TemplateProcessing( single=F"""$A {self.special_tokens['eos']['token']}""" , special_tokens=[(self.special_tokens['eos']['token'], self.special_tokens['eos']['id'])] , ) snake_case: Tuple = { 'model': 'SentencePieceUnigram', 'replacement': replacement, 'add_prefix_space': add_prefix_space, } super().__init__(lowerCAmelCase__ , lowerCAmelCase__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 80_00 , SCREAMING_SNAKE_CASE__ = True , ): '''simple docstring''' snake_case: int = trainers.UnigramTrainer( vocab_size=lowerCAmelCase__ , special_tokens=self.special_tokens_list , show_progress=lowerCAmelCase__ , ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): snake_case: Any = [files] self._tokenizer.train(lowerCAmelCase__ , trainer=lowerCAmelCase__ ) self.add_unk_id() def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 80_00 , SCREAMING_SNAKE_CASE__ = True , ): '''simple docstring''' snake_case: Dict = trainers.UnigramTrainer( vocab_size=lowerCAmelCase__ , special_tokens=self.special_tokens_list , show_progress=lowerCAmelCase__ , ) self._tokenizer.train_from_iterator(lowerCAmelCase__ , trainer=lowerCAmelCase__ ) self.add_unk_id() def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = json.loads(self._tokenizer.to_str() ) snake_case: Optional[int] = self.special_tokens['unk']['id'] snake_case: Union[str, Any] = Tokenizer.from_str(json.dumps(lowerCAmelCase__ ) )
701
'''simple docstring''' import math def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__A ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCAmelCase_ ( __A : float = 0.1 ): '''simple docstring''' snake_case: Optional[int] = 3 snake_case: int = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(__A ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
692
0
'''simple docstring''' import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = tempfile.mkdtemp() snake_case: Union[str, Any] = SamImageProcessor() snake_case: int = SamProcessor(UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def _UpperCamelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] snake_case: Dict = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case: List[Any] = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) snake_case: Optional[Any] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=UpperCAmelCase_ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.get_image_processor() snake_case: Any = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case: List[str] = self.prepare_image_inputs() snake_case: int = image_processor(UpperCAmelCase_ , return_tensors='np' ) snake_case: Tuple = processor(images=UpperCAmelCase_ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.get_image_processor() snake_case: str = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case: List[Any] = [torch.ones((1, 3, 5, 5) )] snake_case: Optional[Any] = [[17_64, 26_46]] snake_case: Dict = [[6_83, 10_24]] snake_case: Optional[Any] = processor.post_process_masks(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) snake_case: Tuple = processor.post_process_masks( UpperCAmelCase_ , torch.tensor(UpperCAmelCase_ ) , torch.tensor(UpperCAmelCase_ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np snake_case: Any = [np.ones((1, 3, 5, 5) )] snake_case: List[Any] = processor.post_process_masks(UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) snake_case: str = [[1, 0], [0, 1]] with self.assertRaises(UpperCAmelCase_ ): snake_case: int = processor.post_process_masks(UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = tempfile.mkdtemp() snake_case: str = SamImageProcessor() snake_case: List[str] = SamProcessor(UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def _UpperCamelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] snake_case: Union[str, Any] = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case: List[Any] = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) snake_case: str = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=UpperCAmelCase_ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.get_image_processor() snake_case: List[str] = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case: Dict = self.prepare_image_inputs() snake_case: List[str] = image_processor(UpperCAmelCase_ , return_tensors='np' ) snake_case: Any = processor(images=UpperCAmelCase_ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_image_processor() snake_case: Any = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case: Optional[int] = [tf.ones((1, 3, 5, 5) )] snake_case: int = [[17_64, 26_46]] snake_case: Any = [[6_83, 10_24]] snake_case: int = processor.post_process_masks(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) snake_case: List[str] = processor.post_process_masks( UpperCAmelCase_ , tf.convert_to_tensor(UpperCAmelCase_ ) , tf.convert_to_tensor(UpperCAmelCase_ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np snake_case: List[Any] = [np.ones((1, 3, 5, 5) )] snake_case: Tuple = processor.post_process_masks( UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) snake_case: Any = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): snake_case: Any = processor.post_process_masks( UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = tempfile.mkdtemp() snake_case: List[str] = SamImageProcessor() snake_case: int = SamProcessor(UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def _UpperCamelCase ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] snake_case: Any = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = self.get_image_processor() snake_case: List[Any] = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case: List[Any] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) snake_case: int = [tf.convert_to_tensor(UpperCAmelCase_ )] snake_case: List[Any] = [torch.tensor(UpperCAmelCase_ )] snake_case: Dict = [[17_64, 26_46]] snake_case: List[Any] = [[6_83, 10_24]] snake_case: int = processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , return_tensors='tf' ) snake_case: int = processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = self.get_image_processor() snake_case: Optional[Any] = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case: Dict = self.prepare_image_inputs() snake_case: Dict = image_processor(UpperCAmelCase_ , return_tensors='pt' )['pixel_values'].numpy() snake_case: int = processor(images=UpperCAmelCase_ , return_tensors='pt' )['pixel_values'].numpy() snake_case: Tuple = image_processor(UpperCAmelCase_ , return_tensors='tf' )['pixel_values'].numpy() snake_case: Optional[Any] = processor(images=UpperCAmelCase_ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ ) )
702
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): __UpperCAmelCase = "pt" elif is_tf_available(): __UpperCAmelCase = "tf" else: __UpperCAmelCase = "jax" class SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ByTaTokenizer __UpperCamelCase = False def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: int = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _UpperCamelCase ( self ): '''simple docstring''' return ByTaTokenizer.from_pretrained('google/byt5-small' ) def _UpperCamelCase ( self , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=20 , SCREAMING_SNAKE_CASE__=5 ): '''simple docstring''' snake_case: Optional[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): try: snake_case: Optional[Any] = tokenizer.decode([i] , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) except UnicodeDecodeError: pass toks.append((i, tok) ) snake_case: List[str] = list(filter(lambda SCREAMING_SNAKE_CASE__ : re.match(r'^[ a-zA-Z]+$' , t[1] ) , SCREAMING_SNAKE_CASE__ ) ) snake_case: str = list(filter(lambda SCREAMING_SNAKE_CASE__ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) ) if max_length is not None and len(SCREAMING_SNAKE_CASE__ ) > max_length: snake_case: Union[str, Any] = 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: snake_case: Tuple = toks + toks # toks_str = [t[1] for t in toks] snake_case: Dict = [t[0] for t in toks] # Ensure consistency snake_case: int = tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) if " " not in output_txt and len(SCREAMING_SNAKE_CASE__ ) > 1: snake_case: str = ( 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: snake_case: Tuple = ' ' + output_txt snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) return output_txt, output_ids def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: str = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>'] ) snake_case: List[Any] = tokenizer(['hi', 'I went to the gym', ''] ) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.ta_base_tokenizer snake_case: Union[str, Any] = 'Unicode €.' snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = [88, 1_13, 1_08, 1_02, 1_14, 1_03, 1_04, 35, 2_29, 1_33, 1_75, 49, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[str] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'Unicode €.</s>' ) snake_case: List[Any] = tokenizer('e è é ê ë' ) snake_case: Optional[Any] = [1_04, 35, 1_98, 1_71, 35, 1_98, 1_72, 35, 1_98, 1_73, 35, 1_98, 1_74, 1] self.assertEqual(encoded['input_ids'] , SCREAMING_SNAKE_CASE__ ) # decoding snake_case: List[Any] = tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , 'e è é ê ë</s>' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , 'e è é ê ë</s>' ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = self.ta_base_tokenizer snake_case: Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off snake_case: Optional[int] = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 1, 0] # fmt: on snake_case: str = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if FRAMEWORK != "jax": snake_case: Optional[Any] = list(batch.input_ids.numpy()[0] ) else: snake_case: Dict = list(batch.input_ids.tolist()[0] ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual((2, 37) , batch.input_ids.shape ) self.assertEqual((2, 37) , batch.attention_mask.shape ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.ta_base_tokenizer snake_case: List[str] = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] snake_case: Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertIn('attention_mask' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_input_ids' , SCREAMING_SNAKE_CASE__ ) self.assertNotIn('decoder_attention_mask' , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.ta_base_tokenizer snake_case: str = [ 'Summary of the text.', 'Another summary.', ] snake_case: Dict = tokenizer( text_target=SCREAMING_SNAKE_CASE__ , max_length=32 , padding='max_length' , truncation=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = self.ta_base_tokenizer snake_case: Optional[int] = ['A long paragraph for summarization. </s>'] snake_case: str = ['Summary of the text. </s>'] # fmt: off snake_case: str = [68, 35, 1_11, 1_14, 1_13, 1_06, 35, 1_15, 1_00, 1_17, 1_00, 1_06, 1_17, 1_00, 1_15, 1_07, 35, 1_05, 1_14, 1_17, 35, 1_18, 1_20, 1_12, 1_12, 1_00, 1_17, 1_08, 1_25, 1_00, 1_19, 1_08, 1_14, 1_13, 49, 35, 1] snake_case: Optional[int] = [86, 1_20, 1_12, 1_12, 1_00, 1_17, 1_24, 35, 1_14, 1_05, 35, 1_19, 1_07, 1_04, 35, 1_19, 1_04, 1_23, 1_19, 49, 35, 1] # fmt: on snake_case: List[Any] = tokenizer(SCREAMING_SNAKE_CASE__ , text_target=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['input_ids'][0] ) self.assertEqual(SCREAMING_SNAKE_CASE__ , batch['labels'][0] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test snake_case: Optional[Any] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: Union[str, Any] = tempfile.mkdtemp() snake_case: Dict = ' He is very happy, UNwant\u00E9d,running' snake_case: Optional[int] = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Any = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): # Isolate this from the other tests because we save additional tokens/etc snake_case: List[str] = tempfile.mkdtemp() snake_case: str = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) snake_case: List[str] = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) snake_case: int = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = after_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) snake_case: Union[str, Any] = tokenizer.__class__.from_pretrained(SCREAMING_SNAKE_CASE__ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: snake_case: Any = json.load(SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: snake_case: str = json.load(SCREAMING_SNAKE_CASE__ ) snake_case: int = [F"""<extra_id_{i}>""" for i in range(1_25 )] snake_case: Optional[int] = added_tokens_extra_ids + [ 'an_additional_special_token' ] snake_case: str = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files snake_case: Dict = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained snake_case: Union[str, Any] = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=SCREAMING_SNAKE_CASE__ )] snake_case: Union[str, Any] = tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertTrue(tokenizer.decode([2_55] ) == '' ) def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' pass def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.get_tokenizers(fast=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Union[str, Any] = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] snake_case: List[str] = tokenizer.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Optional[Any] = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] snake_case: Dict = 0 snake_case: List[Any] = tokenizer.convert_ids_to_tokens( SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) for attr in attributes_list: setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , attr + '_id' , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(getattr(SCREAMING_SNAKE_CASE__ , attr + '_id' ) , SCREAMING_SNAKE_CASE__ ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [] ) setattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' , [token_id_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens' ) , [token_to_test_setters] ) self.assertListEqual(getattr(SCREAMING_SNAKE_CASE__ , 'additional_special_tokens_ids' ) , [token_id_to_test_setters] )
692
0
'''simple docstring''' from __future__ import annotations from typing import TypedDict class SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase = 42 __UpperCamelCase = 42 def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' if not isinstance(__A , __A ): raise TypeError('The parameter s type must be str.' ) return [s[i:] + s[:i] for i in range(len(__A ) )] def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' if not isinstance(__A , __A ): raise TypeError('The parameter s type must be str.' ) if not s: raise ValueError('The parameter s must not be empty.' ) snake_case: int = all_rotations(__A ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation snake_case: Tuple = { 'bwt_string': ''.join([word[-1] for word in rotations] ), 'idx_original_string': rotations.index(__A ), } return response def lowerCAmelCase_ ( __A : List[Any] , __A : Dict ): '''simple docstring''' if not isinstance(__A , __A ): raise TypeError('The parameter bwt_string type must be str.' ) if not bwt_string: raise ValueError('The parameter bwt_string must not be empty.' ) try: snake_case: List[str] = int(__A ) except ValueError: raise TypeError( 'The parameter idx_original_string type must be int or passive' ' of cast to int.' ) if idx_original_string < 0: raise ValueError('The parameter idx_original_string must not be lower than 0.' ) if idx_original_string >= len(__A ): raise ValueError( 'The parameter idx_original_string must be lower than' ' len(bwt_string).' ) snake_case: str = [''] * len(__A ) for _ in range(len(__A ) ): for i in range(len(__A ) ): snake_case: Optional[int] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": __UpperCAmelCase = "Provide a string that I will generate its BWT transform: " __UpperCAmelCase = input(entry_msg).strip() __UpperCAmelCase = bwt_transform(s) print( F'Burrows Wheeler transform for string \'{s}\' results ' F'in \'{result["bwt_string"]}\'' ) __UpperCAmelCase = reverse_bwt(result["bwt_string"], result["idx_original_string"]) print( F'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' F'we get original string \'{original_string}\'' )
703
'''simple docstring''' from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = "layer_norm" , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__() snake_case: List[str] = only_cross_attention snake_case: Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero' snake_case: Tuple = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to""" F""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""" ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: snake_case: List[str] = AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: snake_case: str = AdaLayerNormZero(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: snake_case: int = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = Attention( query_dim=SCREAMING_SNAKE_CASE__ , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. snake_case: Tuple = ( AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) ) snake_case: Any = Attention( query_dim=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # is self-attn if encoder_hidden_states is none else: snake_case: int = None snake_case: Tuple = None # 3. Feed-forward snake_case: Union[str, Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = FeedForward(SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , activation_fn=SCREAMING_SNAKE_CASE__ , final_dropout=SCREAMING_SNAKE_CASE__ ) # let chunk size default to None snake_case: Any = None snake_case: Any = 0 def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = chunk_size snake_case: str = dim def _UpperCamelCase ( 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 , ): '''simple docstring''' if self.use_ada_layer_norm: snake_case: Optional[int] = self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: snake_case , snake_case , snake_case , snake_case , snake_case: int = self.norma( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=hidden_states.dtype ) else: snake_case: List[str] = self.norma(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = cross_attention_kwargs if cross_attention_kwargs is not None else {} snake_case: List[str] = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if self.use_ada_layer_norm_zero: snake_case: Tuple = gate_msa.unsqueeze(1 ) * attn_output snake_case: List[str] = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: snake_case: Dict = ( self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else self.norma(SCREAMING_SNAKE_CASE__ ) ) snake_case: Any = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case: List[str] = attn_output + hidden_states # 3. Feed-forward snake_case: str = self.norma(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: snake_case: str = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""" ) snake_case: List[str] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size snake_case: Optional[Any] = torch.cat( [self.ff(SCREAMING_SNAKE_CASE__ ) for hid_slice in norm_hidden_states.chunk(SCREAMING_SNAKE_CASE__ , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: snake_case: int = self.ff(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: snake_case: Union[str, Any] = gate_mlp.unsqueeze(1 ) * ff_output snake_case: Tuple = ff_output + hidden_states return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 4 , SCREAMING_SNAKE_CASE__ = 0.0 , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = False , ): '''simple docstring''' super().__init__() snake_case: int = int(dim * mult ) snake_case: Optional[Any] = dim_out if dim_out is not None else dim if activation_fn == "gelu": snake_case: int = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if activation_fn == "gelu-approximate": snake_case: Optional[Any] = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , approximate='tanh' ) elif activation_fn == "geglu": snake_case: List[Any] = GEGLU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif activation_fn == "geglu-approximate": snake_case: Optional[int] = ApproximateGELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Any = nn.ModuleList([] ) # project in self.net.append(SCREAMING_SNAKE_CASE__ ) # project dropout self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) # project out self.net.append(nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' for module in self.net: snake_case: Optional[int] = module(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "none" ): '''simple docstring''' super().__init__() snake_case: Optional[int] = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = approximate def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.proj(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = self.gelu(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = nn.Linear(SCREAMING_SNAKE_CASE__ , dim_out * 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case , snake_case: int = self.proj(SCREAMING_SNAKE_CASE__ ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = self.proj(SCREAMING_SNAKE_CASE__ ) return x * torch.sigmoid(1.7_02 * x ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Optional[Any] = nn.Embedding(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = nn.SiLU() snake_case: Union[str, Any] = nn.Linear(SCREAMING_SNAKE_CASE__ , embedding_dim * 2 ) snake_case: int = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ ) ) ) snake_case , snake_case: Dict = torch.chunk(SCREAMING_SNAKE_CASE__ , 2 ) snake_case: str = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale) + shift return x class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = CombinedTimestepLabelEmbeddings(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.SiLU() snake_case: Any = nn.Linear(SCREAMING_SNAKE_CASE__ , 6 * embedding_dim , bias=SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ , eps=1E-6 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' snake_case: int = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=SCREAMING_SNAKE_CASE__ ) ) ) snake_case , snake_case , snake_case , snake_case , snake_case , snake_case: str = emb.chunk(6 , dim=1 ) snake_case: Dict = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 1E-5 ): '''simple docstring''' super().__init__() snake_case: str = num_groups snake_case: str = eps if act_fn is None: snake_case: Dict = None else: snake_case: List[str] = get_activation(SCREAMING_SNAKE_CASE__ ) snake_case: Any = nn.Linear(SCREAMING_SNAKE_CASE__ , out_dim * 2 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.act: snake_case: Optional[Any] = self.act(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.linear(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = emb[:, :, None, None] snake_case , snake_case: List[Any] = emb.chunk(2 , dim=1 ) snake_case: Any = F.group_norm(SCREAMING_SNAKE_CASE__ , self.num_groups , eps=self.eps ) snake_case: Optional[int] = x * (1 + scale) + shift return x
692
0
'''simple docstring''' def lowerCAmelCase_ ( __A : Tuple ): '''simple docstring''' if edge <= 0 or not isinstance(_lowercase , _lowercase ): raise ValueError('Length must be a positive.' ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def lowerCAmelCase_ ( __A : Any ): '''simple docstring''' if edge <= 0 or not isinstance(_lowercase , _lowercase ): raise ValueError('Length must be a positive.' ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
704
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 SCREAMING_SNAKE_CASE ( snake_case , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = RoCBertTokenizer __UpperCamelCase = None __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = filter_non_english def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() snake_case: Any = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '你', '好', '是', '谁', 'a', 'b', 'c', 'd'] snake_case: List[Any] = {} snake_case: List[str] = {} for i, value in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = i snake_case: Union[str, Any] = i snake_case: List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) snake_case: Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] ) snake_case: str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: Dict = tokenizer.tokenize('你好[SEP]你是谁' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['你', '好', '[SEP]', '你', '是', '谁'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) , [5, 6, 2, 5, 7, 8] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE__ , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Union[str, Any] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] snake_case: Union[str, Any] = {} for i, token in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: str = i snake_case: Optional[int] = RoCBertWordpieceTokenizer(vocab=SCREAMING_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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' 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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) if self.test_rust_tokenizer: snake_case: int = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) def _UpperCamelCase ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" snake_case: List[str] = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , ) snake_case: Optional[int] = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE__ , 'do_lower_case' ) else False snake_case: int = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 15), tokenizer_r.mask_token), ((16, 21), 'Allen'), ((21, 23), '##NL'), ((23, 24), '##P'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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, 15), tokenizer_r.mask_token), ((16, 21), 'allen'), ((21, 23), '##nl'), ((23, 24), '##p'), ((25, 33), 'sentence'), ((33, 34), '.'), ((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 _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = ['的', '人', '有'] snake_case: Any = ''.join(SCREAMING_SNAKE_CASE__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): snake_case: Tuple = True snake_case: List[Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = False snake_case: Union[str, Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_r.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: int = tokenizer_p.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # it is expected that only the first Chinese character is not preceded by "##". snake_case: Union[str, Any] = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE__ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) snake_case: int = tokenizer.encode('你好' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Any = tokenizer.encode('你是谁' , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) snake_case: str = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[str] = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): snake_case: Dict = '你好,你是谁' snake_case: int = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[Any] = tokenizer.prepare_for_model( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = tokenizer.encode_plus(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
692
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) __UpperCAmelCase = { "configuration_speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", ], "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"], "processing_speecht5": ["SpeechT5Processor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["SpeechT5Tokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToText", "SpeechT5ForSpeechToSpeech", "SpeechT5ForTextToSpeech", "SpeechT5Model", "SpeechT5PreTrainedModel", "SpeechT5HifiGan", ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
705
'''simple docstring''' from math import asin, atan, cos, radians, sin, sqrt, tan __UpperCAmelCase = 6378137.0 __UpperCAmelCase = 6356752.314245 __UpperCAmelCase = 6_378_137 def lowerCAmelCase_ ( __A : float , __A : float , __A : float , __A : float ): '''simple docstring''' snake_case: Optional[Any] = (AXIS_A - AXIS_B) / AXIS_A snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: List[Any] = atan((1 - flattening) * tan(radians(__A ) ) ) snake_case: Tuple = radians(__A ) snake_case: Tuple = radians(__A ) # Equation snake_case: List[Any] = sin((phi_a - phi_a) / 2 ) snake_case: Dict = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda snake_case: Union[str, Any] = sqrt(sin_sq_phi + (cos(__A ) * cos(__A ) * sin_sq_lambda) ) return 2 * RADIUS * asin(__A ) if __name__ == "__main__": import doctest doctest.testmod()
692
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/config.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/config.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json" ), "distilbert-base-uncased-finetuned-sst-2-english": ( "https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json" ), } class SCREAMING_SNAKE_CASE ( __lowerCamelCase ): '''simple docstring''' __UpperCamelCase = "distilbert" __UpperCamelCase = { "hidden_size": "dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", } def __init__( self , SCREAMING_SNAKE_CASE__=3_05_22 , SCREAMING_SNAKE_CASE__=5_12 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=6 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=7_68 , SCREAMING_SNAKE_CASE__=4 * 7_68 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.2 , SCREAMING_SNAKE_CASE__=0 , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: Dict = vocab_size snake_case: Union[str, Any] = max_position_embeddings snake_case: Dict = sinusoidal_pos_embds snake_case: List[str] = n_layers snake_case: Union[str, Any] = n_heads snake_case: Any = dim snake_case: Any = hidden_dim snake_case: Union[str, Any] = dropout snake_case: Union[str, Any] = attention_dropout snake_case: Union[str, Any] = activation snake_case: Optional[Any] = initializer_range snake_case: str = qa_dropout snake_case: str = seq_classif_dropout super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ ) class SCREAMING_SNAKE_CASE ( __lowerCamelCase ): '''simple docstring''' @property def _UpperCamelCase ( self ): '''simple docstring''' if self.task == "multiple-choice": snake_case: Union[str, Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: snake_case: Union[str, Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
706
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCAmelCase = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
692
0
'''simple docstring''' from math import factorial, pi def lowerCAmelCase_ ( __A : float , __A : int = 30 ): '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError('maclaurin_sin() requires either an int or float for theta' ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError('maclaurin_sin() requires a positive int for accuracy' ) snake_case: Dict = float(__A ) snake_case: Dict = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(__A ) ) def lowerCAmelCase_ ( __A : float , __A : int = 30 ): '''simple docstring''' if not isinstance(__A , (int, float) ): raise ValueError('maclaurin_cos() requires either an int or float for theta' ) if not isinstance(__A , __A ) or accuracy <= 0: raise ValueError('maclaurin_cos() requires a positive int for accuracy' ) snake_case: int = float(__A ) snake_case: int = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(10)) print(maclaurin_sin(-10)) print(maclaurin_sin(10, 15)) print(maclaurin_sin(-10, 15)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(10, 15)) print(maclaurin_cos(-10, 15))
707
'''simple docstring''' import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def lowerCAmelCase_ ( __A : Tuple ): '''simple docstring''' snake_case: Tuple = model.config snake_case: str = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=1_28 , ) snake_case: Optional[Any] = MBartConfig( is_decoder=__A , is_encoder_decoder=__A , add_cross_attention=__A , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=__A , add_final_layer_norm=__A , ) return encoder_config, decoder_config def lowerCAmelCase_ ( __A : int ): '''simple docstring''' if "encoder.model" in name: snake_case: Optional[Any] = name.replace('encoder.model' , 'encoder' ) if "decoder.model" in name: snake_case: str = name.replace('decoder.model' , 'decoder' ) if "patch_embed.proj" in name: snake_case: Any = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: snake_case: Optional[int] = name.replace('patch_embed.norm' , 'embeddings.norm' ) if name.startswith('encoder' ): if "layers" in name: snake_case: Tuple = 'encoder.' + name if "attn.proj" in name: snake_case: Optional[int] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name and "mask" not in name: snake_case: Dict = name.replace('attn' , 'attention.self' ) if "norm1" in name: snake_case: Union[str, Any] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: snake_case: Dict = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: snake_case: List[str] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: snake_case: Dict = name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": snake_case: Dict = 'encoder.layernorm.weight' if name == "encoder.norm.bias": snake_case: int = 'encoder.layernorm.bias' return name def lowerCAmelCase_ ( __A : List[Any] , __A : Optional[Any] ): '''simple docstring''' for key in orig_state_dict.copy().keys(): snake_case: List[Any] = orig_state_dict.pop(__A ) if "qkv" in key: snake_case: Union[str, Any] = key.split('.' ) snake_case: Optional[Any] = int(key_split[3] ) snake_case: Any = int(key_split[5] ) snake_case: Union[str, Any] = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: snake_case: Union[str, Any] = val[:dim, :] snake_case: Any = val[dim : dim * 2, :] snake_case: List[str] = val[-dim:, :] else: snake_case: str = val[:dim] snake_case: Union[str, Any] = val[dim : dim * 2] snake_case: List[Any] = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: snake_case: Optional[int] = val return orig_state_dict def lowerCAmelCase_ ( __A : List[Any] , __A : Any=None , __A : List[str]=False ): '''simple docstring''' snake_case: str = DonutModel.from_pretrained(__A ).eval() # load HuggingFace model snake_case , snake_case: Optional[Any] = get_configs(__A ) snake_case: Optional[int] = DonutSwinModel(__A ) snake_case: Tuple = MBartForCausalLM(__A ) snake_case: Optional[Any] = VisionEncoderDecoderModel(encoder=__A , decoder=__A ) model.eval() snake_case: Optional[int] = original_model.state_dict() snake_case: Optional[int] = convert_state_dict(__A , __A ) model.load_state_dict(__A ) # verify results on scanned document snake_case: Union[str, Any] = load_dataset('hf-internal-testing/example-documents' ) snake_case: str = dataset['test'][0]['image'].convert('RGB' ) snake_case: Optional[int] = XLMRobertaTokenizerFast.from_pretrained(__A , from_slow=__A ) snake_case: Any = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) snake_case: Dict = DonutProcessor(__A , __A ) snake_case: Optional[Any] = processor(__A , return_tensors='pt' ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": snake_case: int = '<s_docvqa><s_question>{user_input}</s_question><s_answer>' snake_case: Optional[Any] = 'When is the coffee break?' snake_case: Optional[int] = task_prompt.replace('{user_input}' , __A ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": snake_case: Dict = '<s_rvlcdip>' elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: snake_case: str = '<s_cord>' elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": snake_case: str = 's_cord-v2>' elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": snake_case: int = '<s_zhtrainticket>' elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt snake_case: Optional[Any] = 'hello world' else: raise ValueError('Model name not supported' ) snake_case: Optional[int] = original_model.decoder.tokenizer(__A , add_special_tokens=__A , return_tensors='pt' )[ 'input_ids' ] snake_case: Any = original_model.encoder.model.patch_embed(__A ) snake_case , snake_case: Dict = model.encoder.embeddings(__A ) assert torch.allclose(__A , __A , atol=1E-3 ) # verify encoder hidden states snake_case: Tuple = original_model.encoder(__A ) snake_case: List[str] = model.encoder(__A ).last_hidden_state assert torch.allclose(__A , __A , atol=1E-2 ) # verify decoder hidden states snake_case: List[Any] = original_model(__A , __A , __A ).logits snake_case: List[Any] = model(__A , decoder_input_ids=__A ).logits assert torch.allclose(__A , __A , atol=1E-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(__A ) processor.save_pretrained(__A ) if push_to_hub: model.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) processor.push_to_hub('nielsr/' + model_name.split('/' )[-1] , commit_message='Update model' ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) __UpperCAmelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
692
0
import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __UpperCAmelCase = logging.getLogger(__name__) def lowerCAmelCase_ ( __A : str , __A : Any ): '''simple docstring''' if os.path.exists(__A ): if os.path.exists(os.path.join(__A , 'config.json' ) ) and os.path.isfile( os.path.join(__A , 'config.json' ) ): os.remove(os.path.join(__A , 'config.json' ) ) if os.path.exists(os.path.join(__A , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(__A , 'pytorch_model.bin' ) ): os.remove(os.path.join(__A , 'pytorch_model.bin' ) ) else: os.makedirs(__A ) model.save_pretrained(__A ) def lowerCAmelCase_ ( __A : int , __A : Any=False ): '''simple docstring''' snake_case: Union[str, Any] = 2 if unlogit: snake_case: str = torch.pow(__A , __A ) snake_case: str = p * torch.log(__A ) snake_case: List[str] = 0 return -plogp.sum(dim=-1 ) def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' logger.info('lv, h >\t' + '\t'.join(f"""{x + 1}""" for x in range(len(__A ) ) ) ) for row in range(len(__A ) ): if tensor.dtype != torch.long: logger.info(f"""layer {row + 1}:\t""" + '\t'.join(f"""{x:.5f}""" for x in tensor[row].cpu().data ) ) else: logger.info(f"""layer {row + 1}:\t""" + '\t'.join(f"""{x:d}""" for x in tensor[row].cpu().data ) ) def lowerCAmelCase_ ( __A : Tuple , __A : Union[str, Any] , __A : List[str] , __A : Optional[Any]=True , __A : int=True , __A : List[Any]=None , __A : int=False ): '''simple docstring''' snake_case: Dict = model.config.num_hidden_layers, model.config.num_attention_heads snake_case: Optional[int] = torch.zeros(__A , __A ).to(args.device ) snake_case: Dict = torch.zeros(__A , __A ).to(args.device ) if head_mask is None: snake_case: List[Any] = torch.ones(__A , __A ).to(args.device ) head_mask.requires_grad_(requires_grad=__A ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: snake_case: int = None snake_case: str = 0.0 snake_case: Dict = 0.0 for step, inputs in enumerate(tqdm(__A , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): snake_case: Dict = tuple(t.to(args.device ) for t in inputs ) (snake_case ): int = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) snake_case: Union[str, Any] = model(__A , labels=__A , head_mask=__A ) # (loss), lm_logits, presents, (all hidden_states), (attentions) snake_case: int = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(__A ): snake_case: Any = entropy(attn.detach() , __A ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(__A ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: snake_case: Tuple = 2 snake_case: Any = torch.pow(torch.pow(__A , __A ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1E-20 if not args.dont_normalize_global_importance: snake_case: List[str] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(__A ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(__A ) logger.info('Head ranked by importance scores' ) snake_case: Any = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) snake_case: Union[str, Any] = torch.arange( head_importance.numel() , device=args.device ) snake_case: int = head_ranks.view_as(__A ) print_ad_tensor(__A ) return attn_entropy, head_importance, total_loss def lowerCAmelCase_ ( __A : Any , __A : Dict , __A : Optional[Any] ): '''simple docstring''' snake_case: List[Any] = compute_heads_importance(__A , __A , __A , compute_entropy=__A ) snake_case: Tuple = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , __A , original_score * args.masking_threshold ) snake_case: Tuple = torch.ones_like(__A ) snake_case: str = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) snake_case: Any = original_score while current_score >= original_score * args.masking_threshold: snake_case: Optional[int] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads snake_case: Dict = float('Inf' ) snake_case: List[Any] = head_importance.view(-1 ).sort()[1] if len(__A ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads snake_case: List[Any] = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) snake_case: Optional[int] = new_head_mask.view(-1 ) snake_case: Optional[Any] = 0.0 snake_case: Dict = new_head_mask.view_as(__A ) snake_case: Any = new_head_mask.clone().detach() print_ad_tensor(__A ) # Compute metric and head importance again snake_case: List[Any] = compute_heads_importance( __A , __A , __A , compute_entropy=__A , head_mask=__A ) snake_case: Optional[int] = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , __A , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_00 , ) logger.info('Final head mask' ) print_ad_tensor(__A ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def lowerCAmelCase_ ( __A : Dict , __A : int , __A : Dict , __A : int ): '''simple docstring''' snake_case: Optional[Any] = datetime.now() snake_case: int = compute_heads_importance( __A , __A , __A , compute_entropy=__A , compute_importance=__A , head_mask=__A ) snake_case: Tuple = 1 / loss snake_case: Union[str, Any] = datetime.now() - before_time snake_case: Dict = sum(p.numel() for p in model.parameters() ) snake_case: Tuple = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(__A ) ) } for k, v in heads_to_prune.items(): if isinstance(__A , __A ): snake_case: Optional[int] = [ v, ] assert sum(len(__A ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(__A ) snake_case: str = sum(p.numel() for p in model.parameters() ) snake_case: Optional[Any] = datetime.now() snake_case: List[str] = compute_heads_importance( __A , __A , __A , compute_entropy=__A , compute_importance=__A , head_mask=__A , actually_pruned=__A , ) snake_case: Any = 1 / loss snake_case: List[str] = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , __A , __A , pruned_num_params / original_num_params * 1_00 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , __A , __A ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 1_00 ) save_model(__A , args.output_dir ) def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=__A , type=__A , required=__A , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=__A , type=__A , required=__A , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=__A , type=__A , required=__A , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=__A , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=__A , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=__A , type=__A , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=__A , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=__A , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=__A , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=__A , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=1_28 , type=__A , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=__A , help='Batch size.' ) parser.add_argument('--seed' , type=__A , default=42 ) parser.add_argument('--local_rank' , type=__A , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=__A , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=__A , default='' , help='Can be used for distant debugging.' ) snake_case: str = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=__A ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: snake_case: Optional[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) snake_case: Dict = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) snake_case: Dict = torch.device('cuda' , args.local_rank ) snake_case: Dict = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) snake_case: int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: snake_case: Union[str, Any] = nn.parallel.DistributedDataParallel( __A , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=__A ) elif args.n_gpu > 1: snake_case: Any = nn.DataParallel(__A ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=__A ) torch.save(__A , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , __A ) # Prepare dataset snake_case: Union[str, Any] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) snake_case: Dict = (torch.from_numpy(__A ),) snake_case: Dict = TensorDataset(*__A ) snake_case: Optional[Any] = RandomSampler(__A ) snake_case: List[Any] = DataLoader(__A , sampler=__A , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(__A , __A , __A ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: snake_case: Tuple = mask_heads(__A , __A , __A ) prune_heads(__A , __A , __A , __A ) if __name__ == "__main__": main()
708
'''simple docstring''' 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 SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = { 'task_specific_params': { 'summarization': {'length_penalty': 1.0, 'max_length': 1_28, 'min_length': 12, 'num_beams': 4}, 'summarization_cnn': {'length_penalty': 2.0, 'max_length': 1_42, 'min_length': 56, 'num_beams': 4}, 'summarization_xsum': {'length_penalty': 1.0, 'max_length': 62, 'min_length': 11, 'num_beams': 6}, } } snake_case: Union[str, Any] = { 'task_specific_params.summarization.length_penalty': 1.0, 'task_specific_params.summarization.max_length': 1_28, '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': 1_42, '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(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Dict = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , x.transpose() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Tuple = np.random.randn(3 , 4 ) snake_case: Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(3 , 4 , 5 ) snake_case: Optional[int] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Dict = np.random.randn(3 , 4 , 5 ) snake_case: str = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Optional[int] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Optional[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) snake_case: Optional[int] = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: List[str] = np.random.randn(3 , 4 , 5 ) snake_case: Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: List[Any] = np.random.randn(3 , 4 ) snake_case: Tuple = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: str = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) ) snake_case: Any = np.random.randn(3 , 4 , 5 ) snake_case: List[str] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.squeeze(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: List[str] = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(1 , 3 , 4 ) snake_case: List[str] = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Optional[Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: int = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Any = np.random.randn(1 , 3 , 4 ) snake_case: Optional[Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) snake_case: Union[str, Any] = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Union[str, Any] = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(1 , 3 , 4 ) snake_case: List[Any] = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ ) ) ) ) snake_case: Tuple = np.random.randn(1 , 4 , 1 , 5 ) snake_case: Tuple = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) ) def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) @require_torch def _UpperCamelCase ( self ): '''simple docstring''' snake_case: int = np.random.randn(3 , 4 ) snake_case: Any = torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_tf def _UpperCamelCase ( self ): '''simple docstring''' snake_case: str = np.random.randn(3 , 4 ) snake_case: Any = tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_flax def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[Any] = np.random.randn(3 , 4 ) snake_case: int = jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.asarray(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) )
692
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL __UpperCAmelCase = logging.get_logger(__name__) def lowerCAmelCase_ ( __A : int ): '''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 SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = 1 / 2_55 , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' super().__init__(**_lowerCAmelCase ) snake_case: Optional[Any] = size if size is not None else {'shortest_edge': 2_56} snake_case: int = get_size_dict(_lowerCAmelCase , default_to_square=_lowerCAmelCase ) snake_case: Tuple = crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24} snake_case: List[Any] = get_size_dict(_lowerCAmelCase , param_name='crop_size' ) snake_case: Dict = do_resize snake_case: Tuple = size snake_case: str = do_center_crop snake_case: Optional[int] = crop_size snake_case: Optional[int] = resample snake_case: Optional[int] = do_rescale snake_case: List[str] = rescale_factor snake_case: str = offset snake_case: int = do_normalize snake_case: Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN snake_case: Optional[Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: Union[str, Any] = get_size_dict(_lowerCAmelCase , default_to_square=_lowerCAmelCase ) if "shortest_edge" in size: snake_case: List[Any] = get_resize_output_image_size(_lowerCAmelCase , size['shortest_edge'] , default_to_square=_lowerCAmelCase ) elif "height" in size and "width" in size: snake_case: List[str] = (size['height'], size['width']) else: raise ValueError(F"""Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}""" ) return resize(_lowerCAmelCase , size=_lowerCAmelCase , resample=_lowerCAmelCase , data_format=_lowerCAmelCase , **_lowerCAmelCase ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: List[Any] = get_size_dict(_lowerCAmelCase ) 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(_lowerCAmelCase , size=(size['height'], size['width']) , data_format=_lowerCAmelCase , **_lowerCAmelCase ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: List[Any] = image.astype(np.floataa ) if offset: snake_case: str = image - (scale / 2) return rescale(_lowerCAmelCase , scale=_lowerCAmelCase , data_format=_lowerCAmelCase , **_lowerCAmelCase ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' return normalize(_lowerCAmelCase , mean=_lowerCAmelCase , std=_lowerCAmelCase , data_format=_lowerCAmelCase , **_lowerCAmelCase ) def _UpperCamelCase ( 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__ = ChannelDimension.FIRST , ): '''simple docstring''' if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) if offset and not do_rescale: raise ValueError('For offset, do_rescale must also be set to True.' ) # All transformations expect numpy arrays. snake_case: Union[str, Any] = to_numpy_array(_lowerCAmelCase ) if do_resize: snake_case: str = self.resize(image=_lowerCAmelCase , size=_lowerCAmelCase , resample=_lowerCAmelCase ) if do_center_crop: snake_case: int = self.center_crop(_lowerCAmelCase , size=_lowerCAmelCase ) if do_rescale: snake_case: Union[str, Any] = self.rescale(image=_lowerCAmelCase , scale=_lowerCAmelCase , offset=_lowerCAmelCase ) if do_normalize: snake_case: Union[str, Any] = self.normalize(image=_lowerCAmelCase , mean=_lowerCAmelCase , std=_lowerCAmelCase ) snake_case: str = to_channel_dimension_format(_lowerCAmelCase , _lowerCAmelCase ) return image def _UpperCamelCase ( 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: Optional[int] = do_resize if do_resize is not None else self.do_resize snake_case: Optional[int] = resample if resample is not None else self.resample snake_case: Tuple = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case: str = 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: int = offset if offset is not None else self.offset snake_case: Tuple = do_normalize if do_normalize is not None else self.do_normalize snake_case: Union[str, Any] = image_mean if image_mean is not None else self.image_mean snake_case: List[Any] = image_std if image_std is not None else self.image_std snake_case: int = size if size is not None else self.size snake_case: Optional[int] = get_size_dict(_lowerCAmelCase , default_to_square=_lowerCAmelCase ) snake_case: str = crop_size if crop_size is not None else self.crop_size snake_case: List[str] = get_size_dict(_lowerCAmelCase , param_name='crop_size' ) if not valid_images(_lowerCAmelCase ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) snake_case: str = make_batched(_lowerCAmelCase ) snake_case: int = [ [ self._preprocess_image( image=_lowerCAmelCase , do_resize=_lowerCAmelCase , size=_lowerCAmelCase , resample=_lowerCAmelCase , do_center_crop=_lowerCAmelCase , crop_size=_lowerCAmelCase , do_rescale=_lowerCAmelCase , rescale_factor=_lowerCAmelCase , offset=_lowerCAmelCase , do_normalize=_lowerCAmelCase , image_mean=_lowerCAmelCase , image_std=_lowerCAmelCase , data_format=_lowerCAmelCase , ) for img in video ] for video in videos ] snake_case: Union[str, Any] = {'pixel_values': videos} return BatchFeature(data=_lowerCAmelCase , tensor_type=_lowerCAmelCase )
709
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig __UpperCAmelCase = logging.get_logger(__name__) # General docstring __UpperCAmelCase = "PoolFormerConfig" # Base docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = [1, 512, 7, 7] # Image classification docstring __UpperCAmelCase = "sail/poolformer_s12" __UpperCAmelCase = "tabby, tabby cat" __UpperCAmelCase = [ "sail/poolformer_s12", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCAmelCase_ ( __A : Tuple , __A : float = 0.0 , __A : bool = False ): '''simple docstring''' if drop_prob == 0.0 or not training: return input snake_case: Union[str, Any] = 1 - drop_prob snake_case: List[Any] = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets snake_case: List[Any] = keep_prob + torch.rand(__A , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize snake_case: Any = input.div(__A ) * random_tensor return output class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' super().__init__() snake_case: List[str] = drop_prob def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return drop_path(SCREAMING_SNAKE_CASE__ , self.drop_prob , self.training ) def _UpperCamelCase ( self ): '''simple docstring''' return "p={}".format(self.drop_prob ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): '''simple docstring''' super().__init__() snake_case: List[str] = patch_size if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (patch_size, patch_size) snake_case: List[str] = stride if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (stride, stride) snake_case: Union[str, Any] = padding if isinstance(SCREAMING_SNAKE_CASE__ , collections.abc.Iterable ) else (padding, padding) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , kernel_size=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) snake_case: Tuple = norm_layer(SCREAMING_SNAKE_CASE__ ) if norm_layer else nn.Identity() def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.projection(SCREAMING_SNAKE_CASE__ ) snake_case: Any = self.norm(SCREAMING_SNAKE_CASE__ ) return embeddings class SCREAMING_SNAKE_CASE ( nn.GroupNorm ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(1 , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: str = nn.AvgPoolad(SCREAMING_SNAKE_CASE__ , stride=1 , padding=pool_size // 2 , count_include_pad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.pool(SCREAMING_SNAKE_CASE__ ) - hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: Any = nn.Convad(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) snake_case: str = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if isinstance(config.hidden_act , SCREAMING_SNAKE_CASE__ ): snake_case: Tuple = ACTaFN[config.hidden_act] else: snake_case: int = config.hidden_act def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Dict = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = self.act_fn(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.drop(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = self.conva(SCREAMING_SNAKE_CASE__ ) snake_case: str = self.drop(SCREAMING_SNAKE_CASE__ ) return hidden_states class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Tuple = PoolFormerPooling(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerOutput(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) snake_case: Dict = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = PoolFormerGroupNorm(SCREAMING_SNAKE_CASE__ ) # Useful for training neural nets snake_case: Union[str, Any] = PoolFormerDropPath(SCREAMING_SNAKE_CASE__ ) if drop_path > 0.0 else nn.Identity() snake_case: Optional[Any] = config.use_layer_scale if config.use_layer_scale: snake_case: Any = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) snake_case: int = nn.Parameter( config.layer_scale_init_value * torch.ones((SCREAMING_SNAKE_CASE__) ) , requires_grad=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if self.use_layer_scale: snake_case: str = self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Dict = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection snake_case: str = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: Dict = () snake_case: Dict = self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) snake_case: Union[str, Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection snake_case: Any = hidden_states + self.drop_path(SCREAMING_SNAKE_CASE__ ) snake_case: List[str] = (output,) + outputs return outputs else: snake_case: Optional[Any] = self.drop_path(self.pooling(self.before_norm(SCREAMING_SNAKE_CASE__ ) ) ) # First residual connection snake_case: Union[str, Any] = pooling_output + hidden_states snake_case: List[Any] = () # Second residual connection inside the PoolFormerOutput block snake_case: List[str] = self.drop_path(self.output(self.after_norm(SCREAMING_SNAKE_CASE__ ) ) ) snake_case: Dict = hidden_states + layer_output snake_case: Optional[Any] = (output,) + outputs return outputs class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: List[Any] = config # stochastic depth decay rule snake_case: List[Any] = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings snake_case: Union[str, Any] = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) snake_case: List[Any] = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) # Transformer blocks snake_case: str = [] snake_case: int = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers snake_case: List[str] = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( SCREAMING_SNAKE_CASE__ , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(SCREAMING_SNAKE_CASE__ ) ) snake_case: Tuple = nn.ModuleList(SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=True ): '''simple docstring''' snake_case: str = () if output_hidden_states else None snake_case: Dict = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): snake_case , snake_case: Dict = layers # Get patch embeddings from hidden_states snake_case: int = embedding_layer(SCREAMING_SNAKE_CASE__ ) # Send the embeddings through the blocks for _, blk in enumerate(SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = blk(SCREAMING_SNAKE_CASE__ ) snake_case: Optional[int] = layer_outputs[0] if output_hidden_states: snake_case: List[str] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = PoolFormerConfig __UpperCamelCase = "poolformer" __UpperCamelCase = "pixel_values" __UpperCamelCase = True def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(SCREAMING_SNAKE_CASE__ , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ): '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case: List[Any] = value __UpperCAmelCase = R"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" __UpperCAmelCase = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n" @add_start_docstrings( "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top." , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: List[Any] = config snake_case: Tuple = PoolFormerEncoder(SCREAMING_SNAKE_CASE__ ) # Initialize weights and apply final processing self.post_init() def _UpperCamelCase ( self ): '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Optional[int] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case: List[Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) snake_case: Optional[Any] = self.encoder( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: List[Any] = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=SCREAMING_SNAKE_CASE__ , hidden_states=encoder_outputs.hidden_states , ) class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__() snake_case: Any = nn.Linear(config.hidden_size , config.hidden_size ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: int = self.dense(SCREAMING_SNAKE_CASE__ ) return output @add_start_docstrings( "\n PoolFormer Model transformer with an image classification head on top\n " , snake_case , ) class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' def __init__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' super().__init__(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = config.num_labels snake_case: str = PoolFormerModel(SCREAMING_SNAKE_CASE__ ) # Final norm snake_case: int = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head snake_case: Dict = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): '''simple docstring''' snake_case: Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict snake_case: Optional[Any] = self.poolformer( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ , ) snake_case: Any = outputs[0] snake_case: str = self.classifier(self.norm(SCREAMING_SNAKE_CASE__ ).mean([-2, -1] ) ) snake_case: Any = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: snake_case: Tuple = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): snake_case: Dict = 'single_label_classification' else: snake_case: List[str] = 'multi_label_classification' if self.config.problem_type == "regression": snake_case: Union[str, Any] = MSELoss() if self.num_labels == 1: snake_case: List[str] = loss_fct(logits.squeeze() , labels.squeeze() ) else: snake_case: int = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.config.problem_type == "single_label_classification": snake_case: Union[str, Any] = CrossEntropyLoss() snake_case: Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": snake_case: int = BCEWithLogitsLoss() snake_case: Optional[int] = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not return_dict: snake_case: str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=SCREAMING_SNAKE_CASE__ , logits=SCREAMING_SNAKE_CASE__ , hidden_states=outputs.hidden_states )
692
0
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all BART models at https://huggingface.co/models?filter=bart __UpperCAmelCase = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, } __UpperCAmelCase = { "facebook/bart-base": 1_024, "facebook/bart-large": 1_024, "facebook/bart-large-mnli": 1_024, "facebook/bart-large-cnn": 1_024, "facebook/bart-large-xsum": 1_024, "yjernite/bart_eli5": 1_024, } @lru_cache() def lowerCAmelCase_ ( ): '''simple docstring''' snake_case: Dict = ( list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) ) ) snake_case: Optional[Any] = bs[:] snake_case: Optional[int] = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCamelCase__ ) cs.append(2**8 + n ) n += 1 snake_case: Dict = [chr(lowerCamelCase__ ) for n in cs] return dict(zip(lowerCamelCase__ , lowerCamelCase__ ) ) def lowerCAmelCase_ ( __A : Optional[int] ): '''simple docstring''' snake_case: Dict = set() snake_case: Union[str, Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) snake_case: Optional[Any] = char return pairs class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="replace" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__="<mask>" , SCREAMING_SNAKE_CASE__=False , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: str = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else bos_token snake_case: List[str] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else eos_token snake_case: Optional[int] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else sep_token snake_case: int = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else cls_token snake_case: Optional[int] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else unk_token snake_case: Dict = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it snake_case: Union[str, Any] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else mask_token super().__init__( errors=UpperCamelCase_ , bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , add_prefix_space=UpperCamelCase_ , **UpperCamelCase_ , ) with open(UpperCamelCase_ , encoding='utf-8' ) as vocab_handle: snake_case: int = json.load(UpperCamelCase_ ) snake_case: Any = {v: k for k, v in self.encoder.items()} snake_case: Any = errors # how to handle errors in decoding snake_case: str = bytes_to_unicode() snake_case: List[str] = {v: k for k, v in self.byte_encoder.items()} with open(UpperCamelCase_ , encoding='utf-8' ) as merges_handle: snake_case: str = merges_handle.read().split('\n' )[1:-1] snake_case: List[str] = [tuple(merge.split() ) for merge in bpe_merges] snake_case: Union[str, Any] = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) ) snake_case: Optional[int] = {} snake_case: Optional[int] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions snake_case: Dict = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property def _UpperCamelCase ( self ): '''simple docstring''' return len(self.encoder ) def _UpperCamelCase ( self ): '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if token in self.cache: return self.cache[token] snake_case: List[str] = tuple(UpperCamelCase_ ) snake_case: str = get_pairs(UpperCamelCase_ ) if not pairs: return token while True: snake_case: str = min(UpperCamelCase_ , key=lambda SCREAMING_SNAKE_CASE__ : self.bpe_ranks.get(UpperCamelCase_ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break snake_case: List[Any] = bigram snake_case: Any = [] snake_case: List[str] = 0 while i < len(UpperCamelCase_ ): try: snake_case: Union[str, Any] = word.index(UpperCamelCase_ , UpperCamelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) snake_case: str = j if word[i] == first and i < len(UpperCamelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 snake_case: Dict = tuple(UpperCamelCase_ ) snake_case: str = new_word if len(UpperCamelCase_ ) == 1: break else: snake_case: int = get_pairs(UpperCamelCase_ ) snake_case: Optional[int] = " ".join(UpperCamelCase_ ) snake_case: Dict = word return word def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = [] for token in re.findall(self.pat , UpperCamelCase_ ): snake_case: Any = "".join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(UpperCamelCase_ ).split(' ' ) ) return bpe_tokens def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.encoder.get(UpperCamelCase_ , self.encoder.get(self.unk_token ) ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.decoder.get(UpperCamelCase_ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[str] = "".join(UpperCamelCase_ ) snake_case: Union[str, Any] = bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if not os.path.isdir(UpperCamelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case: Any = os.path.join( UpperCamelCase_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) snake_case: Optional[int] = os.path.join( UpperCamelCase_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(UpperCamelCase_ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCamelCase_ , ensure_ascii=UpperCamelCase_ ) + '\n' ) snake_case: str = 0 with open(UpperCamelCase_ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE__ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ' Please check that the tokenizer is not corrupted!' ) snake_case: str = token_index writer.write(' '.join(UpperCamelCase_ ) + '\n' ) index += 1 return vocab_file, merge_file def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case: List[Any] = [self.cls_token_id] snake_case: Tuple = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=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, 1] + ([0] * len(UpperCamelCase_ )) + [1] def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' snake_case: int = [self.sep_token_id] snake_case: List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , **SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: List[str] = kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(UpperCamelCase_ ) > 0 and not text[0].isspace()): snake_case: Tuple = " " + text return (text, kwargs)
710
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def lowerCAmelCase_ ( __A : dict , __A : str , __A : set , __A : set , __A : dict , __A : dict , __A : PriorityQueue , __A : dict , __A : float | int , ): '''simple docstring''' for nxt, d in graph[v]: if nxt in visited_forward: continue snake_case: Any = cst_fwd.get(__A , np.inf ) snake_case: int = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) snake_case: Union[str, Any] = new_cost_f snake_case: Tuple = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: snake_case: List[str] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def lowerCAmelCase_ ( __A : str , __A : str , __A : dict , __A : dict ): '''simple docstring''' snake_case: Optional[Any] = -1 snake_case: Any = set() snake_case: str = set() snake_case: int = {source: 0} snake_case: Dict = {destination: 0} snake_case: int = {source: None} snake_case: Union[str, Any] = {destination: None} snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: PriorityQueue[Any] = PriorityQueue() snake_case: Tuple = 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(): snake_case , snake_case: List[str] = queue_forward.get() visited_forward.add(__A ) snake_case , snake_case: int = queue_backward.get() visited_backward.add(__A ) snake_case: str = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) snake_case: Optional[Any] = pass_and_relaxation( __A , __A , __A , __A , __A , __A , __A , __A , __A , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: snake_case: Any = shortest_distance return shortest_path_distance __UpperCAmelCase = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } __UpperCAmelCase = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
692
0
'''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_albert import AlbertTokenizer else: __UpperCAmelCase = None __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __UpperCAmelCase = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', }, 'tokenizer_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json', }, } __UpperCAmelCase = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __UpperCAmelCase = '▁' class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = AlbertTokenizer def __init__( self , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__="[CLS]" , SCREAMING_SNAKE_CASE__="[SEP]" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="[SEP]" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__="[CLS]" , SCREAMING_SNAKE_CASE__="[MASK]" , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: Union[str, Any] = ( AddedToken(__A , lstrip=__A , rstrip=__A , normalized=__A ) if isinstance(__A , __A ) else mask_token ) super().__init__( __A , tokenizer_file=__A , do_lower_case=__A , remove_space=__A , keep_accents=__A , bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , pad_token=__A , cls_token=__A , mask_token=__A , **__A , ) snake_case: Dict = do_lower_case snake_case: List[str] = remove_space snake_case: Any = keep_accents snake_case: Tuple = vocab_file snake_case: Optional[int] = False if not self.vocab_file else True def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' snake_case: List[Any] = [self.sep_token_id] snake_case: Any = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' snake_case: Optional[Any] = [self.sep_token_id] snake_case: 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] def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 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(__A ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case: Union[str, Any] = os.path.join( __A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ): copyfile(self.vocab_file , __A ) return (out_vocab_file,)
711
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = "▁" __UpperCAmelCase = {"vocab_file": "sentencepiece.bpe.model"} __UpperCAmelCase = { "vocab_file": { "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model", } } __UpperCAmelCase = { "facebook/xglm-564M": 2_048, } class SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ): '''simple docstring''' snake_case: Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs # Compatibility with the original tokenizer snake_case: Optional[Any] = 7 snake_case: List[str] = [F"""<madeupword{i}>""" for i in range(self.num_madeup_words )] snake_case: str = kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ word for word in madeup_words if word not in kwargs["additional_special_tokens"] ] super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) snake_case: int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE__ ) ) snake_case: int = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab snake_case: Tuple = 1 # Mimic fairseq token-to-id alignment for the first 4 token snake_case: Optional[Any] = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} snake_case: Union[str, Any] = len(self.sp_model ) snake_case: str = {F"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )} self.fairseq_tokens_to_ids.update(SCREAMING_SNAKE_CASE__ ) snake_case: Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ): '''simple docstring''' snake_case: List[Any] = self.__dict__.copy() snake_case: Union[str, Any] = None snake_case: Union[str, Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[int] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): snake_case: Union[str, Any] = {} snake_case: Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if token_ids_a is None: return [self.sep_token_id] + token_ids_a snake_case: Optional[Any] = [self.sep_token_id] return sep + token_ids_a + sep + sep + token_ids_a def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' snake_case: int = [self.sep_token_id] if token_ids_a is None: return len(sep + token_ids_a ) * [0] return len(sep + token_ids_a + sep + sep + token_ids_a ) * [0] @property def _UpperCamelCase ( self ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words def _UpperCamelCase ( self ): '''simple docstring''' snake_case: Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case: Dict = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ ): '''simple docstring''' snake_case: Optional[Any] = ''.join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , ' ' ).strip() return out_string def _UpperCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case: List[str] = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: snake_case: int = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
692
0
'''simple docstring''' def lowerCAmelCase_ ( __A : List[str] , __A : Tuple ): '''simple docstring''' return "\n".join( f"""{number} * {i} = {number * i}""" for i in range(1 , number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
712
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowerCAmelCase_ ( __A : Optional[Any] ): '''simple docstring''' return getitem, k def lowerCAmelCase_ ( __A : Any , __A : Optional[int] ): '''simple docstring''' return setitem, k, v def lowerCAmelCase_ ( __A : List[str] ): '''simple docstring''' return delitem, k def lowerCAmelCase_ ( __A : str , __A : int , *__A : Tuple ): '''simple docstring''' try: return fun(__A , *__A ), None except Exception as e: return None, e __UpperCAmelCase = ( _set("key_a", "val_a"), _set("key_b", "val_b"), ) __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_a", "val_b"), ] __UpperCAmelCase = [ _set("key_a", "val_a"), _set("key_b", "val_b"), _del("key_a"), _del("key_b"), _set("key_a", "val_a"), _del("key_a"), ] __UpperCAmelCase = [ _get("key_a"), _del("key_a"), _set("key_a", "val_a"), _del("key_a"), _del("key_a"), _get("key_a"), ] __UpperCAmelCase = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] __UpperCAmelCase = [ *[_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 lowerCAmelCase_ ( __A : str ): '''simple docstring''' snake_case: List[Any] = HashMap(initial_block_size=4 ) snake_case: List[Any] = {} for _, (fun, *args) in enumerate(__A ): snake_case , snake_case: Optional[int] = _run_operation(__A , __A , *__A ) snake_case , snake_case: str = _run_operation(__A , __A , *__A ) assert my_res == py_res assert str(__A ) == str(__A ) assert set(__A ) == set(__A ) assert len(__A ) == len(__A ) assert set(my.items() ) == set(py.items() ) def lowerCAmelCase_ ( ): '''simple docstring''' def is_public(__A : str ) -> bool: return not name.startswith('_' ) snake_case: Dict = {name for name in dir({} ) if is_public(__A )} snake_case: List[str] = {name for name in dir(HashMap() ) if is_public(__A )} assert dict_public_names > hash_public_names
692
0