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
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin _a : Optional[int] = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class a_ ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): A__ : Dict = SpeechTaTokenizer A__ : Union[str, Any] = False A__ : str = True def lowerCAmelCase( self : Optional[int] ): super().setUp() # We have a SentencePiece fixture for testing snake_case : Tuple = SpeechTaTokenizer(_lowercase ) snake_case : List[str] = AddedToken('''<mask>''' , lstrip=_lowercase , rstrip=_lowercase ) snake_case : int = mask_token tokenizer.add_special_tokens({'''mask_token''': mask_token} ) tokenizer.add_tokens(['''<ctc_blank>'''] ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] ): snake_case : Optional[int] = """this is a test""" snake_case : Dict = """this is a test""" return input_text, output_text def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : str=20 , UpperCAmelCase__ : int=5 ): snake_case : str = self.get_input_output_texts(_lowercase ) snake_case : List[Any] = tokenizer.encode(_lowercase , add_special_tokens=_lowercase ) snake_case : Optional[Any] = tokenizer.decode(_lowercase , clean_up_tokenization_spaces=_lowercase ) return text, ids def lowerCAmelCase( self : List[str] ): snake_case : List[str] = """<pad>""" snake_case : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowercase ) , _lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowercase ) , _lowercase ) def lowerCAmelCase( self : Dict ): snake_case : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-4] , '''œ''' ) self.assertEqual(vocab_keys[-2] , '''<mask>''' ) self.assertEqual(vocab_keys[-1] , '''<ctc_blank>''' ) self.assertEqual(len(_lowercase ) , 81 ) def lowerCAmelCase( self : List[str] ): self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def lowerCAmelCase( self : List[str] ): snake_case : List[Any] = self.get_tokenizers(do_lower_case=_lowercase ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): snake_case : Optional[Any] = tokenizer.vocab_size snake_case : str = len(_lowercase ) self.assertNotEqual(_lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) snake_case : Dict = ["""aaaaa bbbbbb""", """cccccccccdddddddd"""] snake_case : Optional[Any] = tokenizer.add_tokens(_lowercase ) snake_case : int = tokenizer.vocab_size snake_case : int = len(_lowercase ) self.assertNotEqual(_lowercase , 0 ) self.assertEqual(_lowercase , _lowercase ) self.assertEqual(_lowercase , len(_lowercase ) ) self.assertEqual(_lowercase , all_size + len(_lowercase ) ) snake_case : Optional[int] = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=_lowercase ) self.assertGreaterEqual(len(_lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) snake_case : Optional[Any] = {"""eos_token""": """>>>>|||<||<<|<<""", """pad_token""": """<<<<<|||>|>>>>|>"""} snake_case : str = tokenizer.add_special_tokens(_lowercase ) snake_case : List[Any] = tokenizer.vocab_size snake_case : Tuple = len(_lowercase ) self.assertNotEqual(_lowercase , 0 ) self.assertEqual(_lowercase , _lowercase ) self.assertEqual(_lowercase , len(_lowercase ) ) self.assertEqual(_lowercase , all_size_a + len(_lowercase ) ) snake_case : List[str] = tokenizer.encode( '''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=_lowercase ) self.assertGreaterEqual(len(_lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def lowerCAmelCase( self : str ): pass def lowerCAmelCase( self : Tuple ): pass def lowerCAmelCase( self : Any ): snake_case : Any = self.get_tokenizer() snake_case : Any = tokenizer.tokenize('''This is a test''' ) # fmt: off self.assertListEqual(_lowercase , [SPIECE_UNDERLINE, '''T''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''a''', SPIECE_UNDERLINE, '''t''', '''e''', '''s''', '''t'''] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) snake_case : Any = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''92000''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) snake_case : List[str] = tokenizer.convert_tokens_to_ids(_lowercase ) # fmt: off self.assertListEqual(_lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on snake_case : List[str] = tokenizer.convert_ids_to_tokens(_lowercase ) self.assertListEqual( _lowercase , [SPIECE_UNDERLINE, '''I''', SPIECE_UNDERLINE, '''w''', '''a''', '''s''', SPIECE_UNDERLINE, '''b''', '''o''', '''r''', '''n''', SPIECE_UNDERLINE, '''i''', '''n''', SPIECE_UNDERLINE, '''<unk>''', ''',''', SPIECE_UNDERLINE, '''a''', '''n''', '''d''', SPIECE_UNDERLINE, '''t''', '''h''', '''i''', '''s''', SPIECE_UNDERLINE, '''i''', '''s''', SPIECE_UNDERLINE, '''f''', '''a''', '''l''', '''s''', '''é''', '''.'''] ) @slow def lowerCAmelCase( self : str ): snake_case : Tuple = [ """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """ """general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural """ """Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained """ """models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.""", """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """ """conditioning on both left and right context in all layers.""", """The quick brown fox jumps over the lazy dog.""", ] # fmt: off snake_case : int = { """input_ids""": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], """attention_mask""": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowercase , model_name='''microsoft/speecht5_asr''' , revision='''c5ef64c71905caeccde0e4462ef3f9077224c524''' , sequences=_lowercase , )
721
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" snake_case , snake_case : Any = image.size snake_case , snake_case : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 snake_case : List[str] = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) snake_case : Dict = np.array(__magic_name__ ).astype(np.floataa ) / 255.0 snake_case : Optional[Any] = image[None].transpose(0 , 3 , 1 , 2 ) snake_case : Tuple = torch.from_numpy(__magic_name__ ) return 2.0 * image - 1.0 class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : VQModel , UpperCAmelCase__ : UNetaDModel , UpperCAmelCase__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ): """simple docstring""" super().__init__() self.register_modules(vqvae=UpperCAmelCase__ , unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) @torch.no_grad() def __call__( self : Any , UpperCAmelCase__ : Union[torch.Tensor, PIL.Image.Image] = None , UpperCAmelCase__ : Optional[int] = 1 , UpperCAmelCase__ : Optional[int] = 100 , UpperCAmelCase__ : Optional[float] = 0.0 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" if isinstance(UpperCAmelCase__ , PIL.Image.Image ): snake_case : Optional[int] = 1 elif isinstance(UpperCAmelCase__ , torch.Tensor ): snake_case : Any = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(UpperCAmelCase__ )}" ) if isinstance(UpperCAmelCase__ , PIL.Image.Image ): snake_case : Optional[Any] = preprocess(UpperCAmelCase__ ) snake_case , snake_case : Union[str, Any] = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image snake_case : List[Any] = (batch_size, self.unet.config.in_channels // 2, height, width) snake_case : str = next(self.unet.parameters() ).dtype snake_case : Dict = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=self.device , dtype=UpperCAmelCase__ ) snake_case : Any = image.to(device=self.device , dtype=UpperCAmelCase__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(UpperCAmelCase__ , device=self.device ) snake_case : Optional[Any] = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler snake_case : Union[str, Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] snake_case : Any = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case : Optional[Any] = {} if accepts_eta: snake_case : Dict = eta for t in self.progress_bar(UpperCAmelCase__ ): # concat latents and low resolution image in the channel dimension. snake_case : Optional[int] = torch.cat([latents, image] , dim=1 ) snake_case : str = self.scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) # predict the noise residual snake_case : int = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case : Any = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample # decode the image latents with the VQVAE snake_case : Optional[int] = self.vqvae.decode(UpperCAmelCase__ ).sample snake_case : int = torch.clamp(UpperCAmelCase__ , -1.0 , 1.0 ) snake_case : Dict = image / 2 + 0.5 snake_case : int = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case : Any = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
84
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() _a : int = logging.get_logger(__name__) def a_ ( __magic_name__ ) -> List[str]: """simple docstring""" if "resnet-50" in model_name: snake_case : List[Any] = ResNetConfig.from_pretrained('''microsoft/resnet-50''' ) elif "resnet-101" in model_name: snake_case : Optional[int] = ResNetConfig.from_pretrained('''microsoft/resnet-101''' ) else: raise ValueError('''Model name should include either resnet50 or resnet101''' ) snake_case : Tuple = DetrConfig(use_timm_backbone=snake_case__ , backbone_config=snake_case__ ) # set label attributes snake_case : Dict = '''panoptic''' in model_name if is_panoptic: snake_case : Optional[int] = 250 else: snake_case : Dict = 91 snake_case : Union[str, Any] = '''huggingface/label-files''' snake_case : List[str] = '''coco-detection-id2label.json''' snake_case : str = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='''dataset''' ) , '''r''' ) ) snake_case : int = {int(snake_case__ ): v for k, v in idalabel.items()} snake_case : Any = idalabel snake_case : Dict = {v: k for k, v in idalabel.items()} return config, is_panoptic def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" snake_case : Tuple = [] # stem # fmt: off rename_keys.append(('''backbone.0.body.conv1.weight''', '''backbone.conv_encoder.model.embedder.embedder.convolution.weight''') ) rename_keys.append(('''backbone.0.body.bn1.weight''', '''backbone.conv_encoder.model.embedder.embedder.normalization.weight''') ) rename_keys.append(('''backbone.0.body.bn1.bias''', '''backbone.conv_encoder.model.embedder.embedder.normalization.bias''') ) rename_keys.append(('''backbone.0.body.bn1.running_mean''', '''backbone.conv_encoder.model.embedder.embedder.normalization.running_mean''') ) rename_keys.append(('''backbone.0.body.bn1.running_var''', '''backbone.conv_encoder.model.embedder.embedder.normalization.running_var''') ) # stages for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): # shortcut if layer_idx == 0: rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var", ) ) # 3 convs for i in range(3 ): rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean", ) ) rename_keys.append( ( F"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var", F"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var", ) ) # fmt: on for i in range(config.encoder_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( F"transformer.encoder.layers.{i}.self_attn.out_proj.weight", F"encoder.layers.{i}.self_attn.out_proj.weight", ) ) rename_keys.append( (F"transformer.encoder.layers.{i}.self_attn.out_proj.bias", F"encoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear1.weight", F"encoder.layers.{i}.fc1.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear1.bias", F"encoder.layers.{i}.fc1.bias") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear2.weight", F"encoder.layers.{i}.fc2.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.linear2.bias", F"encoder.layers.{i}.fc2.bias") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm1.weight", F"encoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm1.bias", F"encoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.encoder.layers.{i}.norm2.weight", F"encoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((F"transformer.encoder.layers.{i}.norm2.bias", F"encoder.layers.{i}.final_layer_norm.bias") ) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( F"transformer.decoder.layers.{i}.self_attn.out_proj.weight", F"decoder.layers.{i}.self_attn.out_proj.weight", ) ) rename_keys.append( (F"transformer.decoder.layers.{i}.self_attn.out_proj.bias", F"decoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append( ( F"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight", F"decoder.layers.{i}.encoder_attn.out_proj.weight", ) ) rename_keys.append( ( F"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias", F"decoder.layers.{i}.encoder_attn.out_proj.bias", ) ) rename_keys.append((F"transformer.decoder.layers.{i}.linear1.weight", F"decoder.layers.{i}.fc1.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear1.bias", F"decoder.layers.{i}.fc1.bias") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear2.weight", F"decoder.layers.{i}.fc2.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.linear2.bias", F"decoder.layers.{i}.fc2.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm1.weight", F"decoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm1.bias", F"decoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm2.weight", F"decoder.layers.{i}.encoder_attn_layer_norm.weight") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm2.bias", F"decoder.layers.{i}.encoder_attn_layer_norm.bias") ) rename_keys.append( (F"transformer.decoder.layers.{i}.norm3.weight", F"decoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((F"transformer.decoder.layers.{i}.norm3.bias", F"decoder.layers.{i}.final_layer_norm.bias") ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ('''input_proj.weight''', '''input_projection.weight'''), ('''input_proj.bias''', '''input_projection.bias'''), ('''query_embed.weight''', '''query_position_embeddings.weight'''), ('''transformer.decoder.norm.weight''', '''decoder.layernorm.weight'''), ('''transformer.decoder.norm.bias''', '''decoder.layernorm.bias'''), ('''class_embed.weight''', '''class_labels_classifier.weight'''), ('''class_embed.bias''', '''class_labels_classifier.bias'''), ('''bbox_embed.layers.0.weight''', '''bbox_predictor.layers.0.weight'''), ('''bbox_embed.layers.0.bias''', '''bbox_predictor.layers.0.bias'''), ('''bbox_embed.layers.1.weight''', '''bbox_predictor.layers.1.weight'''), ('''bbox_embed.layers.1.bias''', '''bbox_predictor.layers.1.bias'''), ('''bbox_embed.layers.2.weight''', '''bbox_predictor.layers.2.weight'''), ('''bbox_embed.layers.2.bias''', '''bbox_predictor.layers.2.bias'''), ] ) return rename_keys def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> int: """simple docstring""" snake_case : List[Any] = state_dict.pop(snake_case__ ) snake_case : Dict = val def a_ ( __magic_name__ , __magic_name__=False ) -> Tuple: """simple docstring""" snake_case : Dict = '''''' if is_panoptic: snake_case : Tuple = '''detr.''' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) snake_case : Any = state_dict.pop(F"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight" ) snake_case : Tuple = state_dict.pop(F"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict snake_case : Union[str, Any] = in_proj_weight[:256, :] snake_case : Tuple = in_proj_bias[:256] snake_case : Dict = in_proj_weight[256:512, :] snake_case : Union[str, Any] = in_proj_bias[256:512] snake_case : List[str] = in_proj_weight[-256:, :] snake_case : str = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention snake_case : List[str] = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight" ) snake_case : str = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict snake_case : Any = in_proj_weight[:256, :] snake_case : List[Any] = in_proj_bias[:256] snake_case : List[Any] = in_proj_weight[256:512, :] snake_case : Dict = in_proj_bias[256:512] snake_case : str = in_proj_weight[-256:, :] snake_case : Optional[int] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention snake_case : Any = state_dict.pop( F"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight" ) snake_case : Any = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias" ) # next, add query, keys and values (in that order) of cross-attention to the state dict snake_case : Dict = in_proj_weight_cross_attn[:256, :] snake_case : Tuple = in_proj_bias_cross_attn[:256] snake_case : List[Any] = in_proj_weight_cross_attn[256:512, :] snake_case : Union[str, Any] = in_proj_bias_cross_attn[256:512] snake_case : Optional[int] = in_proj_weight_cross_attn[-256:, :] snake_case : List[Any] = in_proj_bias_cross_attn[-256:] def a_ ( ) -> Dict: """simple docstring""" snake_case : Optional[Any] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' snake_case : List[str] = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return im @torch.no_grad() def a_ ( __magic_name__ , __magic_name__=None , __magic_name__=False ) -> Optional[Any]: """simple docstring""" snake_case , snake_case : int = get_detr_config(snake_case__ ) # load original model from torch hub snake_case : List[str] = { '''detr-resnet-50''': '''detr_resnet50''', '''detr-resnet-101''': '''detr_resnet101''', } logger.info(F"Converting model {model_name}..." ) snake_case : Dict = torch.hub.load('''facebookresearch/detr''' , model_name_to_original_name[model_name] , pretrained=snake_case__ ).eval() snake_case : Optional[int] = detr.state_dict() # rename keys for src, dest in create_rename_keys(snake_case__ ): if is_panoptic: snake_case : int = '''detr.''' + src rename_key(snake_case__ , snake_case__ , snake_case__ ) # query, key and value matrices need special treatment read_in_q_k_v(snake_case__ , is_panoptic=snake_case__ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them snake_case : List[Any] = '''detr.model.''' if is_panoptic else '''model.''' for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith('''detr''' ) and not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ) ): snake_case : str = state_dict.pop(snake_case__ ) snake_case : Optional[Any] = val elif "class_labels_classifier" in key or "bbox_predictor" in key: snake_case : Union[str, Any] = state_dict.pop(snake_case__ ) snake_case : Any = val elif key.startswith('''bbox_attention''' ) or key.startswith('''mask_head''' ): continue else: snake_case : Dict = state_dict.pop(snake_case__ ) snake_case : Dict = val else: if not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ): snake_case : int = state_dict.pop(snake_case__ ) snake_case : Optional[int] = val # finally, create HuggingFace model and load state dict snake_case : Optional[Any] = DetrForSegmentation(snake_case__ ) if is_panoptic else DetrForObjectDetection(snake_case__ ) model.load_state_dict(snake_case__ ) model.eval() # verify our conversion on an image snake_case : List[Any] = '''coco_panoptic''' if is_panoptic else '''coco_detection''' snake_case : int = DetrImageProcessor(format=snake_case__ ) snake_case : int = processor(images=prepare_img() , return_tensors='''pt''' ) snake_case : Any = encoding['''pixel_values'''] snake_case : Tuple = detr(snake_case__ ) snake_case : int = model(snake_case__ ) assert torch.allclose(outputs.logits , original_outputs['''pred_logits'''] , atol=1e-3 ) assert torch.allclose(outputs.pred_boxes , original_outputs['''pred_boxes'''] , atol=1e-3 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs['''pred_masks'''] , atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F"Saving PyTorch model and image processor to {pytorch_dump_folder_path}..." ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) model.save_pretrained(snake_case__ ) processor.save_pretrained(snake_case__ ) if push_to_hub: # Upload model and image processor to the hub logger.info('''Uploading PyTorch model and image processor to the hub...''' ) model.push_to_hub(F"nielsr/{model_name}" ) processor.push_to_hub(F"nielsr/{model_name}" ) if __name__ == "__main__": _a : str = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') _a : int = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
700
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class a_ ( a ): def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = tempfile.mkdtemp() snake_case : Dict = 5 # Realm tok snake_case : str = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] snake_case : Tuple = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) snake_case : Any = os.path.join(UpperCAmelCase__ , 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 : Tuple = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def lowerCAmelCase( self : Any ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Any = RealmConfig(num_block_records=self.num_block_records ) return config def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[int] = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Dict = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=UpperCAmelCase__ , ) return block_records def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Tuple = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[str] = self.get_config() snake_case : Optional[Any] = self.get_dummy_retriever() snake_case : Optional[int] = retriever.tokenizer snake_case : Dict = np.array([0, 3] , dtype='''long''' ) snake_case : Optional[int] = tokenizer(['''Test question'''] ).input_ids snake_case : Union[str, Any] = tokenizer( ['''the fourth'''] , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ).input_ids snake_case : Optional[Any] = config.reader_seq_len snake_case , snake_case , snake_case , snake_case : List[str] = retriever( UpperCAmelCase__ , UpperCAmelCase__ , answer_ids=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors='''np''' ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = self.get_config() snake_case : Optional[int] = self.get_dummy_retriever() snake_case : List[str] = retriever.tokenizer snake_case : Optional[Any] = np.array([0, 3, 5] , dtype='''long''' ) snake_case : Optional[int] = tokenizer(['''Test question'''] ).input_ids snake_case : Any = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ).input_ids snake_case : List[Any] = config.reader_seq_len snake_case , snake_case , snake_case , snake_case : Union[str, Any] = retriever( UpperCAmelCase__ , UpperCAmelCase__ , answer_ids=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors='''np''' ) self.assertEqual([False, True, True] , UpperCAmelCase__ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , UpperCAmelCase__ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : int = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path snake_case : Optional[Any] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: snake_case : Any = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) snake_case : Any = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
84
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _a : Any = {'configuration_xlnet': ['XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Any = ['XLNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : str = ['XLNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Optional[int] = [ 'XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLNetForMultipleChoice', 'XLNetForQuestionAnswering', 'XLNetForQuestionAnsweringSimple', 'XLNetForSequenceClassification', 'XLNetForTokenClassification', 'XLNetLMHeadModel', 'XLNetModel', 'XLNetPreTrainedModel', 'load_tf_weights_in_xlnet', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Optional[int] = [ 'TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLNetForMultipleChoice', 'TFXLNetForQuestionAnsweringSimple', 'TFXLNetForSequenceClassification', 'TFXLNetForTokenClassification', 'TFXLNetLMHeadModel', 'TFXLNetMainLayer', 'TFXLNetModel', 'TFXLNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys _a : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
701
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _a : str = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = ['EncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Dict = ['TFEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = ['FlaxEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys _a : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
84
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _a : List[str] = {'configuration_timm_backbone': ['TimmBackboneConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Any = ['TimmBackbone'] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys _a : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
702
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer _a : str = logging.get_logger(__name__) _a : Optional[int] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Optional[Any] = { 'vocab_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json' ), }, } _a : Union[str, Any] = { 'yjernite/retribert-base-uncased': 512, } _a : Tuple = { 'yjernite/retribert-base-uncased': {'do_lower_case': True}, } class a_ ( a ): A__ : List[str] = VOCAB_FILES_NAMES A__ : Any = PRETRAINED_VOCAB_FILES_MAP A__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Any = PRETRAINED_INIT_CONFIGURATION A__ : Optional[Any] = RetriBertTokenizer A__ : Any = ['input_ids', 'attention_mask'] def __init__( self : Optional[int] , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Dict="[UNK]" , UpperCAmelCase__ : str="[SEP]" , UpperCAmelCase__ : Union[str, Any]="[PAD]" , UpperCAmelCase__ : Dict="[CLS]" , UpperCAmelCase__ : Optional[Any]="[MASK]" , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=None , **UpperCAmelCase__ : Dict , ): """simple docstring""" super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , do_lower_case=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , tokenize_chinese_chars=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ , **UpperCAmelCase__ , ) snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCAmelCase__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCAmelCase__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCAmelCase__ ) != tokenize_chinese_chars ): snake_case : int = getattr(UpperCAmelCase__ , normalizer_state.pop('''type''' ) ) snake_case : List[Any] = do_lower_case snake_case : Union[str, Any] = strip_accents snake_case : int = tokenize_chinese_chars snake_case : int = normalizer_class(**UpperCAmelCase__ ) snake_case : Union[str, Any] = do_lower_case def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=None ): """simple docstring""" snake_case : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ): """simple docstring""" snake_case : List[Any] = [self.sep_token_id] snake_case : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ): """simple docstring""" snake_case : Tuple = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ )
84
0
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() _a : List[Any] = logging.get_logger(__name__) def a_ ( __magic_name__ ) -> Union[str, Any]: """simple docstring""" snake_case : List[Any] = torch.load(snake_case_ , map_location='''cpu''' ) if "model" in sd.keys(): snake_case : List[Any] = torch.load(snake_case_ , map_location='''cpu''' )["model"] # pop unnecessary weights snake_case : List[str] = [ "decoder.version", "decoder.output_projection.weight", ] for key in keys_to_delete: if key in sd: sd.pop(snake_case_ ) snake_case : Union[str, Any] = { "decoder.project_in_dim.weight": "decoder.project_in.weight", "decoder.project_out_dim.weight": "decoder.project_out.weight", "decoder.layer_norm.weight": "decoder.final_layer_norm.weight", "decoder.layer_norm.bias": "decoder.final_layer_norm.bias", } for old_key, new_key in keys_to_rename.items(): if old_key in sd: snake_case : Optional[int] = sd.pop(snake_case_ ) snake_case : Any = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: snake_case : int = sd[key] # We split QKV in separate Q,K,V snake_case : List[Any] = key.replace('''.qkv_proj.''' , '''.q_proj.''' ) snake_case : Any = key.replace('''.qkv_proj.''' , '''.k_proj.''' ) snake_case : Optional[int] = key.replace('''.qkv_proj.''' , '''.v_proj.''' ) snake_case : int = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 snake_case : Dict = torch.split(snake_case_ , depth // 3 , dim=0 ) snake_case : Union[str, Any] = q snake_case : Optional[Any] = k snake_case : Union[str, Any] = v del sd[key] return sd @torch.no_grad() def a_ ( __magic_name__ , __magic_name__ , __magic_name__=None ) -> Optional[int]: """simple docstring""" snake_case : int = load_checkpoint(snake_case_ ) if config is not None: snake_case : Tuple = OPTConfig.from_pretrained(snake_case_ ) else: snake_case : Tuple = OPTConfig() snake_case : Union[str, Any] = OPTModel(snake_case_ ).half().eval() model.load_state_dict(snake_case_ ) # Check results Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) model.save_pretrained(snake_case_ ) if __name__ == "__main__": _a : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--fairseq_path', type=str, help=( 'path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:' ' https://huggingface.co/models?other=opt_metasq' ), ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--hf_config', default=None, type=str, help='Define HF config.') _a : Optional[int] = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
703
import string import numpy def a_ ( __magic_name__ , __magic_name__ ) -> int: """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , __magic_name__ ) class a_ : A__ : List[Any] = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) A__ : List[str] = numpy.vectorize(lambda a : x % 36 ) A__ : Dict = numpy.vectorize(a ) def __init__( self : List[str] , UpperCAmelCase__ : numpy.ndarray ): """simple docstring""" snake_case : int = self.modulus(UpperCAmelCase__ ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key snake_case : List[str] = encrypt_key.shape[0] def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : str ): """simple docstring""" return self.key_string.index(UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : int ): """simple docstring""" return self.key_string[round(UpperCAmelCase__ )] def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: snake_case : Tuple = det % len(self.key_string ) snake_case : Tuple = len(self.key_string ) if greatest_common_divisor(UpperCAmelCase__ , len(self.key_string ) ) != 1: snake_case : List[Any] = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[int] = [char for char in text.upper() if char in self.key_string] snake_case : Optional[int] = chars[-1] while len(UpperCAmelCase__ ) % self.break_key != 0: chars.append(UpperCAmelCase__ ) return "".join(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[int] = self.process_text(text.upper() ) snake_case : Optional[int] = '''''' for i in range(0 , len(UpperCAmelCase__ ) - self.break_key + 1 , self.break_key ): snake_case : int = text[i : i + self.break_key] snake_case : int = [self.replace_letters(UpperCAmelCase__ ) for char in batch] snake_case : Tuple = numpy.array([vec] ).T snake_case : Optional[Any] = self.modulus(self.encrypt_key.dot(UpperCAmelCase__ ) ).T.tolist()[ 0 ] snake_case : Dict = ''''''.join( self.replace_digits(UpperCAmelCase__ ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Optional[int] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: snake_case : int = det % len(self.key_string ) snake_case : Dict = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: snake_case : Any = i break snake_case : Any = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(UpperCAmelCase__ ) ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Any = self.make_decrypt_key() snake_case : Optional[Any] = self.process_text(text.upper() ) snake_case : int = '''''' for i in range(0 , len(UpperCAmelCase__ ) - self.break_key + 1 , self.break_key ): snake_case : Any = text[i : i + self.break_key] snake_case : int = [self.replace_letters(UpperCAmelCase__ ) for char in batch] snake_case : List[str] = numpy.array([vec] ).T snake_case : Optional[Any] = self.modulus(decrypt_key.dot(UpperCAmelCase__ ) ).T.tolist()[0] snake_case : int = ''''''.join( self.replace_digits(UpperCAmelCase__ ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def a_ ( ) -> None: """simple docstring""" snake_case : Any = int(input('''Enter the order of the encryption key: ''' ) ) snake_case : List[Any] = [] print('''Enter each row of the encryption key with space separated integers''' ) for _ in range(__magic_name__ ): snake_case : Optional[Any] = [int(__magic_name__ ) for x in input().split()] hill_matrix.append(__magic_name__ ) snake_case : List[str] = HillCipher(numpy.array(__magic_name__ ) ) print('''Would you like to encrypt or decrypt some text? (1 or 2)''' ) snake_case : int = input('''\n1. Encrypt\n2. Decrypt\n''' ) if option == "1": snake_case : List[Any] = input('''What text would you like to encrypt?: ''' ) print('''Your encrypted text is:''' ) print(hc.encrypt(__magic_name__ ) ) elif option == "2": snake_case : int = input('''What text would you like to decrypt?: ''' ) print('''Your decrypted text is:''' ) print(hc.decrypt(__magic_name__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
84
0
from __future__ import annotations def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: """simple docstring""" if len(_lowerCamelCase ) == 0: raise ValueError('''find_max() arg is an empty sequence''' ) if ( left >= len(_lowerCamelCase ) or left < -len(_lowerCamelCase ) or right >= len(_lowerCamelCase ) or right < -len(_lowerCamelCase ) ): raise IndexError('''list index out of range''' ) if left == right: return nums[left] snake_case : Optional[int] = (left + right) >> 1 # the middle snake_case : List[Any] = find_max(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # find max in range[left, mid] snake_case : Optional[int] = find_max(_lowerCamelCase , mid + 1 , _lowerCamelCase ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
704
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class a_ ( a ): A__ : List[Any] = 'Salesforce/blip-image-captioning-base' A__ : Dict = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) A__ : str = 'image_captioner' A__ : Dict = AutoModelForVisionaSeq A__ : Optional[Any] = ['image'] A__ : List[str] = ['text'] def __init__( self : List[str] , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : "Image" ): """simple docstring""" return self.pre_processor(images=UpperCAmelCase__ , return_tensors='''pt''' ) def lowerCAmelCase( self : Any , UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" return self.model.generate(**UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : List[Any] ): """simple docstring""" return self.pre_processor.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ )[0].strip()
84
0
'''simple docstring''' from __future__ import annotations def a_ ( __magic_name__ , __magic_name__ ) -> str: """simple docstring""" snake_case : List[Any] = set(__magic_name__ ), [start] while stack: snake_case : Optional[Any] = stack.pop() explored.add(__magic_name__ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(__magic_name__ ) return explored _a : Union[str, Any] = { 'A': ['B', 'C', 'D'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B', 'D'], 'E': ['B', 'F'], 'F': ['C', 'E', 'G'], 'G': ['F'], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, 'A'))
705
def a_ ( __magic_name__ ) -> bool: """simple docstring""" if p < 2: raise ValueError('''p should not be less than 2!''' ) elif p == 2: return True snake_case : int = 4 snake_case : Optional[Any] = (1 << p) - 1 for _ in range(p - 2 ): snake_case : Optional[Any] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
84
0
import json import os import unittest from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors @require_tokenizers class a_ ( __a , unittest.TestCase ): A__ : List[Any] = MvpTokenizer A__ : Optional[int] = MvpTokenizerFast A__ : Optional[Any] = True A__ : Optional[int] = filter_roberta_detectors def lowerCAmelCase( self : List[str] ): """simple docstring""" super().setUp() snake_case : str = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] snake_case : Optional[int] = dict(zip(a_ , range(len(a_ ) ) ) ) snake_case : Tuple = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] snake_case : Optional[int] = {"""unk_token""": """<unk>"""} snake_case : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(a_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(a_ ) ) def lowerCAmelCase( self : Union[str, Any] , **UpperCAmelCase__ : Dict ): """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **a_ ) def lowerCAmelCase( self : Optional[Any] , **UpperCAmelCase__ : List[str] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **a_ ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : int ): """simple docstring""" return "lower newer", "lower newer" @cached_property def lowerCAmelCase( self : List[str] ): """simple docstring""" return MvpTokenizer.from_pretrained('''RUCAIBox/mvp''' ) @cached_property def lowerCAmelCase( self : List[Any] ): """simple docstring""" return MvpTokenizerFast.from_pretrained('''RUCAIBox/mvp''' ) @require_torch def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Any = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] snake_case : List[str] = [0, 250, 251, 17_818, 13, 39_186, 1_938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: snake_case : List[Any] = tokenizer(a_ , max_length=len(a_ ) , padding=a_ , return_tensors='''pt''' ) self.assertIsInstance(a_ , a_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) snake_case : Union[str, Any] = batch.input_ids.tolist()[0] self.assertListEqual(a_ , a_ ) # Test that special tokens are reset @require_torch def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : str = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: snake_case : Dict = tokenizer(a_ , padding=a_ , return_tensors='''pt''' ) # check if input_ids are returned and no labels self.assertIn('''input_ids''' , a_ ) self.assertIn('''attention_mask''' , a_ ) self.assertNotIn('''labels''' , a_ ) self.assertNotIn('''decoder_attention_mask''' , a_ ) @require_torch def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : str = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: snake_case : int = tokenizer(text_target=a_ , max_length=32 , padding='''max_length''' , return_tensors='''pt''' ) self.assertEqual(32 , targets['''input_ids'''].shape[1] ) @require_torch def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: snake_case : Optional[Any] = tokenizer( ['''I am a small frog''' * 1_024, '''I am a small frog'''] , padding=a_ , truncation=a_ , return_tensors='''pt''' ) self.assertIsInstance(a_ , a_ ) self.assertEqual(batch.input_ids.shape , (2, 1_024) ) @require_torch def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Union[str, Any] = ["""A long paragraph for summarization."""] snake_case : Tuple = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: snake_case : Dict = tokenizer(a_ , text_target=a_ , return_tensors='''pt''' ) snake_case : List[str] = inputs["""input_ids"""] snake_case : List[str] = inputs["""labels"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" pass def lowerCAmelCase( self : List[str] ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case : Any = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) snake_case : Any = self.tokenizer_class.from_pretrained(a_ , **a_ ) snake_case : int = """A, <mask> AllenNLP sentence.""" snake_case : List[Any] = tokenizer_r.encode_plus(a_ , add_special_tokens=a_ , return_token_type_ids=a_ ) snake_case : List[str] = tokenizer_p.encode_plus(a_ , add_special_tokens=a_ , return_token_type_ids=a_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['''token_type_ids'''] ) , sum(tokens_p['''token_type_ids'''] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['''attention_mask'''] ) / len(tokens_r['''attention_mask'''] ) , sum(tokens_p['''attention_mask'''] ) / len(tokens_p['''attention_mask'''] ) , ) snake_case : List[Any] = tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids'''] ) snake_case : int = tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids'''] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['''input_ids'''] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] ) self.assertSequenceEqual(tokens_r['''input_ids'''] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] ) self.assertSequenceEqual( a_ , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) self.assertSequenceEqual( a_ , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] )
706
from sklearn.metrics import fa_score import datasets _a : List[str] = '\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n' _a : Dict = '\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {\'f1\': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results[\'f1\'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results[\'f1\'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")\n >>> print(round(results[\'f1\'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {\'f1\': array([0.8, 0. , 0. ])}\n' _a : List[Any] = '\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' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : Any ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'''] , ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : List[str]="binary" , UpperCAmelCase__ : str=None ): """simple docstring""" snake_case : List[Any] = fa_score( UpperCAmelCase__ , UpperCAmelCase__ , labels=UpperCAmelCase__ , pos_label=UpperCAmelCase__ , average=UpperCAmelCase__ , sample_weight=UpperCAmelCase__ ) return {"f1": float(UpperCAmelCase__ ) if score.size == 1 else score}
84
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _a : Tuple = logging.get_logger(__name__) _a : Dict = { 'andreasmadsen/efficient_mlm_m0.40': ( 'https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json' ), } class a_ ( a ): A__ : Tuple = 'roberta-prelayernorm' def __init__( self : str , UpperCAmelCase__ : Optional[Any]=50_265 , UpperCAmelCase__ : Union[str, Any]=768 , UpperCAmelCase__ : Optional[Any]=12 , UpperCAmelCase__ : Union[str, Any]=12 , UpperCAmelCase__ : Union[str, Any]=3_072 , UpperCAmelCase__ : List[str]="gelu" , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Any=512 , UpperCAmelCase__ : Tuple=2 , UpperCAmelCase__ : List[str]=0.02 , UpperCAmelCase__ : List[str]=1e-1_2 , UpperCAmelCase__ : Dict=1 , UpperCAmelCase__ : int=0 , UpperCAmelCase__ : Tuple=2 , UpperCAmelCase__ : Optional[int]="absolute" , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : Optional[int] , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase ) snake_case : Union[str, Any] = vocab_size snake_case : List[str] = hidden_size snake_case : str = num_hidden_layers snake_case : Tuple = num_attention_heads snake_case : Dict = hidden_act snake_case : Any = intermediate_size snake_case : Union[str, Any] = hidden_dropout_prob snake_case : Optional[Any] = attention_probs_dropout_prob snake_case : Union[str, Any] = max_position_embeddings snake_case : int = type_vocab_size snake_case : Optional[Any] = initializer_range snake_case : Any = layer_norm_eps snake_case : Any = position_embedding_type snake_case : List[Any] = use_cache snake_case : int = classifier_dropout class a_ ( a ): @property def lowerCAmelCase( self : Dict ): """simple docstring""" if self.task == "multiple-choice": snake_case : 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), ] )
707
def a_ ( __magic_name__ ) -> int: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ): raise TypeError('''only integers accepted as input''' ) else: snake_case : str = str(abs(__magic_name__ ) ) snake_case : Optional[Any] = [list(__magic_name__ ) for char in range(len(__magic_name__ ) )] for index in range(len(__magic_name__ ) ): num_transpositions[index].pop(__magic_name__ ) return max( int(''''''.join(list(__magic_name__ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
84
0
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class a_ : def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : int ): """simple docstring""" return None class a_ : def lowerCAmelCase( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] ): """simple docstring""" return None class a_ ( unittest.TestCase ): A__ : int = [ # (model_name, model_kwargs) ('bert-base-cased', {}), ('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def lowerCAmelCase( self : Optional[int] ): """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(lowercase_ , '''tf''' , 12 , **lowercase_ ) @require_torch @slow def lowerCAmelCase( self : Tuple ): """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(lowercase_ , '''pt''' , 12 , **lowercase_ ) @require_torch @slow def lowerCAmelCase( self : Optional[int] ): """simple docstring""" from transformers import BertModel snake_case : str = ["""[UNK]""", """[SEP]""", """[CLS]""", """[PAD]""", """[MASK]""", """some""", """other""", """words"""] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(lowercase_ ) ) vocab_file.flush() snake_case : str = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: snake_case : Any = BertModel(BertConfig(vocab_size=len(lowercase_ ) ) ) model.save_pretrained(lowercase_ ) self._test_export(lowercase_ , '''pt''' , 12 , lowercase_ ) @require_tf @slow def lowerCAmelCase( self : List[Any] ): """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case : Optional[int] = self._test_export(lowercase_ , '''tf''' , 12 , **lowercase_ ) snake_case : Dict = quantize(Path(lowercase_ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(lowercase_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def lowerCAmelCase( self : Any ): """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: snake_case : Union[str, Any] = self._test_export(lowercase_ , '''pt''' , 12 , **lowercase_ ) snake_case : List[Any] = quantize(lowercase_ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(lowercase_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : Tuple ): """simple docstring""" try: # Compute path with TemporaryDirectory() as tempdir: snake_case : List[str] = Path(lowercase_ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , **lowercase_ ) return path except Exception as e: self.fail(lowercase_ ) @require_torch @require_tokenizers @slow def lowerCAmelCase( self : int ): """simple docstring""" from transformers import BertModel snake_case : List[str] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case : Any = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(lowercase_ , lowercase_ , '''pt''' ) @require_tf @require_tokenizers @slow def lowerCAmelCase( self : Tuple ): """simple docstring""" from transformers import TFBertModel snake_case : Any = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) snake_case : str = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(lowercase_ , lowercase_ , '''tf''' ) def lowerCAmelCase( self : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Optional[int] = FeatureExtractionPipeline(lowercase_ , lowercase_ ) snake_case : List[Any] = ["""input_ids""", """token_type_ids""", """attention_mask""", """output_0""", """output_1"""] snake_case : Any = infer_shapes(lowercase_ , lowercase_ ) # Assert all variables are present self.assertEqual(len(lowercase_ ) , len(lowercase_ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , lowercase_ ) self.assertSequenceEqual(variable_names[3:] , lowercase_ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : int = ["""input_ids""", """attention_mask""", """token_type_ids"""] snake_case : List[Any] = {"""input_ids""": [1, 2, 3, 4], """attention_mask""": [0, 0, 0, 0], """token_type_ids""": [1, 1, 1, 1]} snake_case : Optional[Any] = ensure_valid_input(FuncContiguousArgs() , lowercase_ , lowercase_ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(lowercase_ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(lowercase_ ) , set(lowercase_ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(lowercase_ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) snake_case : List[Any] = ensure_valid_input(FuncNonContiguousArgs() , lowercase_ , lowercase_ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(lowercase_ ) , 1 ) self.assertEqual(len(lowercase_ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : Tuple = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
708
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class a_ : def __init__( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any]=99 , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Any=9 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : Tuple=32 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=37 , UpperCAmelCase__ : Union[str, Any]=8 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : str=0.002 , UpperCAmelCase__ : str=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : Union[str, Any]=0 , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=None , ): """simple docstring""" snake_case : Union[str, Any] = parent snake_case : Union[str, Any] = batch_size snake_case : Any = encoder_seq_length snake_case : str = decoder_seq_length # For common tests snake_case : Optional[int] = self.decoder_seq_length snake_case : Optional[Any] = is_training snake_case : List[Any] = use_attention_mask snake_case : Union[str, Any] = use_labels snake_case : Any = vocab_size snake_case : Optional[int] = hidden_size snake_case : List[str] = num_hidden_layers snake_case : Union[str, Any] = num_attention_heads snake_case : Any = d_ff snake_case : Any = relative_attention_num_buckets snake_case : Optional[Any] = dropout_rate snake_case : int = initializer_factor snake_case : Optional[Any] = eos_token_id snake_case : Dict = pad_token_id snake_case : Optional[Any] = decoder_start_token_id snake_case : Union[str, Any] = None snake_case : List[str] = decoder_layers def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return TaConfig.from_pretrained('''google/umt5-base''' ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=None , ): """simple docstring""" if attention_mask is None: snake_case : Union[str, Any] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: snake_case : Any = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: snake_case : List[Any] = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=UpperCAmelCase__ ) if decoder_head_mask is None: snake_case : Tuple = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=UpperCAmelCase__ ) if cross_attn_head_mask is None: snake_case : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=UpperCAmelCase__ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input snake_case : List[str] = input_ids.clamp(self.pad_token_id + 1 ) snake_case : List[str] = decoder_input_ids.clamp(self.pad_token_id + 1 ) snake_case : str = self.get_config() snake_case : Tuple = config.num_attention_heads snake_case : List[Any] = self.prepare_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, input_dict def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : List[str] = self.prepare_config_and_inputs() return config, inputs_dict def lowerCAmelCase( self : Dict ): """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def lowerCAmelCase( self : Tuple ): """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , ): """simple docstring""" snake_case : str = UMTaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : str = model( input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , ) snake_case : int = model(input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ ) snake_case : int = result.last_hidden_state snake_case : Dict = result.past_key_values snake_case : Dict = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(UpperCAmelCase__ ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , ): """simple docstring""" snake_case : int = UMTaModel(config=UpperCAmelCase__ ).get_decoder().to(UpperCAmelCase__ ).eval() # first forward pass snake_case : List[Any] = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) snake_case : List[Any] = model(UpperCAmelCase__ ) snake_case : Any = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) self.parent.assertTrue(len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) ) self.parent.assertTrue(len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) + 1 ) snake_case , snake_case : List[str] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids snake_case : Any = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and snake_case : Union[str, Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case : Any = model(UpperCAmelCase__ )['''last_hidden_state'''] snake_case : Optional[Any] = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )['''last_hidden_state'''] # select random slice snake_case : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() snake_case : Tuple = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , ): """simple docstring""" snake_case : int = UMTaModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).half().eval() snake_case : str = model(**UpperCAmelCase__ )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(UpperCAmelCase__ ).any().item() ) @require_torch class a_ ( a , a , a , unittest.TestCase ): A__ : str = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) A__ : str = (UMTaForConditionalGeneration,) if is_torch_available() else () A__ : Any = ( { 'conversational': UMTaForConditionalGeneration, 'feature-extraction': UMTaModel, 'summarization': UMTaForConditionalGeneration, 'text2text-generation': UMTaForConditionalGeneration, 'translation': UMTaForConditionalGeneration, 'question-answering': UMTaForQuestionAnswering, } if is_torch_available() else {} ) A__ : Dict = True A__ : List[str] = False A__ : Optional[int] = False A__ : Optional[int] = True A__ : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests A__ : int = [0.8, 0.9] def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Union[str, Any] = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Tuple = self.model_tester.prepare_config_and_inputs() snake_case : Optional[Any] = UMTaModel(config_and_inputs[0] ).to(UpperCAmelCase__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( UpperCAmelCase__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=UpperCAmelCase__ , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : Optional[int] = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() snake_case : int = config_and_inputs[0] snake_case : Union[str, Any] = UMTaForConditionalGeneration(UpperCAmelCase__ ).eval() model.to(UpperCAmelCase__ ) snake_case : str = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=UpperCAmelCase__ ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ), } for attn_name, (name, mask) in zip(UpperCAmelCase__ , head_masking.items() ): snake_case : int = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": snake_case : List[str] = torch.ones( config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ) snake_case : Union[str, Any] = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=UpperCAmelCase__ , return_dict_in_generate=UpperCAmelCase__ , **UpperCAmelCase__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step snake_case : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def lowerCAmelCase( self : Any ): """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class a_ ( unittest.TestCase ): @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[Any] = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=UpperCAmelCase__ ).to(UpperCAmelCase__ ) snake_case : int = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=UpperCAmelCase__ , legacy=UpperCAmelCase__ ) snake_case : List[str] = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] snake_case : Dict = tokenizer(UpperCAmelCase__ , return_tensors='''pt''' , padding=UpperCAmelCase__ ).input_ids # fmt: off snake_case : Optional[Any] = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : List[Any] = model.generate(input_ids.to(UpperCAmelCase__ ) ) snake_case : int = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] snake_case : Tuple = tokenizer.batch_decode(UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
84
0
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _a : List[Any] = logging.get_logger(__name__) _a : Optional[Any] = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', } _a : Any = { '''vocab_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'''}, '''merges_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'''}, } _a : Union[str, Any] = { '''ctrl''': 256, } _a : List[Any] = { '''Pregnancy''': 168_629, '''Christianity''': 7_675, '''Explain''': 106_423, '''Fitness''': 63_440, '''Saving''': 63_163, '''Ask''': 27_171, '''Ass''': 95_985, '''Joke''': 163_509, '''Questions''': 45_622, '''Thoughts''': 49_605, '''Retail''': 52_342, '''Feminism''': 164_338, '''Writing''': 11_992, '''Atheism''': 192_263, '''Netflix''': 48_616, '''Computing''': 39_639, '''Opinion''': 43_213, '''Alone''': 44_967, '''Funny''': 58_917, '''Gaming''': 40_358, '''Human''': 4_088, '''India''': 1_331, '''Joker''': 77_138, '''Diet''': 36_206, '''Legal''': 11_859, '''Norman''': 4_939, '''Tip''': 72_689, '''Weight''': 52_343, '''Movies''': 46_273, '''Running''': 23_425, '''Science''': 2_090, '''Horror''': 37_793, '''Confession''': 60_572, '''Finance''': 12_250, '''Politics''': 16_360, '''Scary''': 191_985, '''Support''': 12_654, '''Technologies''': 32_516, '''Teenage''': 66_160, '''Event''': 32_769, '''Learned''': 67_460, '''Notion''': 182_770, '''Wikipedia''': 37_583, '''Books''': 6_665, '''Extract''': 76_050, '''Confessions''': 102_701, '''Conspiracy''': 75_932, '''Links''': 63_674, '''Narcissus''': 150_425, '''Relationship''': 54_766, '''Relationships''': 134_796, '''Reviews''': 41_671, '''News''': 4_256, '''Translation''': 26_820, '''multilingual''': 128_406, } def a_ ( __magic_name__ ) -> Any: """simple docstring""" snake_case : Any = set() snake_case : Optional[int] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) snake_case : Optional[Any] = char snake_case : List[Any] = set(_lowercase ) return pairs class a_ ( a__ ): A__ : Union[str, Any] = VOCAB_FILES_NAMES A__ : Any = PRETRAINED_VOCAB_FILES_MAP A__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Union[str, Any] = CONTROL_CODES def __init__( self : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str]="<unk>" , **UpperCAmelCase__ : Any ): """simple docstring""" super().__init__(unk_token=lowerCAmelCase__ , **lowerCAmelCase__ ) with open(lowerCAmelCase__ , encoding='''utf-8''' ) as vocab_handle: snake_case : int = json.load(lowerCAmelCase__ ) snake_case : Dict = {v: k for k, v in self.encoder.items()} with open(lowerCAmelCase__ , encoding='''utf-8''' ) as merges_handle: snake_case : Any = merges_handle.read().split('''\n''' )[1:-1] snake_case : Optional[Any] = [tuple(merge.split() ) for merge in merges] snake_case : List[Any] = dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) snake_case : Optional[Any] = {} @property def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return len(self.encoder ) def lowerCAmelCase( self : Tuple ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def lowerCAmelCase( self : Any , UpperCAmelCase__ : Dict ): """simple docstring""" if token in self.cache: return self.cache[token] snake_case : int = tuple(lowerCAmelCase__ ) snake_case : Optional[int] = tuple(list(word[:-1] ) + [word[-1] + '''</w>'''] ) snake_case : Dict = get_pairs(lowerCAmelCase__ ) if not pairs: return token while True: snake_case : Union[str, Any] = min(lowerCAmelCase__ , key=lambda UpperCAmelCase__ : self.bpe_ranks.get(lowerCAmelCase__ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break snake_case : Dict = bigram snake_case : Union[str, Any] = [] snake_case : int = 0 while i < len(lowerCAmelCase__ ): try: snake_case : List[str] = word.index(lowerCAmelCase__ , lowerCAmelCase__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) snake_case : List[str] = j if word[i] == first and i < len(lowerCAmelCase__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 snake_case : int = tuple(lowerCAmelCase__ ) snake_case : Union[str, Any] = new_word if len(lowerCAmelCase__ ) == 1: break else: snake_case : Optional[Any] = get_pairs(lowerCAmelCase__ ) snake_case : str = "@@ ".join(lowerCAmelCase__ ) snake_case : List[Any] = word[:-4] snake_case : int = word return word def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : str = [] snake_case : List[Any] = re.findall(r'''\S+\n?''' , lowerCAmelCase__ ) for token in words: split_tokens.extend(list(self.bpe(lowerCAmelCase__ ).split(''' ''' ) ) ) return split_tokens def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" return self.encoder.get(lowerCAmelCase__ , self.encoder.get(self.unk_token ) ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : List[Any] ): """simple docstring""" return self.decoder.get(lowerCAmelCase__ , self.unk_token ) def lowerCAmelCase( self : str , UpperCAmelCase__ : Any ): """simple docstring""" snake_case : List[str] = " ".join(lowerCAmelCase__ ).replace('''@@ ''' , '''''' ).strip() return out_string def lowerCAmelCase( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : str = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return snake_case : Optional[int] = os.path.join( lowerCAmelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) snake_case : List[str] = os.path.join( lowerCAmelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=lowerCAmelCase__ , ensure_ascii=lowerCAmelCase__ ) + '''\n''' ) snake_case : Tuple = 0 with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda UpperCAmelCase__ : 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 : Dict = token_index writer.write(''' '''.join(lowerCAmelCase__ ) + '''\n''' ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
709
import torch from diffusers import DiffusionPipeline class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): """simple docstring""" super().__init__() self.register_modules(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) def __call__( self : Optional[int] ): """simple docstring""" snake_case : Any = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) snake_case : Dict = 1 snake_case : Optional[Any] = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample snake_case : List[Any] = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ).prev_sample snake_case : List[Any] = scheduler_output - scheduler_output + torch.ones_like(UpperCAmelCase__ ) return result
84
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _a : Tuple = logging.get_logger(__name__) _a : Any = { '''google/pix2struct-textcaps-base''': ( '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json''' ), } class a_ ( UpperCAmelCase__ ): A__ : Union[str, Any] = 'pix2struct_text_model' A__ : int = ['past_key_values'] A__ : Dict = { 'hidden_size': 'hidden_size', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Optional[int] , UpperCAmelCase__ : int=50_244 , UpperCAmelCase__ : str=768 , UpperCAmelCase__ : List[Any]=64 , UpperCAmelCase__ : Union[str, Any]=2_048 , UpperCAmelCase__ : Any=12 , UpperCAmelCase__ : Any=12 , UpperCAmelCase__ : Optional[int]=32 , UpperCAmelCase__ : str=128 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=1e-6 , UpperCAmelCase__ : str=1.0 , UpperCAmelCase__ : Optional[int]="gelu_new" , UpperCAmelCase__ : List[str]=0 , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : Optional[int]=0 , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : int=True , **UpperCAmelCase__ : List[str] , ): """simple docstring""" snake_case : Tuple = vocab_size snake_case : Union[str, Any] = hidden_size snake_case : List[str] = d_kv snake_case : Tuple = d_ff snake_case : str = num_layers snake_case : Dict = num_heads snake_case : Tuple = relative_attention_num_buckets snake_case : List[Any] = relative_attention_max_distance snake_case : Optional[int] = dropout_rate snake_case : Tuple = layer_norm_epsilon snake_case : Union[str, Any] = initializer_factor snake_case : int = use_cache snake_case : List[Any] = eos_token_id snake_case : List[Any] = decoder_start_token_id # for backwards compatibility snake_case : Tuple = dense_act_fn super().__init__( pad_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , decoder_start_token_id=__lowerCAmelCase , tie_word_embeddings=__lowerCAmelCase , is_decoder=__lowerCAmelCase , **__lowerCAmelCase , ) @classmethod def lowerCAmelCase( cls : Dict , UpperCAmelCase__ : Union[str, os.PathLike] , **UpperCAmelCase__ : Dict ): """simple docstring""" cls._set_token_in_kwargs(__lowerCAmelCase ) snake_case , snake_case : str = cls.get_config_dict(__lowerCAmelCase , **__lowerCAmelCase ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": snake_case : Union[str, Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"You are using a model of type {config_dict['model_type']} to instantiate a model of type " F"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(__lowerCAmelCase , **__lowerCAmelCase ) class a_ ( UpperCAmelCase__ ): A__ : Tuple = 'pix2struct_vision_model' def __init__( self : List[Any] , UpperCAmelCase__ : List[Any]=768 , UpperCAmelCase__ : str=768 , UpperCAmelCase__ : Optional[int]=2_048 , UpperCAmelCase__ : int=64 , UpperCAmelCase__ : Any=12 , UpperCAmelCase__ : str=12 , UpperCAmelCase__ : Optional[Any]="gelu_new" , UpperCAmelCase__ : Any=1e-6 , UpperCAmelCase__ : Optional[Any]=0.0 , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : int=1e-1_0 , UpperCAmelCase__ : int=1.0 , UpperCAmelCase__ : Optional[Any]=4_096 , UpperCAmelCase__ : str=32 , UpperCAmelCase__ : Any=128 , **UpperCAmelCase__ : Optional[Any] , ): """simple docstring""" super().__init__(**__lowerCAmelCase ) snake_case : int = hidden_size snake_case : int = patch_embed_hidden_size snake_case : str = d_ff snake_case : Optional[int] = dropout_rate snake_case : Dict = num_hidden_layers snake_case : Union[str, Any] = num_attention_heads snake_case : List[Any] = initializer_range snake_case : List[Any] = initializer_factor snake_case : Tuple = attention_dropout snake_case : str = layer_norm_eps snake_case : List[Any] = dense_act_fn snake_case : Optional[Any] = seq_len snake_case : List[str] = relative_attention_num_buckets snake_case : Any = relative_attention_max_distance snake_case : str = d_kv @classmethod def lowerCAmelCase( cls : List[str] , UpperCAmelCase__ : Union[str, os.PathLike] , **UpperCAmelCase__ : str ): """simple docstring""" cls._set_token_in_kwargs(__lowerCAmelCase ) snake_case , snake_case : List[Any] = cls.get_config_dict(__lowerCAmelCase , **__lowerCAmelCase ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": snake_case : Dict = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"You are using a model of type {config_dict['model_type']} to instantiate a model of type " F"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(__lowerCAmelCase , **__lowerCAmelCase ) class a_ ( UpperCAmelCase__ ): A__ : Optional[int] = 'pix2struct' A__ : Union[str, Any] = True def __init__( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Optional[Any]=1.0 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : Tuple=True , **UpperCAmelCase__ : Any , ): """simple docstring""" super().__init__(tie_word_embeddings=__lowerCAmelCase , is_encoder_decoder=__lowerCAmelCase , **__lowerCAmelCase ) if text_config is None: snake_case : List[Any] = {} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: snake_case : int = {} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) snake_case : List[Any] = PixaStructTextConfig(**__lowerCAmelCase ) snake_case : List[str] = PixaStructVisionConfig(**__lowerCAmelCase ) snake_case : List[str] = self.text_config.decoder_start_token_id snake_case : Optional[int] = self.text_config.pad_token_id snake_case : Union[str, Any] = self.text_config.eos_token_id snake_case : int = initializer_factor snake_case : str = initializer_range snake_case : Union[str, Any] = self.initializer_range snake_case : Any = self.initializer_range snake_case : Dict = is_vqa @classmethod def lowerCAmelCase( cls : Optional[Any] , UpperCAmelCase__ : PixaStructTextConfig , UpperCAmelCase__ : PixaStructVisionConfig , **UpperCAmelCase__ : List[Any] ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__lowerCAmelCase ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Optional[Any] = copy.deepcopy(self.__dict__ ) snake_case : List[Any] = self.text_config.to_dict() snake_case : Optional[int] = self.vision_config.to_dict() snake_case : str = self.__class__.model_type return output
710
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a_ ( a ): A__ : List[str] = ['image_processor', 'tokenizer'] A__ : Any = 'CLIPImageProcessor' A__ : Optional[int] = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : Union[str, Any] , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , UpperCAmelCase__ , ) snake_case : List[Any] = kwargs.pop('''feature_extractor''' ) snake_case : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(UpperCAmelCase__ , UpperCAmelCase__ ) def __call__( self : Any , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: snake_case : int = self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if images is not None: snake_case : Dict = self.image_processor(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if text is not None and images is not None: snake_case : Tuple = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase__ ) , tensor_type=UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : int ): """simple docstring""" return self.tokenizer.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : str ): """simple docstring""" return self.tokenizer.decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : int = self.tokenizer.model_input_names snake_case : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , UpperCAmelCase__ , ) return self.image_processor_class @property def lowerCAmelCase( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , UpperCAmelCase__ , ) return self.image_processor
84
0
'''simple docstring''' import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForPreTraining, is_apex_available, trainer_utils, ) from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'): _a : str = True from torch.cuda.amp import autocast _a : Union[str, Any] = logging.getLogger(__name__) @dataclass class a_ : A__ : str = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) A__ : Optional[str] = field( default=__UpperCAmelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) A__ : Optional[bool] = field( default=__UpperCAmelCase , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} ) A__ : Optional[bool] = field( default=__UpperCAmelCase , metadata={'help': 'Whether to log verbose messages or not.'} , ) A__ : Optional[float] = field( default=2.0 , metadata={'help': 'Maximum temperature for gumbel softmax.'} ) A__ : Optional[float] = field( default=0.5 , metadata={'help': 'Minimum temperature for gumbel softmax.'} ) A__ : Optional[float] = field( default=0.999995 , metadata={'help': 'Decay of gumbel temperature during training.'} ) def a_ ( __magic_name__ , __magic_name__ ) -> Optional[Any]: """simple docstring""" 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 : Union[str, Any] = logging.WARNING if model_args.verbose_logging: snake_case : Dict = logging.DEBUG elif trainer_utils.is_main_process(training_args.local_rank ): snake_case : Union[str, Any] = logging.INFO logger.setLevel(_snake_case ) @dataclass class a_ : A__ : str = field( default=__UpperCAmelCase , metadata={'help': 'The name of the dataset to use (via the datasets library).'} ) A__ : Optional[str] = field( default=__UpperCAmelCase , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) A__ : Optional[str] = field( default='train' , metadata={ 'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\'' } , ) A__ : Optional[str] = field( default='validation' , metadata={ 'help': ( 'The name of the validation data set split to use (via the datasets library). Defaults to \'validation\'' ) } , ) A__ : Optional[str] = field( default='file' , metadata={'help': 'Column in the dataset that contains speech file path. Defaults to \'file\''} , ) A__ : bool = field( default=__UpperCAmelCase , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} ) A__ : Optional[int] = field( default=1 , metadata={ 'help': 'The percentage of the train set used as validation set in case there\'s no validation split' } , ) A__ : Optional[int] = field( default=__UpperCAmelCase , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) A__ : Optional[float] = field( default=20.0 , metadata={'help': 'Filter audio files that are longer than `max_duration_in_seconds` seconds'} ) @dataclass class a_ : A__ : WavaVecaForPreTraining A__ : WavaVecaFeatureExtractor A__ : Union[bool, str] = "longest" A__ : Optional[int] = None A__ : Optional[int] = None def __call__( self : Optional[int] , UpperCAmelCase__ : List[str] ): """simple docstring""" # reformat list to dict and set to pytorch format snake_case : Tuple = self.feature_extractor.pad( UpperCAmelCase_ , max_length=self.max_length , padding=self.padding , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) snake_case : Dict = self.model._get_feat_extract_output_lengths(batch['''input_values'''].shape[-1] ) snake_case : List[Any] = batch['''input_values'''].shape[0] # make sure that no loss is computed on padded inputs if batch["attention_mask"] is not None: # compute real output lengths according to convolution formula snake_case : str = self.model._get_feat_extract_output_lengths(batch['''attention_mask'''].sum(-1 ) ).to( torch.long ) snake_case : Dict = torch.zeros( (batch_size, mask_indices_seq_length) , dtype=torch.long , device=batch['''input_values'''].device ) # these two operations makes sure that all values # before the output lengths indices are attended to snake_case : Dict = 1 snake_case : Optional[int] = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool() # sample randomly masked indices snake_case : Any = _compute_mask_indices( (batch_size, mask_indices_seq_length) , self.model.config.mask_time_prob , self.model.config.mask_time_length , attention_mask=UpperCAmelCase_ , min_masks=2 , ) return batch class a_ ( __UpperCAmelCase ): def __init__( self : Tuple , *UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int]=1 , UpperCAmelCase__ : Optional[int]=0 , UpperCAmelCase__ : Dict=1.0 , **UpperCAmelCase__ : List[str] ): """simple docstring""" super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case : Union[str, Any] = 0 snake_case : Tuple = max_gumbel_temp snake_case : Union[str, Any] = min_gumbel_temp snake_case : Dict = gumbel_temp_decay def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str ): """simple docstring""" model.train() snake_case : Optional[int] = self._prepare_inputs(UpperCAmelCase_ ) if self.use_amp: with autocast(): snake_case : List[str] = self.compute_loss(UpperCAmelCase_ , UpperCAmelCase_ ) else: snake_case : List[Any] = self.compute_loss(UpperCAmelCase_ , UpperCAmelCase_ ) if self.args.n_gpu > 1 or self.deepspeed: if model.module.config.ctc_loss_reduction == "mean": snake_case : Any = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": snake_case : int = loss.sum() / (inputs['''mask_time_indices''']).sum() else: raise ValueError(F"{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']" ) if self.args.gradient_accumulation_steps > 1: snake_case : int = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(UpperCAmelCase_ ).backward() elif self.use_apex: with amp.scale_loss(UpperCAmelCase_ , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(UpperCAmelCase_ ) else: loss.backward() self.num_update_step += 1 # make sure gumbel softmax temperature is decayed if self.args.n_gpu > 1 or self.deepspeed: model.module.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) else: model.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) return loss.detach() def a_ ( ) -> List[Any]: """simple docstring""" snake_case : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) snake_case , snake_case , snake_case : Union[str, Any] = parser.parse_args_into_dataclasses() configure_logger(_snake_case , _snake_case ) # Downloading and loading a dataset from the hub. snake_case : Dict = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) if "validation" not in datasets.keys(): # make sure only "validation" and "train" keys remain" snake_case : Dict = DatasetDict() snake_case : Tuple = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"{data_args.train_split_name}[:{data_args.validation_split_percentage}%]" , cache_dir=model_args.cache_dir , ) snake_case : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"{data_args.train_split_name}[{data_args.validation_split_percentage}%:]" , cache_dir=model_args.cache_dir , ) else: # make sure only "validation" and "train" keys remain" snake_case : Any = DatasetDict() snake_case : List[Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split='''validation''' , cache_dir=model_args.cache_dir , ) snake_case : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"{data_args.train_split_name}" , cache_dir=model_args.cache_dir , ) # only normalized-inputs-training is supported snake_case : int = WavaVecaFeatureExtractor.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=_snake_case ) def prepare_dataset(__magic_name__ ): # check that all files have the correct sampling rate snake_case , snake_case : int = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate ) return batch # load audio files into numpy arrays snake_case : int = datasets.map( _snake_case , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets['''train'''].column_names ) # filter audio files that are too long snake_case : Any = vectorized_datasets.filter( lambda __magic_name__ : len(data['''speech'''] ) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate ) ) def normalize(__magic_name__ ): return feature_extractor(batch['''speech'''] , sampling_rate=feature_extractor.sampling_rate ) # normalize and transform to `BatchFeatures` snake_case : int = vectorized_datasets.map( _snake_case , batched=_snake_case , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets['''train'''].column_names , ) # pretraining is only supported for "newer" stable layer norm architecture # apply_spec_augment has to be True, mask_feature_prob has to be 0.0 snake_case : List[str] = WavaVecaConfig.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , ) if not config.do_stable_layer_norm or config.feat_extract_norm != "layer": raise ValueError( '''PreTraining is only supported for ``config.do_stable_layer_norm=True`` and''' ''' ``config.feat_extract_norm=\'layer\'''' ) snake_case : List[Any] = WavaVecaForPreTraining(_snake_case ) snake_case : List[Any] = DataCollatorForWavaVecaPretraining(model=_snake_case , feature_extractor=_snake_case ) snake_case : Any = WavaVecaPreTrainer( model=_snake_case , data_collator=_snake_case , args=_snake_case , train_dataset=vectorized_datasets['''train'''] , eval_dataset=vectorized_datasets['''validation'''] , tokenizer=_snake_case , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , ) trainer.train() if __name__ == "__main__": main()
711
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _a : Optional[Any] = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' _a : str = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' _a : List[Any] = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : Any ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/krishnap25/mauve''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/krishnap25/mauve'''] , reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] , ) def lowerCAmelCase( self : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : List[str]="auto" , UpperCAmelCase__ : Tuple=-1 , UpperCAmelCase__ : Optional[int]=0.9 , UpperCAmelCase__ : List[Any]=5 , UpperCAmelCase__ : List[Any]=500 , UpperCAmelCase__ : Union[str, Any]="gpt2-large" , UpperCAmelCase__ : Optional[Any]=-1 , UpperCAmelCase__ : int=1_024 , UpperCAmelCase__ : List[Any]=25 , UpperCAmelCase__ : Union[str, Any]=5 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[Any]=25 , ): """simple docstring""" snake_case : List[str] = compute_mauve( p_text=UpperCAmelCase__ , q_text=UpperCAmelCase__ , p_features=UpperCAmelCase__ , q_features=UpperCAmelCase__ , p_tokens=UpperCAmelCase__ , q_tokens=UpperCAmelCase__ , num_buckets=UpperCAmelCase__ , pca_max_data=UpperCAmelCase__ , kmeans_explained_var=UpperCAmelCase__ , kmeans_num_redo=UpperCAmelCase__ , kmeans_max_iter=UpperCAmelCase__ , featurize_model_name=UpperCAmelCase__ , device_id=UpperCAmelCase__ , max_text_length=UpperCAmelCase__ , divergence_curve_discretization_size=UpperCAmelCase__ , mauve_scaling_factor=UpperCAmelCase__ , verbose=UpperCAmelCase__ , seed=UpperCAmelCase__ , ) return out
84
0
from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, 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 GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def a_ ( __magic_name__ , __magic_name__ , __magic_name__=None , __magic_name__=None ) -> Tuple: """simple docstring""" if attention_mask is None: snake_case : Tuple = tf.cast(tf.math.not_equal(_lowercase , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class a_ : A__ : Optional[Any] = OPTConfig A__ : Union[str, Any] = {} A__ : Union[str, Any] = 'gelu' def __init__( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=13 , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : Union[str, Any]=99 , UpperCAmelCase__ : Any=16 , UpperCAmelCase__ : List[str]=2 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=20 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : Optional[int]=1 , UpperCAmelCase__ : Optional[int]=0 , UpperCAmelCase__ : Any=16 , UpperCAmelCase__ : Any=16 , ): """simple docstring""" snake_case : Any = parent snake_case : List[Any] = batch_size snake_case : Optional[int] = seq_length snake_case : Tuple = is_training snake_case : Any = use_labels snake_case : Optional[Any] = vocab_size snake_case : Tuple = hidden_size snake_case : str = num_hidden_layers snake_case : int = num_attention_heads snake_case : Union[str, Any] = intermediate_size snake_case : Tuple = hidden_act snake_case : int = hidden_dropout_prob snake_case : Optional[int] = attention_probs_dropout_prob snake_case : Dict = max_position_embeddings snake_case : Union[str, Any] = eos_token_id snake_case : List[str] = pad_token_id snake_case : Optional[int] = bos_token_id snake_case : int = embed_dim snake_case : str = word_embed_proj_dim snake_case : str = False def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) snake_case : Optional[int] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) snake_case : List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) snake_case : Dict = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=UpperCamelCase__ , **self.config_updates , ) snake_case : Tuple = prepare_opt_inputs_dict(UpperCamelCase__ , UpperCamelCase__ ) return config, inputs_dict def lowerCAmelCase( self : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Optional[Any] = TFOPTModel(config=UpperCamelCase__ ) snake_case : Dict = inputs_dict['''input_ids'''] snake_case : Tuple = input_ids[:1, :] snake_case : int = inputs_dict['''attention_mask'''][:1, :] snake_case : Optional[int] = 1 # first forward pass snake_case : int = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , use_cache=UpperCamelCase__ ) snake_case : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids snake_case : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) snake_case : List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and snake_case : int = tf.concat([input_ids, next_tokens] , axis=-1 ) snake_case : Optional[int] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) snake_case : Tuple = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ )[0] snake_case : Any = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , past_key_values=UpperCamelCase__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice snake_case : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) snake_case : List[str] = output_from_no_past[:, -3:, random_slice_idx] snake_case : List[str] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(UpperCamelCase__ , UpperCamelCase__ , rtol=1e-3 ) @require_tf class a_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): A__ : Dict = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () A__ : Union[str, Any] = (TFOPTForCausalLM,) if is_tf_available() else () A__ : str = ( {'feature-extraction': TFOPTModel, 'text-generation': TFOPTForCausalLM} if is_tf_available() else {} ) A__ : str = False A__ : Tuple = False A__ : Tuple = False A__ : Optional[int] = 10 def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : Optional[int] = TFOPTModelTester(self ) snake_case : Dict = ConfigTester(self , config_class=UpperCamelCase__ ) def lowerCAmelCase( self : Dict ): """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase__ ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Tuple = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ): if hasattr(UpperCamelCase__ , '''weight''' ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(UpperCamelCase__ , '''weight''' ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 10, config.vocab_size + 10]: # build the embeddings snake_case : Tuple = model_class(config=UpperCamelCase__ ) snake_case : int = _get_word_embedding_weight(UpperCamelCase__ , model.get_input_embeddings() ) snake_case : List[Any] = _get_word_embedding_weight(UpperCamelCase__ , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(UpperCamelCase__ ) snake_case : List[str] = _get_word_embedding_weight(UpperCamelCase__ , model.get_input_embeddings() ) snake_case : str = _get_word_embedding_weight(UpperCamelCase__ , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. snake_case : str = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , UpperCamelCase__ ) # check that weights remain the same after resizing snake_case : Tuple = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: snake_case : Any = False self.assertTrue(UpperCamelCase__ ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , UpperCamelCase__ ) snake_case : Union[str, Any] = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: snake_case : Tuple = False self.assertTrue(UpperCamelCase__ ) def a_ ( __magic_name__ ) -> Union[str, Any]: """simple docstring""" return tf.constant(_lowercase , dtype=tf.intaa ) @require_tf class a_ ( unittest.TestCase ): A__ : int = 99 def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Tuple = tf.ones((4, 1) , dtype=tf.intaa ) * 2 snake_case : Union[str, Any] = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) snake_case : Dict = input_ids.shape[0] snake_case : Union[str, Any] = OPTConfig( vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class a_ ( unittest.TestCase ): @slow def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : List[Any] = TFOPTModel.from_pretrained('''facebook/opt-350m''' ) snake_case : Optional[int] = _long_tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) snake_case : Union[str, Any] = tf.not_equal(UpperCamelCase__ , model.config.pad_token_id ) with tf.GradientTape(): snake_case : str = model(input_ids=UpperCamelCase__ , attention_mask=UpperCamelCase__ ).last_hidden_state snake_case : Tuple = (1, 11, 512) self.assertEqual(output.shape , UpperCamelCase__ ) snake_case : str = tf.constant( [[-0.2873, -1.9218, -0.3033], [-1.2710, -0.1338, -0.1902], [0.4095, 0.1214, -1.3121]] ) self.assertTrue(np.allclose(output[:, :3, :3] , UpperCamelCase__ , atol=4e-3 ) ) snake_case : Dict = tf.function(UpperCamelCase__ , jit_compile=UpperCamelCase__ ) snake_case : int = xla_generate(UpperCamelCase__ , UpperCamelCase__ )[0] self.assertTrue(np.allclose(output[:, :3, :3] , UpperCamelCase__ , atol=4e-2 ) ) @require_tf @slow class a_ ( unittest.TestCase ): def lowerCAmelCase( self : List[Any] ): """simple docstring""" super().setUp() snake_case : Dict = '''facebook/opt-350m''' def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Dict = TFOPTForCausalLM.from_pretrained(self.path_model ) snake_case : Optional[int] = GPTaTokenizer.from_pretrained(self.path_model ) snake_case : Optional[int] = [ '''Today is a beautiful day and I want to''', '''In the city of''', '''Paris is the capital of France and''', '''Computers and mobile phones have taken''', ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False snake_case : int = tokenizer(UpperCamelCase__ , return_tensors='''tf''' , padding=UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) snake_case : List[str] = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) snake_case : str = tf.constant( [ [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670], [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822], [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703], [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477], ] ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-4 ) ) snake_case : Dict = tf.function(UpperCamelCase__ , jit_compile=UpperCamelCase__ ) snake_case : Dict = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-4 ) ) @require_tf @slow class a_ ( unittest.TestCase ): @property def lowerCAmelCase( self : Any ): """simple docstring""" return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : str = '''facebook/opt-125m''' snake_case : Optional[Any] = [ '''Today is a beautiful day and I want to''', '''In the city of New York, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] snake_case : Optional[int] = [] snake_case : Dict = GPTaTokenizer.from_pretrained(UpperCamelCase__ ) snake_case : Dict = TFOPTForCausalLM.from_pretrained(UpperCamelCase__ ) for prompt in self.prompts: snake_case : List[Any] = tokenizer(UpperCamelCase__ , return_tensors='''tf''' ).input_ids snake_case : Dict = model.generate(UpperCamelCase__ , max_length=10 ) snake_case : int = tokenizer.batch_decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) predicted_outputs += generated_string self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : Dict = '''facebook/opt-350m''' snake_case : Union[str, Any] = GPTaTokenizer.from_pretrained(UpperCamelCase__ ) snake_case : List[Any] = TFOPTForCausalLM.from_pretrained(UpperCamelCase__ ) snake_case : str = '''left''' # use different length sentences to test batching snake_case : Dict = [ '''Hello, my dog is a little''', '''Today, I''', ] snake_case : Dict = tokenizer(UpperCamelCase__ , return_tensors='''tf''' , padding=UpperCamelCase__ ) snake_case : List[Any] = inputs['''input_ids'''] snake_case : Union[str, Any] = model.generate(input_ids=UpperCamelCase__ , attention_mask=inputs['''attention_mask'''] ) snake_case : str = tokenizer(sentences[0] , return_tensors='''tf''' ).input_ids snake_case : Union[str, Any] = model.generate(input_ids=UpperCamelCase__ ) snake_case : List[str] = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs['''attention_mask'''][-1] , tf.intaa ) ) snake_case : int = tokenizer(sentences[1] , return_tensors='''tf''' ).input_ids snake_case : Union[str, Any] = model.generate(input_ids=UpperCamelCase__ , max_length=model.config.max_length - num_paddings ) snake_case : Any = tokenizer.batch_decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) snake_case : str = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCamelCase__ ) snake_case : List[str] = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCamelCase__ ) snake_case : List[str] = [ '''Hello, my dog is a little bit of a dork.\nI\'m a little bit''', '''Today, I was in the middle of a conversation with a friend about the''', ] self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , [non_padded_sentence, padded_sentence] ) def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : Optional[int] = '''facebook/opt-350m''' snake_case : int = [ '''Today is a beautiful day and I want to''', '''In the city of San Francisco, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] snake_case : Optional[int] = [] snake_case : Union[str, Any] = GPTaTokenizer.from_pretrained(UpperCamelCase__ ) snake_case : Union[str, Any] = TFOPTForCausalLM.from_pretrained(UpperCamelCase__ ) for prompt in self.prompts: snake_case : Tuple = tokenizer(UpperCamelCase__ , return_tensors='''tf''' ).input_ids snake_case : Dict = model.generate(UpperCamelCase__ , max_length=10 ) snake_case : Tuple = tokenizer.batch_decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) predicted_outputs += generated_string self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
712
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" if "cls_token" in name: snake_case : Tuple = name.replace('''cls_token''' , '''vit.embeddings.cls_token''' ) if "mask_token" in name: snake_case : Optional[int] = name.replace('''mask_token''' , '''decoder.mask_token''' ) if "decoder_pos_embed" in name: snake_case : List[str] = name.replace('''decoder_pos_embed''' , '''decoder.decoder_pos_embed''' ) if "pos_embed" in name and "decoder" not in name: snake_case : List[str] = name.replace('''pos_embed''' , '''vit.embeddings.position_embeddings''' ) if "patch_embed.proj" in name: snake_case : List[Any] = name.replace('''patch_embed.proj''' , '''vit.embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: snake_case : int = name.replace('''patch_embed.norm''' , '''vit.embeddings.norm''' ) if "decoder_blocks" in name: snake_case : int = name.replace('''decoder_blocks''' , '''decoder.decoder_layers''' ) if "blocks" in name: snake_case : Optional[Any] = name.replace('''blocks''' , '''vit.encoder.layer''' ) if "attn.proj" in name: snake_case : str = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: snake_case : Any = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: snake_case : List[str] = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: snake_case : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: snake_case : Tuple = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: snake_case : Tuple = name.replace('''mlp.fc2''' , '''output.dense''' ) if "decoder_embed" in name: snake_case : Dict = name.replace('''decoder_embed''' , '''decoder.decoder_embed''' ) if "decoder_norm" in name: snake_case : Dict = name.replace('''decoder_norm''' , '''decoder.decoder_norm''' ) if "decoder_pred" in name: snake_case : Dict = name.replace('''decoder_pred''' , '''decoder.decoder_pred''' ) if "norm.weight" in name and "decoder" not in name: snake_case : Optional[int] = name.replace('''norm.weight''' , '''vit.layernorm.weight''' ) if "norm.bias" in name and "decoder" not in name: snake_case : List[str] = name.replace('''norm.bias''' , '''vit.layernorm.bias''' ) return name def a_ ( __magic_name__ , __magic_name__ ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): snake_case : Union[str, Any] = orig_state_dict.pop(__magic_name__ ) if "qkv" in key: snake_case : Optional[int] = key.split('''.''' ) snake_case : int = int(key_split[1] ) if "decoder_blocks" in key: snake_case : List[str] = config.decoder_hidden_size snake_case : List[Any] = '''decoder.decoder_layers.''' if "weight" in key: snake_case : str = val[:dim, :] snake_case : Optional[Any] = val[dim : dim * 2, :] snake_case : Any = val[-dim:, :] elif "bias" in key: snake_case : Optional[Any] = val[:dim] snake_case : List[Any] = val[dim : dim * 2] snake_case : List[Any] = val[-dim:] else: snake_case : Optional[int] = config.hidden_size snake_case : Tuple = '''vit.encoder.layer.''' if "weight" in key: snake_case : Optional[Any] = val[:dim, :] snake_case : str = val[dim : dim * 2, :] snake_case : Union[str, Any] = val[-dim:, :] elif "bias" in key: snake_case : Tuple = val[:dim] snake_case : int = val[dim : dim * 2] snake_case : Optional[Any] = val[-dim:] else: snake_case : Optional[Any] = val return orig_state_dict def a_ ( __magic_name__ , __magic_name__ ) -> Any: """simple docstring""" snake_case : List[str] = ViTMAEConfig() if "large" in checkpoint_url: snake_case : str = 1_024 snake_case : Tuple = 4_096 snake_case : Optional[Any] = 24 snake_case : List[Any] = 16 elif "huge" in checkpoint_url: snake_case : Tuple = 14 snake_case : int = 1_280 snake_case : Dict = 5_120 snake_case : Tuple = 32 snake_case : Optional[Any] = 16 snake_case : Optional[Any] = ViTMAEForPreTraining(__magic_name__ ) snake_case : Optional[Any] = torch.hub.load_state_dict_from_url(__magic_name__ , map_location='''cpu''' )['''model'''] snake_case : int = ViTMAEImageProcessor(size=config.image_size ) snake_case : Dict = convert_state_dict(__magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ ) model.eval() snake_case : Tuple = '''https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg''' snake_case : List[Any] = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) snake_case : Dict = ViTMAEImageProcessor(size=config.image_size ) snake_case : str = image_processor(images=__magic_name__ , return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) snake_case : Union[str, Any] = model(**__magic_name__ ) snake_case : Optional[Any] = outputs.logits if "large" in checkpoint_url: snake_case : Any = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] ) elif "huge" in checkpoint_url: snake_case : List[Any] = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] ) else: snake_case : Dict = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , __magic_name__ , atol=1e-4 ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__magic_name__ ) if __name__ == "__main__": _a : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) _a : str = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
84
0
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class a_ ( a , a , unittest.TestCase ): A__ : Tuple = IFPipeline A__ : List[Any] = TEXT_TO_IMAGE_PARAMS - {'width', 'height', 'latents'} A__ : str = TEXT_TO_IMAGE_BATCH_PARAMS A__ : Optional[Any] = PipelineTesterMixin.required_optional_params - {'latents'} def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" return self._get_dummy_components() def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict=0 ): """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith('''mps''' ): snake_case : List[str] = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: snake_case : List[str] = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) snake_case : Dict = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowerCAmelCase( self : Any ): """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowerCAmelCase( self : Any ): """simple docstring""" self._test_save_load_local() def lowerCAmelCase( self : List[Any] ): """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def lowerCAmelCase( self : List[str] ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): def lowerCAmelCase( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Dict = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa ) snake_case : Tuple = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''' ) snake_case , snake_case : Union[str, Any] = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() snake_case : List[str] = None snake_case : int = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img snake_case : List[Any] = IFImgaImgPipeline(**pipe_a.components ) snake_case : str = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting snake_case : Any = IFInpaintingPipeline(**pipe_a.components ) snake_case : str = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase( self : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" _start_torch_memory_measurement() snake_case : Dict = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case : Any = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=_SCREAMING_SNAKE_CASE , output_type='''np''' , ) snake_case : int = output.images[0] assert image.shape == (64, 64, 3) snake_case : Dict = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 snake_case : Union[str, Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() snake_case : Optional[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case : Optional[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) snake_case : Union[str, Any] = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , ) snake_case : Optional[Any] = output.images[0] assert image.shape == (256, 256, 3) snake_case : Any = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 snake_case : int = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase( self : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int ): """simple docstring""" _start_torch_memory_measurement() snake_case : Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) snake_case : Any = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case : List[str] = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=_SCREAMING_SNAKE_CASE , output_type='''np''' , ) snake_case : Optional[int] = output.images[0] assert image.shape == (64, 64, 3) snake_case : Tuple = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 snake_case : Union[str, Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() snake_case : Dict = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case : str = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) snake_case : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) snake_case : Tuple = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , original_image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , ) snake_case : Union[str, Any] = output.images[0] assert image.shape == (256, 256, 3) snake_case : Optional[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 snake_case : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict ): """simple docstring""" _start_torch_memory_measurement() snake_case : str = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) snake_case : Optional[int] = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(_SCREAMING_SNAKE_CASE ) snake_case : int = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case : Any = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=_SCREAMING_SNAKE_CASE , output_type='''np''' , ) snake_case : Union[str, Any] = output.images[0] assert image.shape == (64, 64, 3) snake_case : Optional[Any] = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 snake_case : Union[str, Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() snake_case : Union[str, Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) snake_case : Union[str, Any] = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) snake_case : Optional[int] = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(_SCREAMING_SNAKE_CASE ) snake_case : Dict = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , original_image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , ) snake_case : Dict = output.images[0] assert image.shape == (256, 256, 3) snake_case : int = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 snake_case : Any = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def a_ ( ) -> Tuple: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
713
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _a : Optional[Any] = 16 _a : Union[str, Any] = 32 def a_ ( __magic_name__ , __magic_name__ = 16 ) -> Dict: """simple docstring""" snake_case : Tuple = AutoTokenizer.from_pretrained('''bert-base-cased''' ) snake_case : Any = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__magic_name__ ): # max_length=None => use the model max length (it's actually the default) snake_case : Union[str, Any] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__magic_name__ , max_length=__magic_name__ ) 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( __magic_name__ , batched=__magic_name__ , 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(__magic_name__ ): # On TPU it's best to pad everything to the same length or training will be very slow. snake_case : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": snake_case : Tuple = 16 elif accelerator.mixed_precision != "no": snake_case : Dict = 8 else: snake_case : Union[str, Any] = None return tokenizer.pad( __magic_name__ , padding='''longest''' , max_length=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_tensors='''pt''' , ) # Instantiate dataloaders. snake_case : str = DataLoader( tokenized_datasets['''train'''] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) snake_case : List[str] = DataLoader( tokenized_datasets['''validation'''] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders _a : Optional[int] = mocked_dataloaders # noqa: F811 def a_ ( __magic_name__ , __magic_name__ ) -> Optional[Any]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , __magic_name__ ) == "1": snake_case : Optional[int] = 2 # Initialize accelerator snake_case : 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 : Dict = config['''lr'''] snake_case : Any = int(config['''num_epochs'''] ) snake_case : List[str] = int(config['''seed'''] ) snake_case : List[Any] = int(config['''batch_size'''] ) snake_case : Tuple = evaluate.load('''glue''' , '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=__magic_name__ ) def inner_training_loop(__magic_name__ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(__magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) snake_case : str = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=__magic_name__ ) # 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 : Optional[int] = model.to(accelerator.device ) # Instantiate optimizer snake_case : Optional[int] = AdamW(params=model.parameters() , lr=__magic_name__ ) snake_case , snake_case : List[Any] = get_dataloaders(__magic_name__ , __magic_name__ ) # Instantiate scheduler snake_case : int = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=100 , num_training_steps=(len(__magic_name__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. snake_case , snake_case , snake_case , snake_case , snake_case : Tuple = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # Now we train the model for epoch in range(__magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) snake_case : int = model(**__magic_name__ ) snake_case : Optional[int] = outputs.loss accelerator.backward(__magic_name__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): snake_case : List[str] = model(**__magic_name__ ) snake_case : List[Any] = outputs.logits.argmax(dim=-1 ) snake_case , snake_case : Dict = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) snake_case : Tuple = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , __magic_name__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def a_ ( ) -> Union[str, Any]: """simple docstring""" snake_case : int = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=__magic_name__ , default=__magic_name__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) snake_case : Optional[Any] = parser.parse_args() snake_case : Optional[int] = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
84
0
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class a_ ( unittest.TestCase ): def __init__( self : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : List[str]=18 , UpperCAmelCase__ : Dict=30 , UpperCAmelCase__ : int=400 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Optional[Any]=True , ): """simple docstring""" snake_case : Optional[Any] = size if size is not None else {"""height""": 18, """width""": 18} snake_case : Optional[int] = parent snake_case : List[Any] = batch_size snake_case : Union[str, Any] = num_channels snake_case : Tuple = image_size snake_case : Optional[int] = min_resolution snake_case : int = max_resolution snake_case : Optional[Any] = do_resize snake_case : str = size snake_case : Any = apply_ocr def lowerCAmelCase( self : List[Any] ): """simple docstring""" return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class a_ ( UpperCAmelCase__ , unittest.TestCase ): A__ : str = LayoutLMvaImageProcessor if is_pytesseract_available() else None def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Tuple = LayoutLMvaImageProcessingTester(self ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''apply_ocr''' ) ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) snake_case : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" pass def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image ) # Test not batched input snake_case : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , UpperCAmelCase__ ) self.assertIsInstance(encoding.boxes , UpperCAmelCase__ ) # Test batched snake_case : int = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray ) # Test not batched input snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched snake_case : List[str] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , torch.Tensor ) # Test not batched input snake_case : List[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 : Any = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : int ): """simple docstring""" snake_case : str = LayoutLMvaImageProcessor() from datasets import load_dataset snake_case : Any = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) snake_case : Union[str, Any] = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) snake_case : Union[str, Any] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 snake_case : List[str] = [["""11:14""", """to""", """11:39""", """a.m""", """11:39""", """to""", """11:44""", """a.m.""", """11:44""", """a.m.""", """to""", """12:25""", """p.m.""", """12:25""", """to""", """12:58""", """p.m.""", """12:58""", """to""", """4:00""", """p.m.""", """2:00""", """to""", """5:00""", """p.m.""", """Coffee""", """Break""", """Coffee""", """will""", """be""", """served""", """for""", """men""", """and""", """women""", """in""", """the""", """lobby""", """adjacent""", """to""", """exhibit""", """area.""", """Please""", """move""", """into""", """exhibit""", """area.""", """(Exhibits""", """Open)""", """TRRF""", """GENERAL""", """SESSION""", """(PART""", """|)""", """Presiding:""", """Lee""", """A.""", """Waller""", """TRRF""", """Vice""", """President""", """“Introductory""", """Remarks”""", """Lee""", """A.""", """Waller,""", """TRRF""", """Vice""", """Presi-""", """dent""", """Individual""", """Interviews""", """with""", """TRRF""", """Public""", """Board""", """Members""", """and""", """Sci-""", """entific""", """Advisory""", """Council""", """Mem-""", """bers""", """Conducted""", """by""", """TRRF""", """Treasurer""", """Philip""", """G.""", """Kuehn""", """to""", """get""", """answers""", """which""", """the""", """public""", """refrigerated""", """warehousing""", """industry""", """is""", """looking""", """for.""", """Plus""", """questions""", """from""", """the""", """floor.""", """Dr.""", """Emil""", """M.""", """Mrak,""", """University""", """of""", """Cal-""", """ifornia,""", """Chairman,""", """TRRF""", """Board;""", """Sam""", """R.""", """Cecil,""", """University""", """of""", """Georgia""", """College""", """of""", """Agriculture;""", """Dr.""", """Stanley""", """Charm,""", """Tufts""", """University""", """School""", """of""", """Medicine;""", """Dr.""", """Robert""", """H.""", """Cotton,""", """ITT""", """Continental""", """Baking""", """Company;""", """Dr.""", """Owen""", """Fennema,""", """University""", """of""", """Wis-""", """consin;""", """Dr.""", """Robert""", """E.""", """Hardenburg,""", """USDA.""", """Questions""", """and""", """Answers""", """Exhibits""", """Open""", """Capt.""", """Jack""", """Stoney""", """Room""", """TRRF""", """Scientific""", """Advisory""", """Council""", """Meeting""", """Ballroom""", """Foyer"""]] # noqa: E231 snake_case : Dict = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , UpperCAmelCase__ ) self.assertListEqual(encoding.boxes , UpperCAmelCase__ ) # with apply_OCR = False snake_case : Tuple = LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase__ ) snake_case : Tuple = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
714
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract _a : Dict = logging.get_logger(__name__) def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> List[Any]: """simple docstring""" return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def a_ ( __magic_name__ , __magic_name__ , __magic_name__ = None ) -> str: """simple docstring""" snake_case : Any = tesseract_config if tesseract_config is not None else '''''' # apply OCR snake_case : str = to_pil_image(__magic_name__ ) snake_case , snake_case : Union[str, Any] = pil_image.size snake_case : List[Any] = pytesseract.image_to_data(__magic_name__ , lang=__magic_name__ , output_type='''dict''' , config=__magic_name__ ) snake_case , snake_case , snake_case , snake_case , snake_case : Optional[Any] = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates snake_case : Union[str, Any] = [idx for idx, word in enumerate(__magic_name__ ) if not word.strip()] snake_case : Union[str, Any] = [word for idx, word in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : Optional[Any] = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format snake_case : List[Any] = [] for x, y, w, h in zip(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): snake_case : Optional[int] = [x, y, x + w, y + h] actual_boxes.append(__magic_name__ ) # finally, normalize the bounding boxes snake_case : List[Any] = [] for box in actual_boxes: normalized_boxes.append(normalize_box(__magic_name__ , __magic_name__ , __magic_name__ ) ) assert len(__magic_name__ ) == len(__magic_name__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class a_ ( a ): A__ : int = ['pixel_values'] def __init__( self : Optional[int] , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = "" , **UpperCAmelCase__ : int , ): """simple docstring""" super().__init__(**UpperCAmelCase__ ) snake_case : Any = size if size is not None else {'''height''': 224, '''width''': 224} snake_case : Tuple = get_size_dict(UpperCAmelCase__ ) snake_case : Dict = do_resize snake_case : str = size snake_case : Optional[int] = resample snake_case : Union[str, Any] = apply_ocr snake_case : int = ocr_lang snake_case : Union[str, Any] = tesseract_config def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Any , ): """simple docstring""" snake_case : Dict = get_size_dict(UpperCAmelCase__ ) 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(UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : List[Any] , ): """simple docstring""" snake_case : Tuple = do_resize if do_resize is not None else self.do_resize snake_case : List[Any] = size if size is not None else self.size snake_case : Tuple = get_size_dict(UpperCAmelCase__ ) snake_case : str = resample if resample is not None else self.resample snake_case : Optional[int] = apply_ocr if apply_ocr is not None else self.apply_ocr snake_case : Any = ocr_lang if ocr_lang is not None else self.ocr_lang snake_case : Optional[int] = tesseract_config if tesseract_config is not None else self.tesseract_config snake_case : List[str] = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) # All transformations expect numpy arrays. snake_case : Any = [to_numpy_array(UpperCAmelCase__ ) for image in images] if apply_ocr: requires_backends(self , '''pytesseract''' ) snake_case : Optional[int] = [] snake_case : Union[str, Any] = [] for image in images: snake_case , snake_case : List[Any] = apply_tesseract(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) words_batch.append(UpperCAmelCase__ ) boxes_batch.append(UpperCAmelCase__ ) if do_resize: snake_case : Any = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) snake_case : int = [flip_channel_order(UpperCAmelCase__ ) for image in images] snake_case : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] snake_case : List[Any] = BatchFeature(data={'''pixel_values''': images} , tensor_type=UpperCAmelCase__ ) if apply_ocr: snake_case : Dict = words_batch snake_case : Dict = boxes_batch return data
84
0
'''simple docstring''' import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _a : Tuple = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class a_ ( unittest.TestCase ): def __init__( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : Tuple=18 , UpperCAmelCase__ : List[Any]=30 , UpperCAmelCase__ : Tuple=400 , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Union[str, Any]=None , ): """simple docstring""" snake_case : int = size if size is not None else {'''height''': 20, '''width''': 20} snake_case : Union[str, Any] = parent snake_case : str = batch_size snake_case : Dict = num_channels snake_case : Union[str, Any] = image_size snake_case : Any = min_resolution snake_case : List[str] = max_resolution snake_case : List[Any] = size snake_case : Any = do_normalize snake_case : Tuple = do_convert_rgb snake_case : Optional[int] = [512, 1_024, 2_048, 4_096] snake_case : List[Any] = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def lowerCAmelCase( self : List[str] ): """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : int = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' snake_case : Dict = Image.open(requests.get(__lowercase , stream=__lowercase ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class a_ ( lowercase__ , unittest.TestCase ): A__ : Any = PixaStructImageProcessor if is_vision_available() else None def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : Optional[Any] = PixaStructImageProcessingTester(self ) @property def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowercase , '''do_normalize''' ) ) self.assertTrue(hasattr(__lowercase , '''do_convert_rgb''' ) ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Dict = self.image_processor_tester.prepare_dummy_image() snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) snake_case : Tuple = 2_048 snake_case : str = image_processor(__lowercase , return_tensors='''pt''' , max_patches=__lowercase ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" # Initialize image_processor snake_case : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , Image.Image ) # Test not batched input snake_case : Any = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case : int = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case : str = image_processor( __lowercase , return_tensors='''pt''' , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def lowerCAmelCase( self : int ): """simple docstring""" # Initialize image_processor snake_case : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , Image.Image ) # Test not batched input snake_case : Optional[Any] = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 snake_case : Tuple = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(__lowercase ): snake_case : Tuple = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__lowercase ).flattened_patches snake_case : List[str] = '''Hello''' snake_case : List[Any] = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__lowercase , header_text=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case : Optional[Any] = image_processor( __lowercase , return_tensors='''pt''' , max_patches=__lowercase , header_text=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def lowerCAmelCase( self : Tuple ): """simple docstring""" # Initialize image_processor snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase , numpify=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , np.ndarray ) snake_case : Dict = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case : Dict = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case : Optional[int] = image_processor( __lowercase , return_tensors='''pt''' , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def lowerCAmelCase( self : Any ): """simple docstring""" # Initialize image_processor snake_case : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase , torchify=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , torch.Tensor ) # Test not batched input snake_case : Any = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case : Optional[int] = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case : str = image_processor( __lowercase , return_tensors='''pt''' , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class a_ ( lowercase__ , unittest.TestCase ): A__ : Optional[int] = PixaStructImageProcessor if is_vision_available() else None def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Tuple = PixaStructImageProcessingTester(self , num_channels=4 ) snake_case : str = 3 @property def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowercase , '''do_normalize''' ) ) self.assertTrue(hasattr(__lowercase , '''do_convert_rgb''' ) ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" # Initialize image_processor snake_case : int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowercase ) for image in image_inputs: self.assertIsInstance(__lowercase , Image.Image ) # Test not batched input snake_case : Dict = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input snake_case : Union[str, Any] = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched snake_case : Optional[int] = image_processor( __lowercase , return_tensors='''pt''' , max_patches=__lowercase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
715
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class a_ : def __init__( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any]=13 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : List[Any]=24 , UpperCAmelCase__ : Union[str, Any]=16 , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : int=32 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : Optional[int]=37 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Optional[int]=10 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : Optional[Any]=2 , ): """simple docstring""" snake_case : Tuple = parent snake_case : Dict = batch_size snake_case : str = patch_size snake_case : Union[str, Any] = max_length snake_case : str = num_mel_bins snake_case : Any = is_training snake_case : Union[str, Any] = use_labels snake_case : Tuple = hidden_size snake_case : Dict = num_hidden_layers snake_case : Any = num_attention_heads snake_case : Any = intermediate_size snake_case : List[Any] = hidden_act snake_case : str = hidden_dropout_prob snake_case : str = attention_probs_dropout_prob snake_case : str = type_sequence_label_size snake_case : Optional[int] = initializer_range snake_case : str = scope snake_case : int = frequency_stride snake_case : Union[str, Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) snake_case : Optional[int] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 snake_case : Any = (self.max_length - self.patch_size) // self.time_stride + 1 snake_case : Union[str, Any] = frequency_out_dimension * time_out_dimension snake_case : Union[str, Any] = num_patches + 2 def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Optional[int] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) snake_case : str = None if self.use_labels: snake_case : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case : List[str] = self.get_config() return config, input_values, labels def lowerCAmelCase( self : Any ): """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : str = ASTModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : Any = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : int = self.prepare_config_and_inputs() ( ( snake_case ) , ( snake_case ) , ( snake_case ) , ) : int = config_and_inputs snake_case : Tuple = {'''input_values''': input_values} return config, inputs_dict @require_torch class a_ ( a , a , unittest.TestCase ): A__ : List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) A__ : int = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) A__ : Optional[Any] = False A__ : Dict = False A__ : int = False A__ : Optional[int] = False def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int ): """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[int] = ASTModelTester(self ) snake_case : Optional[int] = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=37 ) def lowerCAmelCase( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def lowerCAmelCase( self : Tuple ): """simple docstring""" pass def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Optional[Any] = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case : Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , nn.Linear ) ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Any = model_class(UpperCAmelCase__ ) snake_case : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case : str = [*signature.parameters.keys()] snake_case : List[str] = ['''input_values'''] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) @slow def lowerCAmelCase( self : List[str] ): """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : List[str] = ASTModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def a_ ( ) -> Dict: """simple docstring""" snake_case : Dict = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) snake_case , snake_case : int = torchaudio.load(__magic_name__ ) return audio, sampling_rate @require_torch @require_torchaudio class a_ ( unittest.TestCase ): @cached_property def lowerCAmelCase( self : Any ): """simple docstring""" return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : List[str] = self.default_feature_extractor snake_case : str = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(UpperCAmelCase__ ) snake_case : str = self.default_feature_extractor snake_case , snake_case : int = prepare_audio() snake_case : Optional[int] = audio.squeeze().numpy() snake_case : Optional[Any] = feature_extractor(UpperCAmelCase__ , sampling_rate=UpperCAmelCase__ , return_tensors='''pt''' ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): snake_case : Union[str, Any] = model(**UpperCAmelCase__ ) # verify the logits snake_case : Any = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) snake_case : str = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1e-4 ) )
84
0
from __future__ import annotations import math def a_ ( __magic_name__ , __magic_name__ ) -> float: """simple docstring""" snake_case : Dict = u for i in range(1 , _lowerCAmelCase ): snake_case : Optional[Any] = temp * (u - i) return temp def a_ ( ) -> None: """simple docstring""" snake_case : Optional[Any] = int(input('''enter the numbers of values: ''' ) ) snake_case : list[list[float]] = [] for _ in range(_lowerCAmelCase ): y.append([] ) for i in range(_lowerCAmelCase ): for j in range(_lowerCAmelCase ): y[i].append(_lowerCAmelCase ) snake_case : str = 0 print('''enter the values of parameters in a list: ''' ) snake_case : Tuple = list(map(_lowerCAmelCase , input().split() ) ) print('''enter the values of corresponding parameters: ''' ) for i in range(_lowerCAmelCase ): snake_case : Union[str, Any] = float(input() ) snake_case : Optional[int] = int(input('''enter the value to interpolate: ''' ) ) snake_case : int = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , _lowerCAmelCase ): for j in range(n - i ): snake_case : Optional[Any] = y[j + 1][i - 1] - y[j][i - 1] snake_case : int = y[0][0] for i in range(1 , _lowerCAmelCase ): summ += (ucal(_lowerCAmelCase , _lowerCAmelCase ) * y[0][i]) / math.factorial(_lowerCAmelCase ) print(F"the value at {value} is {summ}" ) if __name__ == "__main__": main()
716
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _a : Union[str, Any] = logging.getLogger(__name__) def a_ ( __magic_name__ , __magic_name__ ) -> Optional[int]: """simple docstring""" return (preds == labels).mean() @dataclass class a_ : A__ : str = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class a_ : A__ : str = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys() )} ) A__ : str = field(metadata={'help': 'Should contain the data files for the task.'} ) A__ : int = field( default=128 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) A__ : bool = field( default=a , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def a_ ( ) -> Dict: """simple docstring""" snake_case : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) snake_case , snake_case , snake_case : Tuple = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"Output directory ({training_args.output_dir}) already exists and is not empty. Use" ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , __magic_name__ ) # Set seed set_seed(training_args.seed ) try: snake_case : int = processors[data_args.task_name]() snake_case : List[str] = processor.get_labels() snake_case : str = len(__magic_name__ ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case : List[Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__magic_name__ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) snake_case : str = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) snake_case : Any = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__magic_name__ , cache_dir=model_args.cache_dir , ) # Get datasets snake_case : Optional[int] = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) snake_case : Any = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(__magic_name__ ) -> Dict: snake_case : str = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(__magic_name__ , p.label_ids )} # Data collator snake_case : Dict = DataCollatorWithPadding(__magic_name__ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer snake_case : List[Any] = Trainer( model=__magic_name__ , args=__magic_name__ , train_dataset=__magic_name__ , eval_dataset=__magic_name__ , compute_metrics=__magic_name__ , data_collator=__magic_name__ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation snake_case : Optional[int] = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) snake_case : Optional[Any] = trainer.evaluate() snake_case : Union[str, Any] = os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_master(): with open(__magic_name__ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''' , __magic_name__ , __magic_name__ ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__magic_name__ ) return results def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" main() if __name__ == "__main__": main()
84
0
def a_ ( __magic_name__ ) -> List[str]: """simple docstring""" snake_case : Any = 1 snake_case : List[Any] = 2 while i * i <= n: snake_case : str = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def a_ ( ) -> Optional[Any]: """simple docstring""" snake_case : List[Any] = 1 snake_case : Tuple = 1 while True: i += 1 t_num += i if count_divisors(__magic_name__ ) > 500: break return t_num if __name__ == "__main__": print(solution())
717
import re def a_ ( __magic_name__ ) -> bool: """simple docstring""" snake_case : List[str] = re.compile( R'''^(?:0|94|\+94|0{2}94)''' R'''7(0|1|2|4|5|6|7|8)''' R'''(-| |)''' R'''\d{7}$''' ) return bool(re.search(__magic_name__ , __magic_name__ ) ) if __name__ == "__main__": _a : Any = '0094702343221' print(is_sri_lankan_phone_number(phone))
84
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _a : int = {'configuration_plbart': ['PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PLBartConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Optional[Any] = ['PLBartTokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = [ 'PLBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'PLBartForCausalLM', 'PLBartForConditionalGeneration', 'PLBartForSequenceClassification', 'PLBartModel', 'PLBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys _a : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure)
718
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class a_ ( unittest.TestCase ): def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : int=18 , UpperCAmelCase__ : Optional[int]=30 , UpperCAmelCase__ : Optional[int]=400 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : int=True , ): """simple docstring""" snake_case : int = size if size is not None else {'''height''': 18, '''width''': 18} snake_case : Optional[Any] = parent snake_case : Any = batch_size snake_case : Any = num_channels snake_case : Union[str, Any] = image_size snake_case : Dict = min_resolution snake_case : Dict = max_resolution snake_case : int = do_resize snake_case : List[str] = size snake_case : List[Any] = apply_ocr def lowerCAmelCase( self : int ): """simple docstring""" return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class a_ ( a , unittest.TestCase ): A__ : List[Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : Optional[Any] = LayoutLMvaImageProcessingTester(self ) @property def lowerCAmelCase( self : Dict ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''apply_ocr''' ) ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def lowerCAmelCase( self : str ): """simple docstring""" pass def lowerCAmelCase( self : Dict ): """simple docstring""" # Initialize image_processing snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image ) # Test not batched input snake_case : Optional[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , UpperCAmelCase__ ) self.assertIsInstance(encoding.boxes , UpperCAmelCase__ ) # Test batched snake_case : Dict = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" # Initialize image_processing snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray ) # 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 : List[Any] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" # Initialize image_processing snake_case : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , 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 : Tuple = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" # with apply_OCR = True snake_case : int = LayoutLMvaImageProcessor() from datasets import load_dataset snake_case : List[Any] = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) snake_case : List[Any] = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) snake_case : Any = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 snake_case : Optional[Any] = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 snake_case : Union[str, Any] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , UpperCAmelCase__ ) self.assertListEqual(encoding.boxes , UpperCAmelCase__ ) # with apply_OCR = False snake_case : str = LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase__ ) snake_case : Optional[Any] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
84
0
class a_ : def __init__( self : int ): """simple docstring""" snake_case : Any = 0 snake_case : Optional[int] = 0 snake_case : str = {} def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : int ): """simple docstring""" if vertex not in self.adjacency: snake_case : Tuple = {} self.num_vertices += 1 def lowerCAmelCase( self : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str ): """simple docstring""" self.add_vertex(lowerCAmelCase_ ) self.add_vertex(lowerCAmelCase_ ) if head == tail: return snake_case : Any = weight snake_case : Union[str, Any] = weight def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : str = self.get_edges() for edge in edges: snake_case , snake_case , snake_case : Optional[Any] = edge edges.remove((tail, head, weight) ) for i in range(len(lowerCAmelCase_ ) ): snake_case : Tuple = list(edges[i] ) edges.sort(key=lambda UpperCAmelCase__ : e[2] ) for i in range(len(lowerCAmelCase_ ) - 1 ): if edges[i][2] >= edges[i + 1][2]: snake_case : List[Any] = edges[i][2] + 1 for edge in edges: snake_case , snake_case , snake_case : Tuple = edge snake_case : int = weight snake_case : int = weight def __str__( self : List[Any] ): """simple docstring""" snake_case : List[Any] = '''''' for tail in self.adjacency: for head in self.adjacency[tail]: snake_case : Optional[Any] = self.adjacency[head][tail] string += F"{head} -> {tail} == {weight}\n" return string.rstrip('''\n''' ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : List[str] = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" return self.adjacency.keys() @staticmethod def lowerCAmelCase( UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : int=None ): """simple docstring""" snake_case : Optional[Any] = Graph() if vertices is None: snake_case : Optional[int] = [] if edges is None: snake_case : Optional[Any] = [] for vertex in vertices: g.add_vertex(lowerCAmelCase_ ) for edge in edges: g.add_edge(*lowerCAmelCase_ ) return g class a_ : def __init__( self : str ): """simple docstring""" snake_case : Tuple = {} snake_case : Union[str, Any] = {} def __len__( self : Dict ): """simple docstring""" return len(self.parent ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Tuple ): """simple docstring""" if item in self.parent: return self.find(lowerCAmelCase_ ) snake_case : str = item snake_case : Optional[Any] = 0 return item def lowerCAmelCase( self : Any , UpperCAmelCase__ : int ): """simple docstring""" if item not in self.parent: return self.make_set(lowerCAmelCase_ ) if item != self.parent[item]: snake_case : Optional[int] = self.find(self.parent[item] ) return self.parent[item] def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any ): """simple docstring""" snake_case : List[str] = self.find(lowerCAmelCase_ ) snake_case : Optional[int] = self.find(lowerCAmelCase_ ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: snake_case : Optional[int] = roota return roota if self.rank[roota] < self.rank[roota]: snake_case : Optional[int] = roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 snake_case : Tuple = roota return roota return None @staticmethod def lowerCAmelCase( UpperCAmelCase__ : List[str] ): """simple docstring""" snake_case : str = graph.num_vertices snake_case : Any = Graph.UnionFind() snake_case : List[str] = [] while num_components > 1: snake_case : str = {} for vertex in graph.get_vertices(): snake_case : str = -1 snake_case : int = graph.get_edges() for edge in edges: snake_case , snake_case , snake_case : Dict = edge edges.remove((tail, head, weight) ) for edge in edges: snake_case , snake_case , snake_case : Optional[Any] = edge snake_case : Optional[int] = union_find.find(lowerCAmelCase_ ) snake_case : List[str] = union_find.find(lowerCAmelCase_ ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: snake_case : Any = [head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: snake_case : Any = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: snake_case , snake_case , snake_case : Union[str, Any] = cheap_edge[vertex] if union_find.find(lowerCAmelCase_ ) != union_find.find(lowerCAmelCase_ ): union_find.union(lowerCAmelCase_ , lowerCAmelCase_ ) mst_edges.append(cheap_edge[vertex] ) snake_case : List[str] = num_components - 1 snake_case : Optional[int] = Graph.build(edges=lowerCAmelCase_ ) return mst
719
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _a : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name _a : Dict = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def a_ ( __magic_name__ , __magic_name__ , __magic_name__=8 ) -> str: """simple docstring""" snake_case : List[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 snake_case : Tuple = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a_ ( a ): def __init__( self : Optional[int] , UpperCAmelCase__ : UNetaDConditionModel , UpperCAmelCase__ : DDPMScheduler , UpperCAmelCase__ : VQModel , ): """simple docstring""" super().__init__() self.register_modules( unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , movq=UpperCAmelCase__ , ) snake_case : List[Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCAmelCase( self : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any ): """simple docstring""" if latents is None: snake_case : int = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) else: if latents.shape != shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}" ) snake_case : Optional[Any] = latents.to(UpperCAmelCase__ ) snake_case : List[Any] = latents * scheduler.init_noise_sigma return latents def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Optional[int]=0 ): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) snake_case : Union[str, Any] = torch.device(F"cuda:{gpu_id}" ) snake_case : Dict = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Any=0 ): """simple docstring""" if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) snake_case : Optional[int] = torch.device(F"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=UpperCAmelCase__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) snake_case : List[str] = None for cpu_offloaded_model in [self.unet, self.movq]: snake_case , snake_case : Optional[int] = cpu_offload_with_hook(UpperCAmelCase__ , UpperCAmelCase__ , prev_module_hook=UpperCAmelCase__ ) # We'll offload the last model manually. snake_case : Tuple = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(UpperCAmelCase__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase__ : torch.FloatTensor , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 100 , UpperCAmelCase__ : float = 4.0 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[torch.FloatTensor] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" snake_case : Optional[int] = self._execution_device snake_case : Union[str, Any] = guidance_scale > 1.0 if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : Any = torch.cat(UpperCAmelCase__ , dim=0 ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : Union[str, Any] = torch.cat(UpperCAmelCase__ , dim=0 ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : int = torch.cat(UpperCAmelCase__ , dim=0 ) snake_case : List[Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: snake_case : Dict = image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Optional[Any] = negative_image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Tuple = hint.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Optional[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase__ ) snake_case : List[str] = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase__ ) self.scheduler.set_timesteps(UpperCAmelCase__ , device=UpperCAmelCase__ ) snake_case : str = self.scheduler.timesteps snake_case : Optional[Any] = self.movq.config.latent_channels snake_case , snake_case : Optional[Any] = downscale_height_and_width(UpperCAmelCase__ , UpperCAmelCase__ , self.movq_scale_factor ) # create initial latent snake_case : Dict = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(UpperCAmelCase__ ) ): # expand the latents if we are doing classifier free guidance snake_case : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case : Optional[int] = {'''image_embeds''': image_embeds, '''hint''': hint} snake_case : Any = self.unet( sample=UpperCAmelCase__ , timestep=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , added_cond_kwargs=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , )[0] if do_classifier_free_guidance: snake_case , snake_case : Dict = noise_pred.split(latents.shape[1] , dim=1 ) snake_case , snake_case : Any = noise_pred.chunk(2 ) snake_case , snake_case : Dict = variance_pred.chunk(2 ) snake_case : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) snake_case : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): snake_case , snake_case : Tuple = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 snake_case : List[Any] = self.scheduler.step( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , generator=UpperCAmelCase__ , )[0] # post-processing snake_case : List[Any] = self.movq.decode(UpperCAmelCase__ , force_not_quantize=UpperCAmelCase__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: snake_case : Optional[Any] = image * 0.5 + 0.5 snake_case : int = image.clamp(0 , 1 ) snake_case : List[str] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": snake_case : str = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
84
0
from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean _a : str = 0 _a : Optional[int] = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] _a : Tuple = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right _a : Tuple = tuple[int, int] class a_ : def __init__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Node | None , ): """simple docstring""" snake_case : Optional[int] = pos_x snake_case : List[Any] = pos_y snake_case : Union[str, Any] = (pos_y, pos_x) snake_case : List[Any] = goal_x snake_case : Optional[Any] = goal_y snake_case : str = g_cost snake_case : str = parent snake_case : Optional[Any] = self.calculate_heuristic() snake_case : List[str] = self.g_cost + self.h_cost def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : List[str] = self.pos_x - self.goal_x snake_case : Optional[Any] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(__a ) + abs(__a ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[Any] , UpperCAmelCase__ : Node ): """simple docstring""" return self.f_cost < other.f_cost class a_ : def __init__( self : Any , UpperCAmelCase__ : TPosition , UpperCAmelCase__ : TPosition ): """simple docstring""" snake_case : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , __a ) snake_case : Tuple = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99_999 , __a ) snake_case : Optional[Any] = [self.start] snake_case : list[Node] = [] snake_case : Tuple = False def lowerCAmelCase( self : int ): """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() snake_case : Tuple = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(__a ) self.closed_nodes.append(__a ) snake_case : Dict = self.get_successors(__a ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(__a ) else: # retrieve the best current path snake_case : Any = self.open_nodes.pop(self.open_nodes.index(__a ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(__a ) else: self.open_nodes.append(__a ) return [self.start.pos] def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Node ): """simple docstring""" snake_case : str = [] for action in delta: snake_case : Union[str, Any] = parent.pos_x + action[1] snake_case : Optional[Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(__a ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( __a , __a , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , __a , ) ) return successors def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Node | None ): """simple docstring""" snake_case : Dict = node snake_case : Tuple = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) snake_case : str = current_node.parent path.reverse() return path class a_ : def __init__( self : Union[str, Any] , UpperCAmelCase__ : TPosition , UpperCAmelCase__ : TPosition ): """simple docstring""" snake_case : Dict = AStar(__a , __a ) snake_case : str = AStar(__a , __a ) snake_case : int = False def lowerCAmelCase( self : str ): """simple docstring""" while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() snake_case : Tuple = self.fwd_astar.open_nodes.pop(0 ) snake_case : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( __a , __a ) self.fwd_astar.closed_nodes.append(__a ) self.bwd_astar.closed_nodes.append(__a ) snake_case : int = current_bwd_node snake_case : List[Any] = current_fwd_node snake_case : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(__a ), self.bwd_astar: self.bwd_astar.get_successors(__a ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(__a ) else: # retrieve the best current path snake_case : str = astar.open_nodes.pop( astar.open_nodes.index(__a ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(__a ) else: astar.open_nodes.append(__a ) return [self.fwd_astar.start.pos] def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : Node , UpperCAmelCase__ : Node ): """simple docstring""" snake_case : str = self.fwd_astar.retrace_path(__a ) snake_case : Any = self.bwd_astar.retrace_path(__a ) bwd_path.pop() bwd_path.reverse() snake_case : Any = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] _a : Optional[int] = (0, 0) _a : Optional[int] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) _a : Optional[int] = time.time() _a : Optional[int] = AStar(init, goal) _a : int = a_star.search() _a : Optional[Any] = time.time() - start_time print(f"AStar execution time = {end_time:f} seconds") _a : List[Any] = time.time() _a : List[str] = BidirectionalAStar(init, goal) _a : List[str] = time.time() - bd_start_time print(f"BidirectionalAStar execution time = {bd_end_time:f} seconds")
720
import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _a : List[Any] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class a_ ( a , unittest.TestCase ): A__ : Dict = ReformerTokenizer A__ : Optional[int] = ReformerTokenizerFast A__ : str = True A__ : Tuple = False A__ : str = True def lowerCAmelCase( self : List[Any] ): """simple docstring""" super().setUp() snake_case : str = ReformerTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : int = '''<s>''' snake_case : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''j''' ) self.assertEqual(len(UpperCAmelCase__ ) , 1_000 ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def lowerCAmelCase( self : Dict ): """simple docstring""" if not self.test_rust_tokenizer: return snake_case : Any = self.get_tokenizer() snake_case : str = self.get_rust_tokenizer() snake_case : Tuple = '''I was born in 92000, and this is falsé.''' snake_case : str = tokenizer.tokenize(UpperCAmelCase__ ) snake_case : int = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : Union[str, Any] = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) snake_case : List[str] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : List[str] = self.get_rust_tokenizer() snake_case : Optional[int] = tokenizer.encode(UpperCAmelCase__ ) snake_case : Optional[Any] = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : List[Any]=15 ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case : str = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) # Simple input snake_case : Union[str, Any] = '''This is a simple input''' snake_case : List[str] = ['''This is a simple input 1''', '''This is a simple input 2'''] snake_case : int = ('''This is a simple input''', '''This is a pair''') snake_case : int = [ ('''This is a simple input 1''', '''This is a simple input 2'''), ('''This is a simple pair 1''', '''This is a simple pair 2'''), ] # Simple input tests self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Simple input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Simple input self.assertRaises( UpperCAmelCase__ , tokenizer_r.batch_encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' , ) # Pair input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Pair input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Pair input self.assertRaises( UpperCAmelCase__ , tokenizer_r.batch_encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' , ) def lowerCAmelCase( self : str ): """simple docstring""" pass def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Union[str, Any] = ReformerTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) snake_case : List[str] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [285, 46, 10, 170, 382] , ) snake_case : int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) snake_case : int = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) snake_case : List[Any] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def lowerCAmelCase( self : Tuple ): """simple docstring""" return ReformerTokenizer.from_pretrained('''google/reformer-crime-and-punishment''' ) @slow def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Any = '''Hello World!''' snake_case : Optional[Any] = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @slow def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[Any] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) snake_case : Dict = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @require_torch @slow def lowerCAmelCase( self : List[Any] ): """simple docstring""" import torch from transformers import ReformerConfig, ReformerModel # Build sequence snake_case : Any = list(self.big_tokenizer.get_vocab().keys() )[:10] snake_case : Union[str, Any] = ''' '''.join(UpperCAmelCase__ ) snake_case : Optional[int] = self.big_tokenizer.encode_plus(UpperCAmelCase__ , return_tensors='''pt''' ) snake_case : List[str] = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors='''pt''' ) snake_case : Optional[Any] = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) snake_case : Tuple = encoded_sequence['''input_ids'''].shape snake_case : List[Any] = ReformerModel(UpperCAmelCase__ ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**UpperCAmelCase__ ) model(**UpperCAmelCase__ ) @slow def lowerCAmelCase( self : Optional[int] ): """simple docstring""" # fmt: off snake_case : Tuple = {'''input_ids''': [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 snake_case : Tuple = [ '''This is a very simple sentence.''', '''The quick brown fox jumps over the lazy dog.''', ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''google/reformer-crime-and-punishment''' , revision='''0e6c3decb8211d49bf881013425dc8b0448b3f5a''' , padding=UpperCAmelCase__ , sequences=UpperCAmelCase__ , )
84
0
from __future__ import annotations from collections.abc import Generator def a_ ( ) -> Optional[int]: """simple docstring""" snake_case : Optional[int] = {} snake_case : Optional[Any] = 2 while True: snake_case : List[str] = factor_map.pop(_UpperCamelCase , _UpperCamelCase ) if factor: snake_case : List[Any] = factor + prime while x in factor_map: x += factor snake_case : Optional[int] = factor else: snake_case : Union[str, Any] = prime yield prime prime += 1 def a_ ( __magic_name__ = 1e10 ) -> List[Any]: """simple docstring""" snake_case : Tuple = sieve() snake_case : Optional[int] = 1 while True: snake_case : Optional[int] = next(_UpperCamelCase ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(_UpperCamelCase ) n += 2 if __name__ == "__main__": print(solution())
721
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" snake_case , snake_case : Any = image.size snake_case , snake_case : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 snake_case : List[str] = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) snake_case : Dict = np.array(__magic_name__ ).astype(np.floataa ) / 255.0 snake_case : Optional[Any] = image[None].transpose(0 , 3 , 1 , 2 ) snake_case : Tuple = torch.from_numpy(__magic_name__ ) return 2.0 * image - 1.0 class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : VQModel , UpperCAmelCase__ : UNetaDModel , UpperCAmelCase__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ): """simple docstring""" super().__init__() self.register_modules(vqvae=UpperCAmelCase__ , unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) @torch.no_grad() def __call__( self : Any , UpperCAmelCase__ : Union[torch.Tensor, PIL.Image.Image] = None , UpperCAmelCase__ : Optional[int] = 1 , UpperCAmelCase__ : Optional[int] = 100 , UpperCAmelCase__ : Optional[float] = 0.0 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" if isinstance(UpperCAmelCase__ , PIL.Image.Image ): snake_case : Optional[int] = 1 elif isinstance(UpperCAmelCase__ , torch.Tensor ): snake_case : Any = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(UpperCAmelCase__ )}" ) if isinstance(UpperCAmelCase__ , PIL.Image.Image ): snake_case : Optional[Any] = preprocess(UpperCAmelCase__ ) snake_case , snake_case : Union[str, Any] = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image snake_case : List[Any] = (batch_size, self.unet.config.in_channels // 2, height, width) snake_case : str = next(self.unet.parameters() ).dtype snake_case : Dict = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=self.device , dtype=UpperCAmelCase__ ) snake_case : Any = image.to(device=self.device , dtype=UpperCAmelCase__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(UpperCAmelCase__ , device=self.device ) snake_case : Optional[Any] = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler snake_case : Union[str, Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] snake_case : Any = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case : Optional[Any] = {} if accepts_eta: snake_case : Dict = eta for t in self.progress_bar(UpperCAmelCase__ ): # concat latents and low resolution image in the channel dimension. snake_case : Optional[int] = torch.cat([latents, image] , dim=1 ) snake_case : str = self.scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) # predict the noise residual snake_case : int = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case : Any = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample # decode the image latents with the VQVAE snake_case : Optional[int] = self.vqvae.decode(UpperCAmelCase__ ).sample snake_case : int = torch.clamp(UpperCAmelCase__ , -1.0 , 1.0 ) snake_case : Dict = image / 2 + 0.5 snake_case : int = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case : Any = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
84
0
import math def a_ ( __magic_name__ ) -> int: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ): snake_case : str = F"Input value of [number={number}] must be an integer" raise TypeError(__magic_name__ ) if number < 1: snake_case : Tuple = F"Input value of [number={number}] must be > 0" raise ValueError(__magic_name__ ) elif number == 1: return 3 elif number == 2: return 5 else: snake_case : Tuple = int(math.log(number // 3 , 2 ) ) + 2 snake_case : Optional[Any] = [3, 5] snake_case : Any = 2 snake_case : str = 3 for block in range(1 , __magic_name__ ): for _ in range(__magic_name__ ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): _a : Tuple = 0 try: _a : Optional[int] = proth(number) except ValueError: print(f"ValueError: there is no {number}th Proth number") continue print(f"The {number}th Proth number: {value}")
700
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class a_ ( a ): def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = tempfile.mkdtemp() snake_case : Dict = 5 # Realm tok snake_case : str = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] snake_case : Tuple = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) snake_case : Any = os.path.join(UpperCAmelCase__ , 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 : Tuple = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def lowerCAmelCase( self : Any ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Any = RealmConfig(num_block_records=self.num_block_records ) return config def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[int] = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Dict = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=UpperCAmelCase__ , ) return block_records def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Tuple = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[str] = self.get_config() snake_case : Optional[Any] = self.get_dummy_retriever() snake_case : Optional[int] = retriever.tokenizer snake_case : Dict = np.array([0, 3] , dtype='''long''' ) snake_case : Optional[int] = tokenizer(['''Test question'''] ).input_ids snake_case : Union[str, Any] = tokenizer( ['''the fourth'''] , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ).input_ids snake_case : Optional[Any] = config.reader_seq_len snake_case , snake_case , snake_case , snake_case : List[str] = retriever( UpperCAmelCase__ , UpperCAmelCase__ , answer_ids=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors='''np''' ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = self.get_config() snake_case : Optional[int] = self.get_dummy_retriever() snake_case : List[str] = retriever.tokenizer snake_case : Optional[Any] = np.array([0, 3, 5] , dtype='''long''' ) snake_case : Optional[int] = tokenizer(['''Test question'''] ).input_ids snake_case : Any = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ).input_ids snake_case : List[Any] = config.reader_seq_len snake_case , snake_case , snake_case , snake_case : Union[str, Any] = retriever( UpperCAmelCase__ , UpperCAmelCase__ , answer_ids=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors='''np''' ) self.assertEqual([False, True, True] , UpperCAmelCase__ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , UpperCAmelCase__ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : int = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path snake_case : Optional[Any] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: snake_case : Any = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) snake_case : Any = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
84
0
from math import factorial _a : Any = {str(d): factorial(d) for d in range(10)} def a_ ( __magic_name__ ) -> int: """simple docstring""" return sum(DIGIT_FACTORIAL[d] for d in str(_SCREAMING_SNAKE_CASE ) ) def a_ ( ) -> int: """simple docstring""" snake_case : List[str] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , _SCREAMING_SNAKE_CASE ) if sum_of_digit_factorial(_SCREAMING_SNAKE_CASE ) == i ) if __name__ == "__main__": print(f"{solution() = }")
701
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _a : str = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = ['EncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Dict = ['TFEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = ['FlaxEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys _a : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
84
0
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging _a : Any = logging.get_logger(__name__) # TODO Update this _a : Optional[Any] = { 'facebook/esm-1b': 'https://huggingface.co/facebook/esm-1b/resolve/main/config.json', # See all ESM models at https://huggingface.co/models?filter=esm } class a_ ( __snake_case ): A__ : List[str] = 'esm' def __init__( self : Any , UpperCAmelCase__ : int=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Optional[int]=768 , UpperCAmelCase__ : str=12 , UpperCAmelCase__ : Any=12 , UpperCAmelCase__ : List[Any]=3_072 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[int]=1_026 , UpperCAmelCase__ : List[str]=0.02 , UpperCAmelCase__ : Optional[Any]=1e-1_2 , UpperCAmelCase__ : Union[str, Any]="absolute" , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : Any , ): """simple docstring""" super().__init__(pad_token_id=__UpperCamelCase , mask_token_id=__UpperCamelCase , **__UpperCamelCase ) snake_case : Tuple = vocab_size snake_case : str = hidden_size snake_case : List[str] = num_hidden_layers snake_case : Union[str, Any] = num_attention_heads snake_case : Any = intermediate_size snake_case : int = hidden_dropout_prob snake_case : Optional[Any] = attention_probs_dropout_prob snake_case : Dict = max_position_embeddings snake_case : List[str] = initializer_range snake_case : Union[str, Any] = layer_norm_eps snake_case : Optional[Any] = position_embedding_type snake_case : Any = use_cache snake_case : List[Any] = emb_layer_norm_before snake_case : Optional[int] = token_dropout snake_case : List[Any] = is_folding_model if is_folding_model: if esmfold_config is None: logger.info('''No esmfold_config supplied for folding model, using default values.''' ) snake_case : Union[str, Any] = EsmFoldConfig() elif isinstance(__UpperCamelCase , __UpperCamelCase ): snake_case : Dict = EsmFoldConfig(**__UpperCamelCase ) snake_case : Dict = esmfold_config if vocab_list is None: logger.warning('''No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!''' ) snake_case : Dict = get_default_vocab_list() else: snake_case : Optional[int] = vocab_list else: snake_case : Tuple = None snake_case : Union[str, Any] = None if self.esmfold_config is not None and getattr(self.esmfold_config , '''use_esm_attn_map''' , __UpperCamelCase ): raise ValueError('''The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!''' ) def lowerCAmelCase( self : str ): """simple docstring""" snake_case : List[str] = super().to_dict() if isinstance(self.esmfold_config , __UpperCamelCase ): snake_case : int = self.esmfold_config.to_dict() return output @dataclass class a_ : A__ : Optional[int] = None A__ : Tuple = True A__ : Any = False A__ : Optional[Any] = False A__ : str = False A__ : str = 0 A__ : str = True A__ : Tuple = False A__ : Dict = 128 A__ : Tuple = None def lowerCAmelCase( self : str ): """simple docstring""" if self.trunk is None: snake_case : Optional[Any] = TrunkConfig() elif isinstance(self.trunk , __UpperCamelCase ): snake_case : Any = TrunkConfig(**self.trunk ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Union[str, Any] = asdict(self ) snake_case : Optional[int] = self.trunk.to_dict() return output @dataclass class a_ : A__ : Tuple = 48 A__ : List[str] = 1024 A__ : Union[str, Any] = 128 A__ : Union[str, Any] = 32 A__ : Any = 32 A__ : Any = 32 A__ : List[Any] = 0 A__ : Optional[Any] = 0 A__ : Optional[Any] = False A__ : Any = 4 A__ : Any = 128 A__ : int = None def lowerCAmelCase( self : Dict ): """simple docstring""" if self.structure_module is None: snake_case : Union[str, Any] = StructureModuleConfig() elif isinstance(self.structure_module , __UpperCamelCase ): snake_case : str = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(F"`max_recycles` should be positive, got {self.max_recycles}." ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '''`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got''' F" {self.sequence_state_dim} and {self.sequence_state_dim}." ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '''`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got''' F" {self.pairwise_state_dim} and {self.pairwise_state_dim}." ) snake_case : List[Any] = self.sequence_state_dim // self.sequence_head_width snake_case : Union[str, Any] = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '''`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got''' F" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}." ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '''`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got''' F" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}." ) if self.pairwise_state_dim % 2 != 0: raise ValueError(F"`pairwise_state_dim` should be even, got {self.pairwise_state_dim}." ) if self.dropout >= 0.4: raise ValueError(F"`dropout` should not be greater than 0.4, got {self.dropout}." ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Tuple = asdict(self ) snake_case : List[Any] = self.structure_module.to_dict() return output @dataclass class a_ : A__ : Dict = 384 A__ : Union[str, Any] = 128 A__ : Union[str, Any] = 16 A__ : Union[str, Any] = 128 A__ : List[str] = 12 A__ : Dict = 4 A__ : List[Any] = 8 A__ : Optional[Any] = 0.1 A__ : Union[str, Any] = 8 A__ : Optional[Any] = 1 A__ : int = 2 A__ : Union[str, Any] = 7 A__ : Any = 10 A__ : int = 1e-8 A__ : Dict = 1e5 def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return asdict(self ) def a_ ( ) -> Dict: """simple docstring""" return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
702
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer _a : str = logging.get_logger(__name__) _a : Optional[int] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Optional[Any] = { 'vocab_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json' ), }, } _a : Union[str, Any] = { 'yjernite/retribert-base-uncased': 512, } _a : Tuple = { 'yjernite/retribert-base-uncased': {'do_lower_case': True}, } class a_ ( a ): A__ : List[str] = VOCAB_FILES_NAMES A__ : Any = PRETRAINED_VOCAB_FILES_MAP A__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Any = PRETRAINED_INIT_CONFIGURATION A__ : Optional[Any] = RetriBertTokenizer A__ : Any = ['input_ids', 'attention_mask'] def __init__( self : Optional[int] , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Dict="[UNK]" , UpperCAmelCase__ : str="[SEP]" , UpperCAmelCase__ : Union[str, Any]="[PAD]" , UpperCAmelCase__ : Dict="[CLS]" , UpperCAmelCase__ : Optional[Any]="[MASK]" , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=None , **UpperCAmelCase__ : Dict , ): """simple docstring""" super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , do_lower_case=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , tokenize_chinese_chars=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ , **UpperCAmelCase__ , ) snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCAmelCase__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCAmelCase__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCAmelCase__ ) != tokenize_chinese_chars ): snake_case : int = getattr(UpperCAmelCase__ , normalizer_state.pop('''type''' ) ) snake_case : List[Any] = do_lower_case snake_case : Union[str, Any] = strip_accents snake_case : int = tokenize_chinese_chars snake_case : int = normalizer_class(**UpperCAmelCase__ ) snake_case : Union[str, Any] = do_lower_case def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=None ): """simple docstring""" snake_case : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ): """simple docstring""" snake_case : List[Any] = [self.sep_token_id] snake_case : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ): """simple docstring""" snake_case : Tuple = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ )
84
0
import os from distutils.util import strtobool def a_ ( __magic_name__ , __magic_name__ ) -> Optional[int]: """simple docstring""" for e in env_keys: snake_case : List[str] = int(os.environ.get(lowerCAmelCase_ , -1 ) ) if val >= 0: return val return default def a_ ( __magic_name__ , __magic_name__=False ) -> Any: """simple docstring""" snake_case : List[Any] = os.environ.get(lowerCAmelCase_ , str(lowerCAmelCase_ ) ) return strtobool(lowerCAmelCase_ ) == 1 # As its name indicates `strtobool` actually returns an int... def a_ ( __magic_name__ , __magic_name__="no" ) -> Dict: """simple docstring""" snake_case : List[str] = os.environ.get(lowerCAmelCase_ , str(lowerCAmelCase_ ) ) return value
703
import string import numpy def a_ ( __magic_name__ , __magic_name__ ) -> int: """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , __magic_name__ ) class a_ : A__ : List[Any] = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) A__ : List[str] = numpy.vectorize(lambda a : x % 36 ) A__ : Dict = numpy.vectorize(a ) def __init__( self : List[str] , UpperCAmelCase__ : numpy.ndarray ): """simple docstring""" snake_case : int = self.modulus(UpperCAmelCase__ ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key snake_case : List[str] = encrypt_key.shape[0] def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : str ): """simple docstring""" return self.key_string.index(UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : int ): """simple docstring""" return self.key_string[round(UpperCAmelCase__ )] def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: snake_case : Tuple = det % len(self.key_string ) snake_case : Tuple = len(self.key_string ) if greatest_common_divisor(UpperCAmelCase__ , len(self.key_string ) ) != 1: snake_case : List[Any] = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[int] = [char for char in text.upper() if char in self.key_string] snake_case : Optional[int] = chars[-1] while len(UpperCAmelCase__ ) % self.break_key != 0: chars.append(UpperCAmelCase__ ) return "".join(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[int] = self.process_text(text.upper() ) snake_case : Optional[int] = '''''' for i in range(0 , len(UpperCAmelCase__ ) - self.break_key + 1 , self.break_key ): snake_case : int = text[i : i + self.break_key] snake_case : int = [self.replace_letters(UpperCAmelCase__ ) for char in batch] snake_case : Tuple = numpy.array([vec] ).T snake_case : Optional[Any] = self.modulus(self.encrypt_key.dot(UpperCAmelCase__ ) ).T.tolist()[ 0 ] snake_case : Dict = ''''''.join( self.replace_digits(UpperCAmelCase__ ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Optional[int] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: snake_case : int = det % len(self.key_string ) snake_case : Dict = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: snake_case : Any = i break snake_case : Any = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(UpperCAmelCase__ ) ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Any = self.make_decrypt_key() snake_case : Optional[Any] = self.process_text(text.upper() ) snake_case : int = '''''' for i in range(0 , len(UpperCAmelCase__ ) - self.break_key + 1 , self.break_key ): snake_case : Any = text[i : i + self.break_key] snake_case : int = [self.replace_letters(UpperCAmelCase__ ) for char in batch] snake_case : List[str] = numpy.array([vec] ).T snake_case : Optional[Any] = self.modulus(decrypt_key.dot(UpperCAmelCase__ ) ).T.tolist()[0] snake_case : int = ''''''.join( self.replace_digits(UpperCAmelCase__ ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def a_ ( ) -> None: """simple docstring""" snake_case : Any = int(input('''Enter the order of the encryption key: ''' ) ) snake_case : List[Any] = [] print('''Enter each row of the encryption key with space separated integers''' ) for _ in range(__magic_name__ ): snake_case : Optional[Any] = [int(__magic_name__ ) for x in input().split()] hill_matrix.append(__magic_name__ ) snake_case : List[str] = HillCipher(numpy.array(__magic_name__ ) ) print('''Would you like to encrypt or decrypt some text? (1 or 2)''' ) snake_case : int = input('''\n1. Encrypt\n2. Decrypt\n''' ) if option == "1": snake_case : List[Any] = input('''What text would you like to encrypt?: ''' ) print('''Your encrypted text is:''' ) print(hc.encrypt(__magic_name__ ) ) elif option == "2": snake_case : int = input('''What text would you like to decrypt?: ''' ) print('''Your decrypted text is:''' ) print(hc.decrypt(__magic_name__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
84
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _a : Optional[Any] = { 'configuration_roformer': ['ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoFormerConfig', 'RoFormerOnnxConfig'], 'tokenization_roformer': ['RoFormerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : List[Any] = ['RoFormerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Optional[Any] = [ '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: _a : str = [ '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: _a : Dict = [ '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 _a : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
704
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class a_ ( a ): A__ : List[Any] = 'Salesforce/blip-image-captioning-base' A__ : Dict = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) A__ : str = 'image_captioner' A__ : Dict = AutoModelForVisionaSeq A__ : Optional[Any] = ['image'] A__ : List[str] = ['text'] def __init__( self : List[str] , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : "Image" ): """simple docstring""" return self.pre_processor(images=UpperCAmelCase__ , return_tensors='''pt''' ) def lowerCAmelCase( self : Any , UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" return self.model.generate(**UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : List[Any] ): """simple docstring""" return self.pre_processor.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ )[0].strip()
84
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _a : Optional[Any] = logging.get_logger(__name__) _a : Union[str, Any] = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class a_ ( __SCREAMING_SNAKE_CASE ): A__ : Optional[int] = 'camembert' def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=30_522 , UpperCAmelCase__ : Optional[int]=768 , UpperCAmelCase__ : List[Any]=12 , UpperCAmelCase__ : Tuple=12 , UpperCAmelCase__ : Union[str, Any]=3_072 , UpperCAmelCase__ : Any="gelu" , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : int=512 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : List[str]=0.02 , UpperCAmelCase__ : List[str]=1e-1_2 , UpperCAmelCase__ : Optional[int]=1 , UpperCAmelCase__ : int=0 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Union[str, Any]="absolute" , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Optional[int]=None , **UpperCAmelCase__ : Any , ): """simple docstring""" super().__init__(pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , **__snake_case ) snake_case : Optional[Any] = vocab_size snake_case : List[str] = hidden_size snake_case : str = num_hidden_layers snake_case : str = num_attention_heads snake_case : Optional[Any] = hidden_act snake_case : Optional[Any] = intermediate_size snake_case : Tuple = hidden_dropout_prob snake_case : Dict = attention_probs_dropout_prob snake_case : Union[str, Any] = max_position_embeddings snake_case : Optional[int] = type_vocab_size snake_case : Any = initializer_range snake_case : List[Any] = layer_norm_eps snake_case : Tuple = position_embedding_type snake_case : Tuple = use_cache snake_case : Dict = classifier_dropout class a_ ( __SCREAMING_SNAKE_CASE ): @property def lowerCAmelCase( self : Dict ): """simple docstring""" if self.task == "multiple-choice": snake_case : List[str] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: snake_case : Dict = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
705
def a_ ( __magic_name__ ) -> bool: """simple docstring""" if p < 2: raise ValueError('''p should not be less than 2!''' ) elif p == 2: return True snake_case : int = 4 snake_case : Optional[Any] = (1 << p) - 1 for _ in range(p - 2 ): snake_case : Optional[Any] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
84
0
from __future__ import annotations _a : Any = { """A""": ["""B""", """C""", """E"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F""", """G"""], """D""": ["""B"""], """E""": ["""A""", """B""", """D"""], """F""": ["""C"""], """G""": ["""C"""], } class a_ : def __init__( self : Union[str, Any] , UpperCAmelCase__ : dict[str, list[str]] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Union[str, Any] = graph # mapping node to its parent in resulting breadth first tree snake_case : Dict = {} snake_case : Tuple = source_vertex def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : int = {self.source_vertex} snake_case : List[Any] = None snake_case : int = [self.source_vertex] # first in first out queue while queue: snake_case : Optional[int] = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(UpperCAmelCase__ ) snake_case : int = vertex queue.append(UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : str ): """simple docstring""" if target_vertex == self.source_vertex: return self.source_vertex snake_case : Tuple = self.parent.get(UpperCAmelCase__ ) if target_vertex_parent is None: snake_case : List[str] = ( F"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(UpperCAmelCase__ ) return self.shortest_path(UpperCAmelCase__ ) + F"->{target_vertex}" if __name__ == "__main__": _a : Tuple = Graph(graph, 'G') g.breath_first_search() print(g.shortest_path('D')) print(g.shortest_path('G')) print(g.shortest_path('Foo'))
706
from sklearn.metrics import fa_score import datasets _a : List[str] = '\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n' _a : Dict = '\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {\'f1\': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results[\'f1\'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results[\'f1\'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")\n >>> print(round(results[\'f1\'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {\'f1\': array([0.8, 0. , 0. ])}\n' _a : List[Any] = '\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' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : Any ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'''] , ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : List[str]="binary" , UpperCAmelCase__ : str=None ): """simple docstring""" snake_case : List[Any] = fa_score( UpperCAmelCase__ , UpperCAmelCase__ , labels=UpperCAmelCase__ , pos_label=UpperCAmelCase__ , average=UpperCAmelCase__ , sample_weight=UpperCAmelCase__ ) return {"f1": float(UpperCAmelCase__ ) if score.size == 1 else score}
84
0
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): A__ : Tuple = StableUnCLIPPipeline A__ : Union[str, Any] = TEXT_TO_IMAGE_PARAMS A__ : List[str] = TEXT_TO_IMAGE_BATCH_PARAMS A__ : Any = TEXT_TO_IMAGE_IMAGE_PARAMS A__ : str = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false A__ : Union[str, Any] = False def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Tuple = 32 snake_case : List[str] = embedder_hidden_size # prior components torch.manual_seed(0 ) snake_case : Optional[int] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) snake_case : int = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__a , projection_dim=__a , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) ) torch.manual_seed(0 ) snake_case : str = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=__a , num_layers=1 , ) torch.manual_seed(0 ) snake_case : List[Any] = DDPMScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1_000 , clip_sample=__a , clip_sample_range=5.0 , beta_schedule='''squaredcos_cap_v2''' , ) # regular denoising components torch.manual_seed(0 ) snake_case : str = StableUnCLIPImageNormalizer(embedding_dim=__a ) snake_case : Optional[Any] = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) snake_case : int = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) snake_case : int = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__a , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) ) torch.manual_seed(0 ) snake_case : Union[str, Any] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='''projection''' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__a , layers_per_block=1 , upcast_attention=__a , use_linear_projection=__a , ) torch.manual_seed(0 ) snake_case : Optional[Any] = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.0_0085 , beta_end=0.012 , prediction_type='''v_prediction''' , set_alpha_to_one=__a , steps_offset=1 , ) torch.manual_seed(0 ) snake_case : Union[str, Any] = AutoencoderKL() snake_case : List[str] = { # prior components "prior_tokenizer": prior_tokenizer, "prior_text_encoder": prior_text_encoder, "prior": prior, "prior_scheduler": prior_scheduler, # image noising components "image_normalizer": image_normalizer, "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder, "unet": unet, "scheduler": scheduler, "vae": vae, } return components def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str]=0 ): """simple docstring""" if str(__a ).startswith('''mps''' ): snake_case : Optional[Any] = torch.manual_seed(__a ) else: snake_case : List[str] = torch.Generator(device=__a ).manual_seed(__a ) snake_case : List[Any] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "prior_num_inference_steps": 2, "output_type": "numpy", } return inputs def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Optional[int] = torch_device == "cpu" self._test_attention_slicing_forward_pass(test_max_difference=__a ) def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : Optional[Any] = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=__a ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): def lowerCAmelCase( self : Dict ): """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Any = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy''' ) snake_case : Tuple = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() snake_case : List[str] = torch.Generator(device='''cpu''' ).manual_seed(0 ) snake_case : Optional[Any] = pipe('''anime turle''' , generator=__a , output_type='''np''' ) snake_case : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__a , __a ) def lowerCAmelCase( self : int ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() snake_case : Optional[Any] = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) snake_case : Optional[int] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() snake_case : str = pipe( '''anime turtle''' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='''np''' , ) snake_case : Dict = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
707
def a_ ( __magic_name__ ) -> int: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ): raise TypeError('''only integers accepted as input''' ) else: snake_case : str = str(abs(__magic_name__ ) ) snake_case : Optional[Any] = [list(__magic_name__ ) for char in range(len(__magic_name__ ) )] for index in range(len(__magic_name__ ) ): num_transpositions[index].pop(__magic_name__ ) return max( int(''''''.join(list(__magic_name__ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
84
0
import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers _a : Union[str, Any] = 'python tqdm regex requests packaging filelock numpy tokenizers'.split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append('dataclasses') if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append('importlib_metadata') for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f"can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py") def a_ ( __magic_name__ , __magic_name__=None ) -> Dict: """simple docstring""" require_version(deps[pkg] , __UpperCamelCase )
708
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class a_ : def __init__( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any]=99 , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Any=9 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : Tuple=32 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=37 , UpperCAmelCase__ : Union[str, Any]=8 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : str=0.002 , UpperCAmelCase__ : str=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : Union[str, Any]=0 , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=None , ): """simple docstring""" snake_case : Union[str, Any] = parent snake_case : Union[str, Any] = batch_size snake_case : Any = encoder_seq_length snake_case : str = decoder_seq_length # For common tests snake_case : Optional[int] = self.decoder_seq_length snake_case : Optional[Any] = is_training snake_case : List[Any] = use_attention_mask snake_case : Union[str, Any] = use_labels snake_case : Any = vocab_size snake_case : Optional[int] = hidden_size snake_case : List[str] = num_hidden_layers snake_case : Union[str, Any] = num_attention_heads snake_case : Any = d_ff snake_case : Any = relative_attention_num_buckets snake_case : Optional[Any] = dropout_rate snake_case : int = initializer_factor snake_case : Optional[Any] = eos_token_id snake_case : Dict = pad_token_id snake_case : Optional[Any] = decoder_start_token_id snake_case : Union[str, Any] = None snake_case : List[str] = decoder_layers def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return TaConfig.from_pretrained('''google/umt5-base''' ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=None , ): """simple docstring""" if attention_mask is None: snake_case : Union[str, Any] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: snake_case : Any = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: snake_case : List[Any] = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=UpperCAmelCase__ ) if decoder_head_mask is None: snake_case : Tuple = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=UpperCAmelCase__ ) if cross_attn_head_mask is None: snake_case : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=UpperCAmelCase__ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input snake_case : List[str] = input_ids.clamp(self.pad_token_id + 1 ) snake_case : List[str] = decoder_input_ids.clamp(self.pad_token_id + 1 ) snake_case : str = self.get_config() snake_case : Tuple = config.num_attention_heads snake_case : List[Any] = self.prepare_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, input_dict def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : List[str] = self.prepare_config_and_inputs() return config, inputs_dict def lowerCAmelCase( self : Dict ): """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def lowerCAmelCase( self : Tuple ): """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , ): """simple docstring""" snake_case : str = UMTaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : str = model( input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , ) snake_case : int = model(input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ ) snake_case : int = result.last_hidden_state snake_case : Dict = result.past_key_values snake_case : Dict = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(UpperCAmelCase__ ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , ): """simple docstring""" snake_case : int = UMTaModel(config=UpperCAmelCase__ ).get_decoder().to(UpperCAmelCase__ ).eval() # first forward pass snake_case : List[Any] = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) snake_case : List[Any] = model(UpperCAmelCase__ ) snake_case : Any = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) self.parent.assertTrue(len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) ) self.parent.assertTrue(len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) + 1 ) snake_case , snake_case : List[str] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids snake_case : Any = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and snake_case : Union[str, Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case : Any = model(UpperCAmelCase__ )['''last_hidden_state'''] snake_case : Optional[Any] = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )['''last_hidden_state'''] # select random slice snake_case : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() snake_case : Tuple = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , ): """simple docstring""" snake_case : int = UMTaModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).half().eval() snake_case : str = model(**UpperCAmelCase__ )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(UpperCAmelCase__ ).any().item() ) @require_torch class a_ ( a , a , a , unittest.TestCase ): A__ : str = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) A__ : str = (UMTaForConditionalGeneration,) if is_torch_available() else () A__ : Any = ( { 'conversational': UMTaForConditionalGeneration, 'feature-extraction': UMTaModel, 'summarization': UMTaForConditionalGeneration, 'text2text-generation': UMTaForConditionalGeneration, 'translation': UMTaForConditionalGeneration, 'question-answering': UMTaForQuestionAnswering, } if is_torch_available() else {} ) A__ : Dict = True A__ : List[str] = False A__ : Optional[int] = False A__ : Optional[int] = True A__ : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests A__ : int = [0.8, 0.9] def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Union[str, Any] = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Tuple = self.model_tester.prepare_config_and_inputs() snake_case : Optional[Any] = UMTaModel(config_and_inputs[0] ).to(UpperCAmelCase__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( UpperCAmelCase__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=UpperCAmelCase__ , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : Optional[int] = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() snake_case : int = config_and_inputs[0] snake_case : Union[str, Any] = UMTaForConditionalGeneration(UpperCAmelCase__ ).eval() model.to(UpperCAmelCase__ ) snake_case : str = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=UpperCAmelCase__ ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ), } for attn_name, (name, mask) in zip(UpperCAmelCase__ , head_masking.items() ): snake_case : int = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": snake_case : List[str] = torch.ones( config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ) snake_case : Union[str, Any] = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=UpperCAmelCase__ , return_dict_in_generate=UpperCAmelCase__ , **UpperCAmelCase__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step snake_case : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def lowerCAmelCase( self : Any ): """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class a_ ( unittest.TestCase ): @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[Any] = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=UpperCAmelCase__ ).to(UpperCAmelCase__ ) snake_case : int = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=UpperCAmelCase__ , legacy=UpperCAmelCase__ ) snake_case : List[str] = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] snake_case : Dict = tokenizer(UpperCAmelCase__ , return_tensors='''pt''' , padding=UpperCAmelCase__ ).input_ids # fmt: off snake_case : Optional[Any] = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : List[Any] = model.generate(input_ids.to(UpperCAmelCase__ ) ) snake_case : int = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] snake_case : Tuple = tokenizer.batch_decode(UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
84
0
import math from datetime import datetime, timedelta def a_ ( __magic_name__ ) -> int: """simple docstring""" snake_case : List[str] = year % 19 snake_case : Tuple = year % 4 snake_case : Any = year % 7 snake_case : List[Any] = math.floor(year / 100 ) snake_case : Any = math.floor((13 + 8 * leap_day_inhibits) / 25 ) snake_case : Tuple = leap_day_inhibits / 4 snake_case : List[str] = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 snake_case : Dict = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 snake_case : int = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon snake_case : Dict = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(__magic_name__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(__magic_name__ , 4 , 18 ) else: return datetime(__magic_name__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_994, 2_000, 2_010, 2_021, 2_023): _a : int = """will be""" if year > datetime.now().year else """was""" print(f"Easter in {year} {tense} {gauss_easter(year)}")
709
import torch from diffusers import DiffusionPipeline class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): """simple docstring""" super().__init__() self.register_modules(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) def __call__( self : Optional[int] ): """simple docstring""" snake_case : Any = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) snake_case : Dict = 1 snake_case : Optional[Any] = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample snake_case : List[Any] = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ).prev_sample snake_case : List[Any] = scheduler_output - scheduler_output + torch.ones_like(UpperCAmelCase__ ) return result
84
0
def a_ ( __magic_name__ ) -> List[str]: """simple docstring""" snake_case : List[Any] = int(snake_case_ ) if n_element < 1: snake_case : Any = ValueError('''a should be a positive number''' ) raise my_error snake_case : int = [1] snake_case : Optional[Any] = (0, 0, 0) snake_case : Optional[Any] = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _a : Tuple = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') _a : Optional[Any] = hamming(int(n)) print('-----------------------------------------------------') print(f"The list with nth numbers is: {hamming_numbers}") print('-----------------------------------------------------')
710
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a_ ( a ): A__ : List[str] = ['image_processor', 'tokenizer'] A__ : Any = 'CLIPImageProcessor' A__ : Optional[int] = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : Union[str, Any] , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , UpperCAmelCase__ , ) snake_case : List[Any] = kwargs.pop('''feature_extractor''' ) snake_case : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(UpperCAmelCase__ , UpperCAmelCase__ ) def __call__( self : Any , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: snake_case : int = self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if images is not None: snake_case : Dict = self.image_processor(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if text is not None and images is not None: snake_case : Tuple = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase__ ) , tensor_type=UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : int ): """simple docstring""" return self.tokenizer.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : str ): """simple docstring""" return self.tokenizer.decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : int = self.tokenizer.model_input_names snake_case : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , UpperCAmelCase__ , ) return self.image_processor_class @property def lowerCAmelCase( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , UpperCAmelCase__ , ) return self.image_processor
84
0
'''simple docstring''' import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def a_ ( __magic_name__ ) -> int: """simple docstring""" if ( (cp >= 0X4_e_0_0 and cp <= 0X9_f_f_f) or (cp >= 0X3_4_0_0 and cp <= 0X4_d_b_f) # or (cp >= 0X2_0_0_0_0 and cp <= 0X2_a_6_d_f) # or (cp >= 0X2_a_7_0_0 and cp <= 0X2_b_7_3_f) # or (cp >= 0X2_b_7_4_0 and cp <= 0X2_b_8_1_f) # or (cp >= 0X2_b_8_2_0 and cp <= 0X2_c_e_a_f) # or (cp >= 0Xf_9_0_0 and cp <= 0Xf_a_f_f) or (cp >= 0X2_f_8_0_0 and cp <= 0X2_f_a_1_f) # ): # return True return False def a_ ( __magic_name__ ) -> Union[str, Any]: """simple docstring""" for char in word: snake_case : int = ord(__UpperCamelCase ) if not _is_chinese_char(__UpperCamelCase ): return 0 return 1 def a_ ( __magic_name__ ) -> Optional[int]: """simple docstring""" snake_case : Tuple = set() for token in tokens: snake_case : Any = len(__UpperCamelCase ) > 1 and is_chinese(__UpperCamelCase ) if chinese_word: word_set.add(__UpperCamelCase ) snake_case : Any = list(__UpperCamelCase ) return word_list def a_ ( __magic_name__ , __magic_name__ ) -> Union[str, Any]: """simple docstring""" if not chinese_word_set: return bert_tokens snake_case : Any = max([len(__UpperCamelCase ) for w in chinese_word_set] ) snake_case : Dict = bert_tokens snake_case : Optional[Any] = 0, len(__UpperCamelCase ) while start < end: snake_case : Dict = True if is_chinese(bert_word[start] ): snake_case : Tuple = min(end - start , __UpperCamelCase ) for i in range(__UpperCamelCase , 1 , -1 ): snake_case : List[str] = ''''''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): snake_case : Dict = '''##''' + bert_word[j] snake_case : str = start + i snake_case : Tuple = False break if single_word: start += 1 return bert_word def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> Tuple: """simple docstring""" snake_case : Optional[Any] = [] for i in range(0 , len(__UpperCamelCase ) , 100 ): snake_case : str = ltp_tokenizer.pipeline(lines[i : i + 100] , tasks=['''cws'''] ).cws snake_case : List[Any] = [get_chinese_word(__UpperCamelCase ) for r in res] ltp_res.extend(__UpperCamelCase ) assert len(__UpperCamelCase ) == len(__UpperCamelCase ) snake_case : str = [] for i in range(0 , len(__UpperCamelCase ) , 100 ): snake_case : Dict = bert_tokenizer(lines[i : i + 100] , add_special_tokens=__UpperCamelCase , truncation=__UpperCamelCase , max_length=512 ) bert_res.extend(res['''input_ids'''] ) assert len(__UpperCamelCase ) == len(__UpperCamelCase ) snake_case : Tuple = [] for input_ids, chinese_word in zip(__UpperCamelCase , __UpperCamelCase ): snake_case : Optional[int] = [] for id in input_ids: snake_case : List[str] = bert_tokenizer._convert_id_to_token(__UpperCamelCase ) input_tokens.append(__UpperCamelCase ) snake_case : List[Any] = add_sub_symbol(__UpperCamelCase , __UpperCamelCase ) snake_case : Optional[int] = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(__UpperCamelCase ): if token[:2] == "##": snake_case : List[str] = token[2:] # save chinese tokens' pos if len(__UpperCamelCase ) == 1 and _is_chinese_char(ord(__UpperCamelCase ) ): ref_id.append(__UpperCamelCase ) ref_ids.append(__UpperCamelCase ) assert len(__UpperCamelCase ) == len(__UpperCamelCase ) return ref_ids def a_ ( __magic_name__ ) -> str: """simple docstring""" with open(args.file_name , '''r''' , encoding='''utf-8''' ) as f: snake_case : Any = f.readlines() snake_case : List[str] = [line.strip() for line in data if len(__UpperCamelCase ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' snake_case : List[Any] = LTP(args.ltp ) # faster in GPU device snake_case : List[Any] = BertTokenizer.from_pretrained(args.bert ) snake_case : Optional[Any] = prepare_ref(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) with open(args.save_path , '''w''' , encoding='''utf-8''' ) as f: snake_case : Optional[Any] = [json.dumps(__UpperCamelCase ) + '''\n''' for ref in ref_ids] f.writelines(__UpperCamelCase ) if __name__ == "__main__": _a : Tuple = argparse.ArgumentParser(description='prepare_chinese_ref') parser.add_argument( '--file_name', required=False, type=str, default='./resources/chinese-demo.txt', help='file need process, same as training data in lm', ) parser.add_argument( '--ltp', required=False, type=str, default='./resources/ltp', help='resources for LTP tokenizer, usually a path', ) parser.add_argument( '--bert', required=False, type=str, default='./resources/robert', help='resources for Bert tokenizer', ) parser.add_argument( '--save_path', required=False, type=str, default='./resources/ref.txt', help='path to save res', ) _a : int = parser.parse_args() main(args)
711
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _a : Optional[Any] = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' _a : str = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' _a : List[Any] = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : Any ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/krishnap25/mauve''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/krishnap25/mauve'''] , reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] , ) def lowerCAmelCase( self : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : List[str]="auto" , UpperCAmelCase__ : Tuple=-1 , UpperCAmelCase__ : Optional[int]=0.9 , UpperCAmelCase__ : List[Any]=5 , UpperCAmelCase__ : List[Any]=500 , UpperCAmelCase__ : Union[str, Any]="gpt2-large" , UpperCAmelCase__ : Optional[Any]=-1 , UpperCAmelCase__ : int=1_024 , UpperCAmelCase__ : List[Any]=25 , UpperCAmelCase__ : Union[str, Any]=5 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[Any]=25 , ): """simple docstring""" snake_case : List[str] = compute_mauve( p_text=UpperCAmelCase__ , q_text=UpperCAmelCase__ , p_features=UpperCAmelCase__ , q_features=UpperCAmelCase__ , p_tokens=UpperCAmelCase__ , q_tokens=UpperCAmelCase__ , num_buckets=UpperCAmelCase__ , pca_max_data=UpperCAmelCase__ , kmeans_explained_var=UpperCAmelCase__ , kmeans_num_redo=UpperCAmelCase__ , kmeans_max_iter=UpperCAmelCase__ , featurize_model_name=UpperCAmelCase__ , device_id=UpperCAmelCase__ , max_text_length=UpperCAmelCase__ , divergence_curve_discretization_size=UpperCAmelCase__ , mauve_scaling_factor=UpperCAmelCase__ , verbose=UpperCAmelCase__ , seed=UpperCAmelCase__ , ) return out
84
0
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand _a : Optional[int] = ( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) _a : Any = ( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) _a : Dict = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) _a : int = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) _a : List[Any] = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 14]), ('2H 5D 3C AS 5S', False, [14, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [14, 13, 12, 11, 10]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) _a : Optional[Any] = ( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) _a : List[str] = ( ('JH AH TH KH QH', 23), ('JH 9H TH KH QH', 22), ('JC KH JS JD JH', 21), ('KH KC 3S 3H 3D', 20), ('8C 9C 5C 3C TC', 19), ('JS QS 9H TS KH', 18), ('7C 7S KH 2H 7H', 17), ('3C KH 5D 5S KH', 16), ('QH 8H KD JH 8S', 15), ('2D 6D 9D TH 7D', 14), ) def a_ ( ) -> Optional[int]: """simple docstring""" snake_case , snake_case : int = randrange(len(lowerCamelCase_ ) ), randrange(len(lowerCamelCase_ ) ) snake_case : int = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] snake_case , snake_case : List[str] = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def a_ ( __magic_name__ = 100 ) -> List[Any]: """simple docstring""" return (generate_random_hand() for _ in range(lowerCamelCase_ )) @pytest.mark.parametrize('''hand, expected''' , lowerCamelCase_ ) def a_ ( __magic_name__ , __magic_name__ ) -> Tuple: """simple docstring""" assert PokerHand(lowerCamelCase_ )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , lowerCamelCase_ ) def a_ ( __magic_name__ , __magic_name__ ) -> Optional[int]: """simple docstring""" assert PokerHand(lowerCamelCase_ )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , lowerCamelCase_ ) def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> Optional[Any]: """simple docstring""" snake_case : Optional[int] = PokerHand(lowerCamelCase_ ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , lowerCamelCase_ ) def a_ ( __magic_name__ , __magic_name__ ) -> Optional[int]: """simple docstring""" assert PokerHand(lowerCamelCase_ )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , lowerCamelCase_ ) def a_ ( __magic_name__ , __magic_name__ ) -> Dict: """simple docstring""" assert PokerHand(lowerCamelCase_ )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , lowerCamelCase_ ) def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: """simple docstring""" assert PokerHand(lowerCamelCase_ ).compare_with(PokerHand(lowerCamelCase_ ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> Optional[int]: """simple docstring""" assert PokerHand(lowerCamelCase_ ).compare_with(PokerHand(lowerCamelCase_ ) ) == expected def a_ ( ) -> Union[str, Any]: """simple docstring""" snake_case : Union[str, Any] = [PokerHand(lowerCamelCase_ ) for hand in SORTED_HANDS] snake_case : List[Any] = poker_hands.copy() shuffle(lowerCamelCase_ ) snake_case : int = chain(sorted(lowerCamelCase_ ) ) for index, hand in enumerate(lowerCamelCase_ ): assert hand == poker_hands[index] def a_ ( ) -> Optional[Any]: """simple docstring""" snake_case : Optional[int] = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=lowerCamelCase_ ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def a_ ( ) -> List[Any]: """simple docstring""" snake_case : int = PokerHand('''2C 4S AS 3D 5C''' ) snake_case : Optional[Any] = True snake_case : int = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def a_ ( ) -> Any: """simple docstring""" snake_case : int = 0 snake_case : Optional[Any] = os.path.abspath(os.path.dirname(lowerCamelCase_ ) ) snake_case : int = os.path.join(lowerCamelCase_ , '''poker_hands.txt''' ) with open(lowerCamelCase_ ) as file_hand: for line in file_hand: snake_case : Tuple = line[:14].strip() snake_case : Any = line[15:].strip() snake_case , snake_case : Optional[Any] = PokerHand(lowerCamelCase_ ), PokerHand(lowerCamelCase_ ) snake_case : Any = player.compare_with(lowerCamelCase_ ) if output == "Win": answer += 1 assert answer == 376
712
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" if "cls_token" in name: snake_case : Tuple = name.replace('''cls_token''' , '''vit.embeddings.cls_token''' ) if "mask_token" in name: snake_case : Optional[int] = name.replace('''mask_token''' , '''decoder.mask_token''' ) if "decoder_pos_embed" in name: snake_case : List[str] = name.replace('''decoder_pos_embed''' , '''decoder.decoder_pos_embed''' ) if "pos_embed" in name and "decoder" not in name: snake_case : List[str] = name.replace('''pos_embed''' , '''vit.embeddings.position_embeddings''' ) if "patch_embed.proj" in name: snake_case : List[Any] = name.replace('''patch_embed.proj''' , '''vit.embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: snake_case : int = name.replace('''patch_embed.norm''' , '''vit.embeddings.norm''' ) if "decoder_blocks" in name: snake_case : int = name.replace('''decoder_blocks''' , '''decoder.decoder_layers''' ) if "blocks" in name: snake_case : Optional[Any] = name.replace('''blocks''' , '''vit.encoder.layer''' ) if "attn.proj" in name: snake_case : str = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: snake_case : Any = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: snake_case : List[str] = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: snake_case : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: snake_case : Tuple = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: snake_case : Tuple = name.replace('''mlp.fc2''' , '''output.dense''' ) if "decoder_embed" in name: snake_case : Dict = name.replace('''decoder_embed''' , '''decoder.decoder_embed''' ) if "decoder_norm" in name: snake_case : Dict = name.replace('''decoder_norm''' , '''decoder.decoder_norm''' ) if "decoder_pred" in name: snake_case : Dict = name.replace('''decoder_pred''' , '''decoder.decoder_pred''' ) if "norm.weight" in name and "decoder" not in name: snake_case : Optional[int] = name.replace('''norm.weight''' , '''vit.layernorm.weight''' ) if "norm.bias" in name and "decoder" not in name: snake_case : List[str] = name.replace('''norm.bias''' , '''vit.layernorm.bias''' ) return name def a_ ( __magic_name__ , __magic_name__ ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): snake_case : Union[str, Any] = orig_state_dict.pop(__magic_name__ ) if "qkv" in key: snake_case : Optional[int] = key.split('''.''' ) snake_case : int = int(key_split[1] ) if "decoder_blocks" in key: snake_case : List[str] = config.decoder_hidden_size snake_case : List[Any] = '''decoder.decoder_layers.''' if "weight" in key: snake_case : str = val[:dim, :] snake_case : Optional[Any] = val[dim : dim * 2, :] snake_case : Any = val[-dim:, :] elif "bias" in key: snake_case : Optional[Any] = val[:dim] snake_case : List[Any] = val[dim : dim * 2] snake_case : List[Any] = val[-dim:] else: snake_case : Optional[int] = config.hidden_size snake_case : Tuple = '''vit.encoder.layer.''' if "weight" in key: snake_case : Optional[Any] = val[:dim, :] snake_case : str = val[dim : dim * 2, :] snake_case : Union[str, Any] = val[-dim:, :] elif "bias" in key: snake_case : Tuple = val[:dim] snake_case : int = val[dim : dim * 2] snake_case : Optional[Any] = val[-dim:] else: snake_case : Optional[Any] = val return orig_state_dict def a_ ( __magic_name__ , __magic_name__ ) -> Any: """simple docstring""" snake_case : List[str] = ViTMAEConfig() if "large" in checkpoint_url: snake_case : str = 1_024 snake_case : Tuple = 4_096 snake_case : Optional[Any] = 24 snake_case : List[Any] = 16 elif "huge" in checkpoint_url: snake_case : Tuple = 14 snake_case : int = 1_280 snake_case : Dict = 5_120 snake_case : Tuple = 32 snake_case : Optional[Any] = 16 snake_case : Optional[Any] = ViTMAEForPreTraining(__magic_name__ ) snake_case : Optional[Any] = torch.hub.load_state_dict_from_url(__magic_name__ , map_location='''cpu''' )['''model'''] snake_case : int = ViTMAEImageProcessor(size=config.image_size ) snake_case : Dict = convert_state_dict(__magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ ) model.eval() snake_case : Tuple = '''https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg''' snake_case : List[Any] = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) snake_case : Dict = ViTMAEImageProcessor(size=config.image_size ) snake_case : str = image_processor(images=__magic_name__ , return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) snake_case : Union[str, Any] = model(**__magic_name__ ) snake_case : Optional[Any] = outputs.logits if "large" in checkpoint_url: snake_case : Any = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] ) elif "huge" in checkpoint_url: snake_case : List[Any] = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] ) else: snake_case : Dict = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , __magic_name__ , atol=1e-4 ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__magic_name__ ) if __name__ == "__main__": _a : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) _a : str = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
84
0
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer _a : List[Any] = logging.get_logger(__name__) _a : str = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _a : int = { "vocab_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _a : Union[str, Any] = { "vocab_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json" ), }, } _a : Union[str, Any] = { "vocab_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json" ), }, } _a : str = { "facebook/dpr-ctx_encoder-single-nq-base": 512, "facebook/dpr-ctx_encoder-multiset-base": 512, } _a : List[str] = { "facebook/dpr-question_encoder-single-nq-base": 512, "facebook/dpr-question_encoder-multiset-base": 512, } _a : List[str] = { "facebook/dpr-reader-single-nq-base": 512, "facebook/dpr-reader-multiset-base": 512, } _a : Optional[Any] = { "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True}, } _a : Optional[int] = { "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True}, "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True}, } _a : List[Any] = { "facebook/dpr-reader-single-nq-base": {"do_lower_case": True}, "facebook/dpr-reader-multiset-base": {"do_lower_case": True}, } class a_ ( _A ): A__ : List[str] = VOCAB_FILES_NAMES A__ : Optional[int] = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP A__ : Dict = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Dict = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION A__ : List[str] = DPRContextEncoderTokenizer class a_ ( _A ): A__ : int = VOCAB_FILES_NAMES A__ : List[Any] = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP A__ : Union[str, Any] = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : List[str] = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION A__ : List[str] = DPRQuestionEncoderTokenizer _a : Tuple = collections.namedtuple( 'DPRSpanPrediction', ['span_score', 'relevance_score', 'doc_id', 'start_index', 'end_index', 'text'] ) _a : Dict = collections.namedtuple('DPRReaderOutput', ['start_logits', 'end_logits', 'relevance_logits']) _a : Any = R"\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer's default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n " @add_start_docstrings(_A ) class a_ : def __call__( self : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] = None , UpperCAmelCase__ : int = None , UpperCAmelCase__ : Tuple = False , UpperCAmelCase__ : Union[str, Any] = False , UpperCAmelCase__ : Optional[Any] = None , UpperCAmelCase__ : Any = None , UpperCAmelCase__ : int = None , **UpperCAmelCase__ : Optional[Any] , ): """simple docstring""" if titles is None and texts is None: return super().__call__( UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , **UpperCAmelCase__ , ) elif titles is None or texts is None: snake_case : Tuple = titles if texts is None else texts return super().__call__( UpperCAmelCase__ , UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , **UpperCAmelCase__ , ) snake_case : List[str] = titles if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else [titles] snake_case : List[Any] = texts if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else [texts] snake_case : Optional[Any] = len(UpperCAmelCase__ ) snake_case : Tuple = questions if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else [questions] * n_passages assert len(UpperCAmelCase__ ) == len( UpperCAmelCase__ ), F"There should be as many titles than texts but got {len(UpperCAmelCase__ )} titles and {len(UpperCAmelCase__ )} texts." snake_case : Dict = super().__call__(UpperCAmelCase__ , UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ )["input_ids"] snake_case : int = super().__call__(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ )["input_ids"] snake_case : Tuple = { "input_ids": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(UpperCAmelCase__ , UpperCAmelCase__ ) ] } if return_attention_mask is not False: snake_case : Dict = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) snake_case : int = attention_mask return self.pad(UpperCAmelCase__ , padding=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors=UpperCAmelCase__ ) def lowerCAmelCase( self : str , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] = 16 , UpperCAmelCase__ : Optional[int] = 64 , UpperCAmelCase__ : Optional[int] = 4 , ): """simple docstring""" snake_case : Dict = reader_input["input_ids"] snake_case : Union[str, Any] = reader_output[:3] snake_case : Dict = len(UpperCAmelCase__ ) snake_case : List[Any] = sorted(range(UpperCAmelCase__ ) , reverse=UpperCAmelCase__ , key=relevance_logits.__getitem__ ) snake_case : List[DPRReaderOutput] = [] for doc_id in sorted_docs: snake_case : Optional[int] = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence snake_case : List[Any] = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: snake_case : List[Any] = sequence_ids.index(self.pad_token_id ) else: snake_case : Tuple = len(UpperCAmelCase__ ) snake_case : str = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=UpperCAmelCase__ , top_spans=UpperCAmelCase__ , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=UpperCAmelCase__ , start_index=UpperCAmelCase__ , end_index=UpperCAmelCase__ , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(UpperCAmelCase__ ) >= num_spans: break return nbest_spans_predictions[:num_spans] def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , ): """simple docstring""" snake_case : Any = [] for start_index, start_score in enumerate(UpperCAmelCase__ ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) snake_case : str = sorted(UpperCAmelCase__ , key=lambda UpperCAmelCase__ : x[1] , reverse=UpperCAmelCase__ ) snake_case : List[str] = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F"Wrong span indices: [{start_index}:{end_index}]" snake_case : str = end_index - start_index + 1 assert length <= max_answer_length, F"Span is too long: {length} > {max_answer_length}" if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(UpperCAmelCase__ ) == top_spans: break return chosen_span_intervals @add_end_docstrings(_A ) class a_ ( _A , _A ): A__ : Optional[int] = VOCAB_FILES_NAMES A__ : str = READER_PRETRAINED_VOCAB_FILES_MAP A__ : Tuple = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : str = READER_PRETRAINED_INIT_CONFIGURATION A__ : Optional[Any] = ['input_ids', 'attention_mask'] A__ : str = DPRReaderTokenizer
713
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _a : Optional[Any] = 16 _a : Union[str, Any] = 32 def a_ ( __magic_name__ , __magic_name__ = 16 ) -> Dict: """simple docstring""" snake_case : Tuple = AutoTokenizer.from_pretrained('''bert-base-cased''' ) snake_case : Any = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__magic_name__ ): # max_length=None => use the model max length (it's actually the default) snake_case : Union[str, Any] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__magic_name__ , max_length=__magic_name__ ) 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( __magic_name__ , batched=__magic_name__ , 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(__magic_name__ ): # On TPU it's best to pad everything to the same length or training will be very slow. snake_case : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": snake_case : Tuple = 16 elif accelerator.mixed_precision != "no": snake_case : Dict = 8 else: snake_case : Union[str, Any] = None return tokenizer.pad( __magic_name__ , padding='''longest''' , max_length=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_tensors='''pt''' , ) # Instantiate dataloaders. snake_case : str = DataLoader( tokenized_datasets['''train'''] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) snake_case : List[str] = DataLoader( tokenized_datasets['''validation'''] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders _a : Optional[int] = mocked_dataloaders # noqa: F811 def a_ ( __magic_name__ , __magic_name__ ) -> Optional[Any]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , __magic_name__ ) == "1": snake_case : Optional[int] = 2 # Initialize accelerator snake_case : 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 : Dict = config['''lr'''] snake_case : Any = int(config['''num_epochs'''] ) snake_case : List[str] = int(config['''seed'''] ) snake_case : List[Any] = int(config['''batch_size'''] ) snake_case : Tuple = evaluate.load('''glue''' , '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=__magic_name__ ) def inner_training_loop(__magic_name__ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(__magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) snake_case : str = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=__magic_name__ ) # 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 : Optional[int] = model.to(accelerator.device ) # Instantiate optimizer snake_case : Optional[int] = AdamW(params=model.parameters() , lr=__magic_name__ ) snake_case , snake_case : List[Any] = get_dataloaders(__magic_name__ , __magic_name__ ) # Instantiate scheduler snake_case : int = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=100 , num_training_steps=(len(__magic_name__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. snake_case , snake_case , snake_case , snake_case , snake_case : Tuple = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # Now we train the model for epoch in range(__magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) snake_case : int = model(**__magic_name__ ) snake_case : Optional[int] = outputs.loss accelerator.backward(__magic_name__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): snake_case : List[str] = model(**__magic_name__ ) snake_case : List[Any] = outputs.logits.argmax(dim=-1 ) snake_case , snake_case : Dict = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) snake_case : Tuple = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , __magic_name__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def a_ ( ) -> Union[str, Any]: """simple docstring""" snake_case : int = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=__magic_name__ , default=__magic_name__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) snake_case : Optional[Any] = parser.parse_args() snake_case : Optional[int] = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
84
0
import numpy as np def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
714
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract _a : Dict = logging.get_logger(__name__) def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> List[Any]: """simple docstring""" return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def a_ ( __magic_name__ , __magic_name__ , __magic_name__ = None ) -> str: """simple docstring""" snake_case : Any = tesseract_config if tesseract_config is not None else '''''' # apply OCR snake_case : str = to_pil_image(__magic_name__ ) snake_case , snake_case : Union[str, Any] = pil_image.size snake_case : List[Any] = pytesseract.image_to_data(__magic_name__ , lang=__magic_name__ , output_type='''dict''' , config=__magic_name__ ) snake_case , snake_case , snake_case , snake_case , snake_case : Optional[Any] = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates snake_case : Union[str, Any] = [idx for idx, word in enumerate(__magic_name__ ) if not word.strip()] snake_case : Union[str, Any] = [word for idx, word in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : Optional[Any] = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format snake_case : List[Any] = [] for x, y, w, h in zip(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): snake_case : Optional[int] = [x, y, x + w, y + h] actual_boxes.append(__magic_name__ ) # finally, normalize the bounding boxes snake_case : List[Any] = [] for box in actual_boxes: normalized_boxes.append(normalize_box(__magic_name__ , __magic_name__ , __magic_name__ ) ) assert len(__magic_name__ ) == len(__magic_name__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class a_ ( a ): A__ : int = ['pixel_values'] def __init__( self : Optional[int] , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = "" , **UpperCAmelCase__ : int , ): """simple docstring""" super().__init__(**UpperCAmelCase__ ) snake_case : Any = size if size is not None else {'''height''': 224, '''width''': 224} snake_case : Tuple = get_size_dict(UpperCAmelCase__ ) snake_case : Dict = do_resize snake_case : str = size snake_case : Optional[int] = resample snake_case : Union[str, Any] = apply_ocr snake_case : int = ocr_lang snake_case : Union[str, Any] = tesseract_config def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Any , ): """simple docstring""" snake_case : Dict = get_size_dict(UpperCAmelCase__ ) 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(UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : List[Any] , ): """simple docstring""" snake_case : Tuple = do_resize if do_resize is not None else self.do_resize snake_case : List[Any] = size if size is not None else self.size snake_case : Tuple = get_size_dict(UpperCAmelCase__ ) snake_case : str = resample if resample is not None else self.resample snake_case : Optional[int] = apply_ocr if apply_ocr is not None else self.apply_ocr snake_case : Any = ocr_lang if ocr_lang is not None else self.ocr_lang snake_case : Optional[int] = tesseract_config if tesseract_config is not None else self.tesseract_config snake_case : List[str] = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) # All transformations expect numpy arrays. snake_case : Any = [to_numpy_array(UpperCAmelCase__ ) for image in images] if apply_ocr: requires_backends(self , '''pytesseract''' ) snake_case : Optional[int] = [] snake_case : Union[str, Any] = [] for image in images: snake_case , snake_case : List[Any] = apply_tesseract(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) words_batch.append(UpperCAmelCase__ ) boxes_batch.append(UpperCAmelCase__ ) if do_resize: snake_case : Any = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) snake_case : int = [flip_channel_order(UpperCAmelCase__ ) for image in images] snake_case : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] snake_case : List[Any] = BatchFeature(data={'''pixel_values''': images} , tensor_type=UpperCAmelCase__ ) if apply_ocr: snake_case : Dict = words_batch snake_case : Dict = boxes_batch return data
84
0
'''simple docstring''' from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
715
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class a_ : def __init__( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any]=13 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : List[Any]=24 , UpperCAmelCase__ : Union[str, Any]=16 , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : int=32 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : Optional[int]=37 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Optional[int]=10 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : Optional[Any]=2 , ): """simple docstring""" snake_case : Tuple = parent snake_case : Dict = batch_size snake_case : str = patch_size snake_case : Union[str, Any] = max_length snake_case : str = num_mel_bins snake_case : Any = is_training snake_case : Union[str, Any] = use_labels snake_case : Tuple = hidden_size snake_case : Dict = num_hidden_layers snake_case : Any = num_attention_heads snake_case : Any = intermediate_size snake_case : List[Any] = hidden_act snake_case : str = hidden_dropout_prob snake_case : str = attention_probs_dropout_prob snake_case : str = type_sequence_label_size snake_case : Optional[int] = initializer_range snake_case : str = scope snake_case : int = frequency_stride snake_case : Union[str, Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) snake_case : Optional[int] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 snake_case : Any = (self.max_length - self.patch_size) // self.time_stride + 1 snake_case : Union[str, Any] = frequency_out_dimension * time_out_dimension snake_case : Union[str, Any] = num_patches + 2 def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Optional[int] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) snake_case : str = None if self.use_labels: snake_case : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case : List[str] = self.get_config() return config, input_values, labels def lowerCAmelCase( self : Any ): """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : str = ASTModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : Any = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : int = self.prepare_config_and_inputs() ( ( snake_case ) , ( snake_case ) , ( snake_case ) , ) : int = config_and_inputs snake_case : Tuple = {'''input_values''': input_values} return config, inputs_dict @require_torch class a_ ( a , a , unittest.TestCase ): A__ : List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) A__ : int = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) A__ : Optional[Any] = False A__ : Dict = False A__ : int = False A__ : Optional[int] = False def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int ): """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[int] = ASTModelTester(self ) snake_case : Optional[int] = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=37 ) def lowerCAmelCase( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def lowerCAmelCase( self : Tuple ): """simple docstring""" pass def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Optional[Any] = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case : Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , nn.Linear ) ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Any = model_class(UpperCAmelCase__ ) snake_case : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case : str = [*signature.parameters.keys()] snake_case : List[str] = ['''input_values'''] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) @slow def lowerCAmelCase( self : List[str] ): """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : List[str] = ASTModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def a_ ( ) -> Dict: """simple docstring""" snake_case : Dict = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) snake_case , snake_case : int = torchaudio.load(__magic_name__ ) return audio, sampling_rate @require_torch @require_torchaudio class a_ ( unittest.TestCase ): @cached_property def lowerCAmelCase( self : Any ): """simple docstring""" return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : List[str] = self.default_feature_extractor snake_case : str = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(UpperCAmelCase__ ) snake_case : str = self.default_feature_extractor snake_case , snake_case : int = prepare_audio() snake_case : Optional[int] = audio.squeeze().numpy() snake_case : Optional[Any] = feature_extractor(UpperCAmelCase__ , sampling_rate=UpperCAmelCase__ , return_tensors='''pt''' ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): snake_case : Union[str, Any] = model(**UpperCAmelCase__ ) # verify the logits snake_case : Any = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) snake_case : str = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1e-4 ) )
84
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _a : Dict = logging.get_logger(__name__) _a : Optional[Any] = { '''tiiuae/falcon-40b''': '''https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json''', '''tiiuae/falcon-7b''': '''https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json''', } class a_ ( __UpperCAmelCase ): A__ : Dict = '''falcon''' A__ : Optional[Any] = ['''past_key_values'''] def __init__( self : Tuple , UpperCAmelCase__ : Optional[Any]=65_024 , UpperCAmelCase__ : int=4_544 , UpperCAmelCase__ : Dict=32 , UpperCAmelCase__ : Optional[Any]=71 , UpperCAmelCase__ : Tuple=1e-5 , UpperCAmelCase__ : Union[str, Any]=0.02 , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=0.0 , UpperCAmelCase__ : List[str]=0.0 , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : Union[str, Any]=11 , UpperCAmelCase__ : List[Any]=11 , **UpperCAmelCase__ : Optional[Any] , ): """simple docstring""" snake_case : Optional[int] = vocab_size # Backward compatibility with n_embed kwarg snake_case : Dict = kwargs.pop('''n_embed''' , __SCREAMING_SNAKE_CASE ) snake_case : str = hidden_size if n_embed is None else n_embed snake_case : Dict = num_hidden_layers snake_case : int = num_attention_heads snake_case : str = layer_norm_epsilon snake_case : Any = initializer_range snake_case : str = use_cache snake_case : List[Any] = hidden_dropout snake_case : int = attention_dropout snake_case : List[str] = bos_token_id snake_case : Any = eos_token_id snake_case : Optional[Any] = num_attention_heads if num_kv_heads is None else num_kv_heads snake_case : Optional[int] = alibi snake_case : Dict = new_decoder_architecture snake_case : Optional[int] = multi_query # Ignored when new_decoder_architecture is True snake_case : Tuple = parallel_attn snake_case : Optional[Any] = bias super().__init__(bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @property def lowerCAmelCase( self : List[str] ): """simple docstring""" return self.hidden_size // self.num_attention_heads @property def lowerCAmelCase( self : Any ): """simple docstring""" return not self.alibi
716
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _a : Union[str, Any] = logging.getLogger(__name__) def a_ ( __magic_name__ , __magic_name__ ) -> Optional[int]: """simple docstring""" return (preds == labels).mean() @dataclass class a_ : A__ : str = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class a_ : A__ : str = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys() )} ) A__ : str = field(metadata={'help': 'Should contain the data files for the task.'} ) A__ : int = field( default=128 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) A__ : bool = field( default=a , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def a_ ( ) -> Dict: """simple docstring""" snake_case : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) snake_case , snake_case , snake_case : Tuple = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"Output directory ({training_args.output_dir}) already exists and is not empty. Use" ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , __magic_name__ ) # Set seed set_seed(training_args.seed ) try: snake_case : int = processors[data_args.task_name]() snake_case : List[str] = processor.get_labels() snake_case : str = len(__magic_name__ ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case : List[Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__magic_name__ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) snake_case : str = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) snake_case : Any = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__magic_name__ , cache_dir=model_args.cache_dir , ) # Get datasets snake_case : Optional[int] = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) snake_case : Any = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(__magic_name__ ) -> Dict: snake_case : str = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(__magic_name__ , p.label_ids )} # Data collator snake_case : Dict = DataCollatorWithPadding(__magic_name__ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer snake_case : List[Any] = Trainer( model=__magic_name__ , args=__magic_name__ , train_dataset=__magic_name__ , eval_dataset=__magic_name__ , compute_metrics=__magic_name__ , data_collator=__magic_name__ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation snake_case : Optional[int] = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) snake_case : Optional[Any] = trainer.evaluate() snake_case : Union[str, Any] = os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_master(): with open(__magic_name__ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''' , __magic_name__ , __magic_name__ ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__magic_name__ ) return results def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" main() if __name__ == "__main__": main()
84
0
import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py _a : List[Any] = '\\n@INPROCEEDINGS{Papineni02bleu:a,\n author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n booktitle = {},\n year = {2002},\n pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n title = "{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation",\n author = "Lin, Chin-Yew and\n Och, Franz Josef",\n booktitle = "{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics",\n month = "aug 23{--}aug 27",\n year = "2004",\n address = "Geneva, Switzerland",\n publisher = "COLING",\n url = "https://www.aclweb.org/anthology/C04-1072",\n pages = "501--507",\n}\n' _a : Tuple = '\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine\'s output and that of a human: "the closer a machine translation is to a professional human translation,\nthe better it is" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation\'s overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU\'s output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n' _a : Optional[Any] = '\nComputes BLEU score of translated segments against one or more references.\nArgs:\n predictions: list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n max_order: Maximum n-gram order to use when computing BLEU score.\n smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n \'bleu\': bleu score,\n \'precisions\': geometric mean of n-gram precisions,\n \'brevity_penalty\': brevity penalty,\n \'length_ratio\': ratio of lengths,\n \'translation_length\': translation_length,\n \'reference_length\': reference_length\nExamples:\n\n >>> predictions = [\n ... ["hello", "there", "general", "kenobi"], # tokenized prediction of the first sample\n ... ["foo", "bar", "foobar"] # tokenized prediction of the second sample\n ... ]\n >>> references = [\n ... [["hello", "there", "general", "kenobi"], ["hello", "there", "!"]], # tokenized references for the first sample (2 references)\n ... [["foo", "bar", "foobar"]] # tokenized references for the second sample (1 reference)\n ... ]\n >>> bleu = datasets.load_metric("bleu")\n >>> results = bleu.compute(predictions=predictions, references=references)\n >>> print(results["bleu"])\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : str ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/BLEU''', '''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''', ] , ) def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : List[str]=False ): """simple docstring""" snake_case : Dict = compute_bleu( reference_corpus=__a , translation_corpus=__a , max_order=__a , smooth=__a ) (snake_case) : Dict = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
717
import re def a_ ( __magic_name__ ) -> bool: """simple docstring""" snake_case : List[str] = re.compile( R'''^(?:0|94|\+94|0{2}94)''' R'''7(0|1|2|4|5|6|7|8)''' R'''(-| |)''' R'''\d{7}$''' ) return bool(re.search(__magic_name__ , __magic_name__ ) ) if __name__ == "__main__": _a : Any = '0094702343221' print(is_sri_lankan_phone_number(phone))
84
0
def a_ ( __magic_name__ = 1_000_000 ) -> Dict: """simple docstring""" snake_case : Dict = 1 snake_case : Optional[int] = 1 snake_case : int = {1: 1} for inputa in range(2 , _lowercase ): snake_case : int = 0 snake_case : Union[str, Any] = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: snake_case : Tuple = (3 * number) + 1 counter += 1 if inputa not in counters: snake_case : Optional[int] = counter if counter > pre_counter: snake_case : Optional[int] = inputa snake_case : Dict = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
718
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class a_ ( unittest.TestCase ): def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : int=18 , UpperCAmelCase__ : Optional[int]=30 , UpperCAmelCase__ : Optional[int]=400 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : int=True , ): """simple docstring""" snake_case : int = size if size is not None else {'''height''': 18, '''width''': 18} snake_case : Optional[Any] = parent snake_case : Any = batch_size snake_case : Any = num_channels snake_case : Union[str, Any] = image_size snake_case : Dict = min_resolution snake_case : Dict = max_resolution snake_case : int = do_resize snake_case : List[str] = size snake_case : List[Any] = apply_ocr def lowerCAmelCase( self : int ): """simple docstring""" return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class a_ ( a , unittest.TestCase ): A__ : List[Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : Optional[Any] = LayoutLMvaImageProcessingTester(self ) @property def lowerCAmelCase( self : Dict ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''apply_ocr''' ) ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def lowerCAmelCase( self : str ): """simple docstring""" pass def lowerCAmelCase( self : Dict ): """simple docstring""" # Initialize image_processing snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image ) # Test not batched input snake_case : Optional[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , UpperCAmelCase__ ) self.assertIsInstance(encoding.boxes , UpperCAmelCase__ ) # Test batched snake_case : Dict = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" # Initialize image_processing snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray ) # 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 : List[Any] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" # Initialize image_processing snake_case : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , 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 : Tuple = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" # with apply_OCR = True snake_case : int = LayoutLMvaImageProcessor() from datasets import load_dataset snake_case : List[Any] = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) snake_case : List[Any] = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) snake_case : Any = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 snake_case : Optional[Any] = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 snake_case : Union[str, Any] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , UpperCAmelCase__ ) self.assertListEqual(encoding.boxes , UpperCAmelCase__ ) # with apply_OCR = False snake_case : str = LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase__ ) snake_case : Optional[Any] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
84
0
import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer _a : List[str] = logging.get_logger(__name__) _a : Union[str, Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : List[Any] = { 'vocab_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } _a : List[Any] = { 'vocab_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } _a : List[str] = { 'vocab_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json' ), }, } _a : Dict = { 'facebook/dpr-ctx_encoder-single-nq-base': 512, 'facebook/dpr-ctx_encoder-multiset-base': 512, } _a : Optional[Any] = { 'facebook/dpr-question_encoder-single-nq-base': 512, 'facebook/dpr-question_encoder-multiset-base': 512, } _a : List[Any] = { 'facebook/dpr-reader-single-nq-base': 512, 'facebook/dpr-reader-multiset-base': 512, } _a : Dict = { 'facebook/dpr-ctx_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-ctx_encoder-multiset-base': {'do_lower_case': True}, } _a : List[str] = { 'facebook/dpr-question_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-question_encoder-multiset-base': {'do_lower_case': True}, } _a : List[Any] = { 'facebook/dpr-reader-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-reader-multiset-base': {'do_lower_case': True}, } class a_ ( __snake_case ): A__ : Tuple = VOCAB_FILES_NAMES A__ : Dict = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP A__ : List[str] = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Union[str, Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION A__ : int = DPRContextEncoderTokenizer class a_ ( __snake_case ): A__ : int = VOCAB_FILES_NAMES A__ : int = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP A__ : Dict = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Any = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION A__ : List[Any] = DPRQuestionEncoderTokenizer _a : List[str] = collections.namedtuple( 'DPRSpanPrediction', ['span_score', 'relevance_score', 'doc_id', 'start_index', 'end_index', 'text'] ) _a : Tuple = collections.namedtuple('DPRReaderOutput', ['start_logits', 'end_logits', 'relevance_logits']) _a : Tuple = R'\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `\'tf\'`: Return TensorFlow `tf.constant` objects.\n - `\'pt\'`: Return PyTorch `torch.Tensor` objects.\n - `\'np\'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer\'s default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n ' @add_start_docstrings(__snake_case ) class a_ : def __call__( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict = None , UpperCAmelCase__ : Dict = None , UpperCAmelCase__ : Tuple = False , UpperCAmelCase__ : Optional[Any] = False , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Any = None , UpperCAmelCase__ : Union[str, Any] = None , **UpperCAmelCase__ : Any , ): """simple docstring""" if titles is None and texts is None: return super().__call__( _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) elif titles is None or texts is None: snake_case : str = titles if texts is None else texts return super().__call__( _lowercase , _lowercase , padding=_lowercase , truncation=_lowercase , max_length=_lowercase , return_tensors=_lowercase , return_attention_mask=_lowercase , **_lowercase , ) snake_case : str = titles if not isinstance(_lowercase , _lowercase ) else [titles] snake_case : Optional[Any] = texts if not isinstance(_lowercase , _lowercase ) else [texts] snake_case : Tuple = len(_lowercase ) snake_case : Dict = questions if not isinstance(_lowercase , _lowercase ) else [questions] * n_passages assert len(_lowercase ) == len( _lowercase ), F"There should be as many titles than texts but got {len(_lowercase )} titles and {len(_lowercase )} texts." snake_case : Optional[Any] = super().__call__(_lowercase , _lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] snake_case : str = super().__call__(_lowercase , add_special_tokens=_lowercase , padding=_lowercase , truncation=_lowercase )["""input_ids"""] snake_case : Union[str, Any] = { """input_ids""": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(_lowercase , _lowercase ) ] } if return_attention_mask is not False: snake_case : Optional[int] = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) snake_case : str = attention_mask return self.pad(_lowercase , padding=_lowercase , max_length=_lowercase , return_tensors=_lowercase ) def lowerCAmelCase( self : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int = 16 , UpperCAmelCase__ : Union[str, Any] = 64 , UpperCAmelCase__ : Union[str, Any] = 4 , ): """simple docstring""" snake_case : Union[str, Any] = reader_input["""input_ids"""] snake_case : Optional[int] = reader_output[:3] snake_case : int = len(_lowercase ) snake_case : Any = sorted(range(_lowercase ) , reverse=_lowercase , key=relevance_logits.__getitem__ ) snake_case : List[DPRReaderOutput] = [] for doc_id in sorted_docs: snake_case : Optional[int] = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence snake_case : Dict = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: snake_case : int = sequence_ids.index(self.pad_token_id ) else: snake_case : Optional[Any] = len(_lowercase ) snake_case : List[Any] = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=_lowercase , top_spans=_lowercase , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=_lowercase , start_index=_lowercase , end_index=_lowercase , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(_lowercase ) >= num_spans: break return nbest_spans_predictions[:num_spans] def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , ): """simple docstring""" snake_case : Tuple = [] for start_index, start_score in enumerate(_lowercase ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) snake_case : str = sorted(_lowercase , key=lambda UpperCAmelCase__ : x[1] , reverse=_lowercase ) snake_case : Union[str, Any] = [] for (start_index, end_index), score in scores: assert start_index <= end_index, F"Wrong span indices: [{start_index}:{end_index}]" snake_case : List[str] = end_index - start_index + 1 assert length <= max_answer_length, F"Span is too long: {length} > {max_answer_length}" if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(_lowercase ) == top_spans: break return chosen_span_intervals @add_end_docstrings(__snake_case ) class a_ ( __snake_case , __snake_case ): A__ : str = VOCAB_FILES_NAMES A__ : List[str] = READER_PRETRAINED_VOCAB_FILES_MAP A__ : Optional[Any] = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : str = READER_PRETRAINED_INIT_CONFIGURATION A__ : List[Any] = ['input_ids', 'attention_mask'] A__ : Any = DPRReaderTokenizer
719
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _a : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name _a : Dict = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def a_ ( __magic_name__ , __magic_name__ , __magic_name__=8 ) -> str: """simple docstring""" snake_case : List[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 snake_case : Tuple = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a_ ( a ): def __init__( self : Optional[int] , UpperCAmelCase__ : UNetaDConditionModel , UpperCAmelCase__ : DDPMScheduler , UpperCAmelCase__ : VQModel , ): """simple docstring""" super().__init__() self.register_modules( unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , movq=UpperCAmelCase__ , ) snake_case : List[Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCAmelCase( self : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any ): """simple docstring""" if latents is None: snake_case : int = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) else: if latents.shape != shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}" ) snake_case : Optional[Any] = latents.to(UpperCAmelCase__ ) snake_case : List[Any] = latents * scheduler.init_noise_sigma return latents def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Optional[int]=0 ): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) snake_case : Union[str, Any] = torch.device(F"cuda:{gpu_id}" ) snake_case : Dict = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Any=0 ): """simple docstring""" if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) snake_case : Optional[int] = torch.device(F"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=UpperCAmelCase__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) snake_case : List[str] = None for cpu_offloaded_model in [self.unet, self.movq]: snake_case , snake_case : Optional[int] = cpu_offload_with_hook(UpperCAmelCase__ , UpperCAmelCase__ , prev_module_hook=UpperCAmelCase__ ) # We'll offload the last model manually. snake_case : Tuple = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(UpperCAmelCase__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase__ : torch.FloatTensor , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 100 , UpperCAmelCase__ : float = 4.0 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[torch.FloatTensor] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" snake_case : Optional[int] = self._execution_device snake_case : Union[str, Any] = guidance_scale > 1.0 if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : Any = torch.cat(UpperCAmelCase__ , dim=0 ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : Union[str, Any] = torch.cat(UpperCAmelCase__ , dim=0 ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : int = torch.cat(UpperCAmelCase__ , dim=0 ) snake_case : List[Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: snake_case : Dict = image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Optional[Any] = negative_image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Tuple = hint.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Optional[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase__ ) snake_case : List[str] = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase__ ) self.scheduler.set_timesteps(UpperCAmelCase__ , device=UpperCAmelCase__ ) snake_case : str = self.scheduler.timesteps snake_case : Optional[Any] = self.movq.config.latent_channels snake_case , snake_case : Optional[Any] = downscale_height_and_width(UpperCAmelCase__ , UpperCAmelCase__ , self.movq_scale_factor ) # create initial latent snake_case : Dict = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(UpperCAmelCase__ ) ): # expand the latents if we are doing classifier free guidance snake_case : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case : Optional[int] = {'''image_embeds''': image_embeds, '''hint''': hint} snake_case : Any = self.unet( sample=UpperCAmelCase__ , timestep=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , added_cond_kwargs=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , )[0] if do_classifier_free_guidance: snake_case , snake_case : Dict = noise_pred.split(latents.shape[1] , dim=1 ) snake_case , snake_case : Any = noise_pred.chunk(2 ) snake_case , snake_case : Dict = variance_pred.chunk(2 ) snake_case : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) snake_case : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): snake_case , snake_case : Tuple = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 snake_case : List[Any] = self.scheduler.step( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , generator=UpperCAmelCase__ , )[0] # post-processing snake_case : List[Any] = self.movq.decode(UpperCAmelCase__ , force_not_quantize=UpperCAmelCase__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: snake_case : Optional[Any] = image * 0.5 + 0.5 snake_case : int = image.clamp(0 , 1 ) snake_case : List[str] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": snake_case : str = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
84
0
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": _a : Dict = input('Enter image url: ').strip() print(f"Downloading image from {url} ...") _a : Any = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image _a : Dict = soup.find('meta', {'property': 'og:image'})['content'] _a : int = requests.get(image_url).content _a : Dict = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, 'wb') as fp: fp.write(image_data) print(f"Done. Image saved to disk as {file_name}.")
720
import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _a : List[Any] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class a_ ( a , unittest.TestCase ): A__ : Dict = ReformerTokenizer A__ : Optional[int] = ReformerTokenizerFast A__ : str = True A__ : Tuple = False A__ : str = True def lowerCAmelCase( self : List[Any] ): """simple docstring""" super().setUp() snake_case : str = ReformerTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : int = '''<s>''' snake_case : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''j''' ) self.assertEqual(len(UpperCAmelCase__ ) , 1_000 ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def lowerCAmelCase( self : Dict ): """simple docstring""" if not self.test_rust_tokenizer: return snake_case : Any = self.get_tokenizer() snake_case : str = self.get_rust_tokenizer() snake_case : Tuple = '''I was born in 92000, and this is falsé.''' snake_case : str = tokenizer.tokenize(UpperCAmelCase__ ) snake_case : int = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : Union[str, Any] = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) snake_case : List[str] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : List[str] = self.get_rust_tokenizer() snake_case : Optional[int] = tokenizer.encode(UpperCAmelCase__ ) snake_case : Optional[Any] = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : List[Any]=15 ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case : str = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) # Simple input snake_case : Union[str, Any] = '''This is a simple input''' snake_case : List[str] = ['''This is a simple input 1''', '''This is a simple input 2'''] snake_case : int = ('''This is a simple input''', '''This is a pair''') snake_case : int = [ ('''This is a simple input 1''', '''This is a simple input 2'''), ('''This is a simple pair 1''', '''This is a simple pair 2'''), ] # Simple input tests self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Simple input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Simple input self.assertRaises( UpperCAmelCase__ , tokenizer_r.batch_encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' , ) # Pair input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Pair input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Pair input self.assertRaises( UpperCAmelCase__ , tokenizer_r.batch_encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' , ) def lowerCAmelCase( self : str ): """simple docstring""" pass def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Union[str, Any] = ReformerTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) snake_case : List[str] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [285, 46, 10, 170, 382] , ) snake_case : int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) snake_case : int = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) snake_case : List[Any] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def lowerCAmelCase( self : Tuple ): """simple docstring""" return ReformerTokenizer.from_pretrained('''google/reformer-crime-and-punishment''' ) @slow def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Any = '''Hello World!''' snake_case : Optional[Any] = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @slow def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[Any] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) snake_case : Dict = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @require_torch @slow def lowerCAmelCase( self : List[Any] ): """simple docstring""" import torch from transformers import ReformerConfig, ReformerModel # Build sequence snake_case : Any = list(self.big_tokenizer.get_vocab().keys() )[:10] snake_case : Union[str, Any] = ''' '''.join(UpperCAmelCase__ ) snake_case : Optional[int] = self.big_tokenizer.encode_plus(UpperCAmelCase__ , return_tensors='''pt''' ) snake_case : List[str] = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors='''pt''' ) snake_case : Optional[Any] = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) snake_case : Tuple = encoded_sequence['''input_ids'''].shape snake_case : List[Any] = ReformerModel(UpperCAmelCase__ ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**UpperCAmelCase__ ) model(**UpperCAmelCase__ ) @slow def lowerCAmelCase( self : Optional[int] ): """simple docstring""" # fmt: off snake_case : Tuple = {'''input_ids''': [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 snake_case : Tuple = [ '''This is a very simple sentence.''', '''The quick brown fox jumps over the lazy dog.''', ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''google/reformer-crime-and-punishment''' , revision='''0e6c3decb8211d49bf881013425dc8b0448b3f5a''' , padding=UpperCAmelCase__ , sequences=UpperCAmelCase__ , )
84
0
class a_ ( __SCREAMING_SNAKE_CASE ): pass class a_ ( __SCREAMING_SNAKE_CASE ): pass class a_ : def __init__( self : Union[str, Any] ): snake_case : Optional[int] = [ [], [], [], ] def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] ): try: if len(self.queues[priority] ) >= 100: raise OverflowError('''Maximum queue size is 100''' ) self.queues[priority].append(_a ) except IndexError: raise ValueError('''Valid priorities are 0, 1, and 2''' ) def lowerCAmelCase( self : Union[str, Any] ): for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('''All queues are empty''' ) def __str__( self : Dict ): return "\n".join(F"Priority {i}: {q}" for i, q in enumerate(self.queues ) ) class a_ : def __init__( self : List[str] ): snake_case : List[str] = [] def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : List[Any] ): if len(self.queue ) == 100: raise OverFlowError('''Maximum queue size is 100''' ) self.queue.append(_a ) def lowerCAmelCase( self : Tuple ): if not self.queue: raise UnderFlowError('''The queue is empty''' ) else: snake_case : Any = min(self.queue ) self.queue.remove(_a ) return data def __str__( self : Optional[Any] ): return str(self.queue ) def a_ ( ) -> Tuple: """simple docstring""" snake_case : Union[str, Any] = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 100 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 128 ) print(lowerCAmelCase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowerCAmelCase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def a_ ( ) -> List[str]: """simple docstring""" snake_case : Optional[Any] = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(100 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(128 ) print(lowerCAmelCase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowerCAmelCase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
721
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" snake_case , snake_case : Any = image.size snake_case , snake_case : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 snake_case : List[str] = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) snake_case : Dict = np.array(__magic_name__ ).astype(np.floataa ) / 255.0 snake_case : Optional[Any] = image[None].transpose(0 , 3 , 1 , 2 ) snake_case : Tuple = torch.from_numpy(__magic_name__ ) return 2.0 * image - 1.0 class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : VQModel , UpperCAmelCase__ : UNetaDModel , UpperCAmelCase__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ): """simple docstring""" super().__init__() self.register_modules(vqvae=UpperCAmelCase__ , unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) @torch.no_grad() def __call__( self : Any , UpperCAmelCase__ : Union[torch.Tensor, PIL.Image.Image] = None , UpperCAmelCase__ : Optional[int] = 1 , UpperCAmelCase__ : Optional[int] = 100 , UpperCAmelCase__ : Optional[float] = 0.0 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" if isinstance(UpperCAmelCase__ , PIL.Image.Image ): snake_case : Optional[int] = 1 elif isinstance(UpperCAmelCase__ , torch.Tensor ): snake_case : Any = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(UpperCAmelCase__ )}" ) if isinstance(UpperCAmelCase__ , PIL.Image.Image ): snake_case : Optional[Any] = preprocess(UpperCAmelCase__ ) snake_case , snake_case : Union[str, Any] = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image snake_case : List[Any] = (batch_size, self.unet.config.in_channels // 2, height, width) snake_case : str = next(self.unet.parameters() ).dtype snake_case : Dict = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=self.device , dtype=UpperCAmelCase__ ) snake_case : Any = image.to(device=self.device , dtype=UpperCAmelCase__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(UpperCAmelCase__ , device=self.device ) snake_case : Optional[Any] = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler snake_case : Union[str, Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] snake_case : Any = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case : Optional[Any] = {} if accepts_eta: snake_case : Dict = eta for t in self.progress_bar(UpperCAmelCase__ ): # concat latents and low resolution image in the channel dimension. snake_case : Optional[int] = torch.cat([latents, image] , dim=1 ) snake_case : str = self.scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) # predict the noise residual snake_case : int = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case : Any = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample # decode the image latents with the VQVAE snake_case : Optional[int] = self.vqvae.decode(UpperCAmelCase__ ).sample snake_case : int = torch.clamp(UpperCAmelCase__ , -1.0 , 1.0 ) snake_case : Dict = image / 2 + 0.5 snake_case : int = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case : Any = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
84
0
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels _a : Any = object() # For specifying empty leaf dict `{}` _a : str = object() def a_ ( __magic_name__ , __magic_name__ ) -> Dict: """simple docstring""" snake_case : List[Any] = tuple((re.compile(x + '''$''' ) for x in qs) ) for i in range(len(_lowerCamelCase ) - len(_lowerCamelCase ) + 1 ): snake_case : Dict = [x.match(_lowerCamelCase ) for x, y in zip(_lowerCamelCase , ks[i:] )] if matches and all(_lowerCamelCase ): return True return False def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" def replace(__magic_name__ , __magic_name__ ): for rule, replacement in rules: if _match(_lowerCamelCase , _lowerCamelCase ): return replacement return val return replace def a_ ( ) -> List[str]: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P('''mp''' , _lowerCamelCase )), (("transformer", "wte", "embedding"), P('''mp''' , _lowerCamelCase )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(_lowerCamelCase , '''mp''' )), (("attention", "out_proj", "kernel"), P('''mp''' , _lowerCamelCase )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(_lowerCamelCase , '''mp''' )), (("mlp", "c_fc", "bias"), P('''mp''' )), (("mlp", "c_proj", "kernel"), P('''mp''' , _lowerCamelCase )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" snake_case : Tuple = _get_partition_rules() snake_case : Union[str, Any] = _replacement_rules(_lowerCamelCase ) snake_case : int = {k: _unmatched for k in flatten_dict(_lowerCamelCase )} snake_case : Any = {k: replace(_lowerCamelCase , _lowerCamelCase ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(_lowerCamelCase ) )
700
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class a_ ( a ): def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = tempfile.mkdtemp() snake_case : Dict = 5 # Realm tok snake_case : str = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] snake_case : Tuple = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) snake_case : Any = os.path.join(UpperCAmelCase__ , 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 : Tuple = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def lowerCAmelCase( self : Any ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Any = RealmConfig(num_block_records=self.num_block_records ) return config def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[int] = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Dict = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=UpperCAmelCase__ , ) return block_records def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Tuple = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[str] = self.get_config() snake_case : Optional[Any] = self.get_dummy_retriever() snake_case : Optional[int] = retriever.tokenizer snake_case : Dict = np.array([0, 3] , dtype='''long''' ) snake_case : Optional[int] = tokenizer(['''Test question'''] ).input_ids snake_case : Union[str, Any] = tokenizer( ['''the fourth'''] , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ).input_ids snake_case : Optional[Any] = config.reader_seq_len snake_case , snake_case , snake_case , snake_case : List[str] = retriever( UpperCAmelCase__ , UpperCAmelCase__ , answer_ids=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors='''np''' ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = self.get_config() snake_case : Optional[int] = self.get_dummy_retriever() snake_case : List[str] = retriever.tokenizer snake_case : Optional[Any] = np.array([0, 3, 5] , dtype='''long''' ) snake_case : Optional[int] = tokenizer(['''Test question'''] ).input_ids snake_case : Any = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ).input_ids snake_case : List[Any] = config.reader_seq_len snake_case , snake_case , snake_case , snake_case : Union[str, Any] = retriever( UpperCAmelCase__ , UpperCAmelCase__ , answer_ids=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors='''np''' ) self.assertEqual([False, True, True] , UpperCAmelCase__ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , UpperCAmelCase__ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : int = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path snake_case : Optional[Any] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: snake_case : Any = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) snake_case : Any = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
84
0
import tempfile import unittest from make_student import create_student_by_copying_alternating_layers from transformers import AutoConfig from transformers.file_utils import cached_property from transformers.testing_utils import require_torch _a : str = """sshleifer/bart-tiny-random""" _a : Dict = """patrickvonplaten/t5-tiny-random""" @require_torch class a_ ( unittest.TestCase ): @cached_property def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return AutoConfig.from_pretrained(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case , *snake_case : Tuple = create_student_by_copying_alternating_layers(UpperCAmelCase__ , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.num_hidden_layers , 1 ) def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case , *snake_case : Any = create_student_by_copying_alternating_layers(UpperCAmelCase__ , tempfile.mkdtemp() , e=1 , d=UpperCAmelCase__ ) def lowerCAmelCase( self : str ): """simple docstring""" snake_case , *snake_case : int = create_student_by_copying_alternating_layers(UpperCAmelCase__ , tempfile.mkdtemp() , e=1 , d=UpperCAmelCase__ ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case , *snake_case : List[Any] = create_student_by_copying_alternating_layers(UpperCAmelCase__ , tempfile.mkdtemp() , e=1 , d=1 ) self.assertEqual(student.config.encoder_layers , 1 ) self.assertEqual(student.config.decoder_layers , 1 ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" with self.assertRaises(UpperCAmelCase__ ): create_student_by_copying_alternating_layers(UpperCAmelCase__ , tempfile.mkdtemp() , e=UpperCAmelCase__ , d=UpperCAmelCase__ )
701
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _a : str = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = ['EncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Dict = ['TFEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = ['FlaxEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys _a : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
84
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _a : str = { 'configuration_informer': [ 'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Dict = [ 'INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'InformerForPrediction', 'InformerModel', 'InformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys _a : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
702
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer _a : str = logging.get_logger(__name__) _a : Optional[int] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Optional[Any] = { 'vocab_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json' ), }, } _a : Union[str, Any] = { 'yjernite/retribert-base-uncased': 512, } _a : Tuple = { 'yjernite/retribert-base-uncased': {'do_lower_case': True}, } class a_ ( a ): A__ : List[str] = VOCAB_FILES_NAMES A__ : Any = PRETRAINED_VOCAB_FILES_MAP A__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Any = PRETRAINED_INIT_CONFIGURATION A__ : Optional[Any] = RetriBertTokenizer A__ : Any = ['input_ids', 'attention_mask'] def __init__( self : Optional[int] , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Dict="[UNK]" , UpperCAmelCase__ : str="[SEP]" , UpperCAmelCase__ : Union[str, Any]="[PAD]" , UpperCAmelCase__ : Dict="[CLS]" , UpperCAmelCase__ : Optional[Any]="[MASK]" , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=None , **UpperCAmelCase__ : Dict , ): """simple docstring""" super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , do_lower_case=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , tokenize_chinese_chars=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ , **UpperCAmelCase__ , ) snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCAmelCase__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCAmelCase__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCAmelCase__ ) != tokenize_chinese_chars ): snake_case : int = getattr(UpperCAmelCase__ , normalizer_state.pop('''type''' ) ) snake_case : List[Any] = do_lower_case snake_case : Union[str, Any] = strip_accents snake_case : int = tokenize_chinese_chars snake_case : int = normalizer_class(**UpperCAmelCase__ ) snake_case : Union[str, Any] = do_lower_case def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=None ): """simple docstring""" snake_case : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ): """simple docstring""" snake_case : List[Any] = [self.sep_token_id] snake_case : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ): """simple docstring""" snake_case : Tuple = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ )
84
0
import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class a_ ( a , unittest.TestCase ): A__ : str = BarthezTokenizer A__ : Any = BarthezTokenizerFast A__ : int = True A__ : Union[str, Any] = True def lowerCAmelCase( self : Any ): """simple docstring""" super().setUp() snake_case : int = BarthezTokenizerFast.from_pretrained('''moussaKam/mbarthez''' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=UpperCAmelCase__ ) snake_case : int = tokenizer def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Any = '<pad>' snake_case : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : str = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''<mask>''' ) self.assertEqual(len(UpperCAmelCase__ ) , 101_122 ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 101_122 ) @require_torch def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : str = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] snake_case : List[str] = [0, 57, 3_018, 70_307, 91, 2] snake_case : Any = self.tokenizer( UpperCAmelCase__ , max_length=len(UpperCAmelCase__ ) , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors='''pt''' ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) snake_case : int = batch.input_ids.tolist()[0] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : str ): """simple docstring""" if not self.test_rust_tokenizer: return snake_case : Optional[int] = self.get_tokenizer() snake_case : List[Any] = self.get_rust_tokenizer() snake_case : int = 'I was born in 92000, and this is falsé.' snake_case : List[str] = tokenizer.tokenize(UpperCAmelCase__ ) snake_case : List[Any] = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : List[Any] = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) snake_case : Union[str, Any] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : Union[str, Any] = self.get_rust_tokenizer() snake_case : Optional[int] = tokenizer.encode(UpperCAmelCase__ ) snake_case : List[Any] = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : int = {'input_ids': [[0, 490, 14_328, 4_507, 354, 47, 43_669, 95, 25, 78_117, 20_215, 19_779, 190, 22, 400, 4, 35_343, 80_310, 603, 86, 24_937, 105, 33_438, 94_762, 196, 39_642, 7, 15, 15_933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10_534, 87, 25, 66, 3_358, 196, 55_289, 8, 82_961, 81, 2_204, 75_203, 7, 15, 763, 12_956, 216, 178, 14_328, 9_595, 1_377, 69_693, 7, 448, 71_021, 196, 18_106, 1_437, 13_974, 108, 9_083, 4, 49_315, 7, 39, 86, 1_326, 2_793, 46_333, 4, 448, 196, 74_588, 7, 49_315, 7, 39, 21, 822, 38_470, 74, 21, 66_723, 62_480, 8, 22_050, 5, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. snake_case : int = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''moussaKam/mbarthez''' , revision='''c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6''' , sequences=UpperCAmelCase__ , )
703
import string import numpy def a_ ( __magic_name__ , __magic_name__ ) -> int: """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , __magic_name__ ) class a_ : A__ : List[Any] = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) A__ : List[str] = numpy.vectorize(lambda a : x % 36 ) A__ : Dict = numpy.vectorize(a ) def __init__( self : List[str] , UpperCAmelCase__ : numpy.ndarray ): """simple docstring""" snake_case : int = self.modulus(UpperCAmelCase__ ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key snake_case : List[str] = encrypt_key.shape[0] def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : str ): """simple docstring""" return self.key_string.index(UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : int ): """simple docstring""" return self.key_string[round(UpperCAmelCase__ )] def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: snake_case : Tuple = det % len(self.key_string ) snake_case : Tuple = len(self.key_string ) if greatest_common_divisor(UpperCAmelCase__ , len(self.key_string ) ) != 1: snake_case : List[Any] = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[int] = [char for char in text.upper() if char in self.key_string] snake_case : Optional[int] = chars[-1] while len(UpperCAmelCase__ ) % self.break_key != 0: chars.append(UpperCAmelCase__ ) return "".join(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[int] = self.process_text(text.upper() ) snake_case : Optional[int] = '''''' for i in range(0 , len(UpperCAmelCase__ ) - self.break_key + 1 , self.break_key ): snake_case : int = text[i : i + self.break_key] snake_case : int = [self.replace_letters(UpperCAmelCase__ ) for char in batch] snake_case : Tuple = numpy.array([vec] ).T snake_case : Optional[Any] = self.modulus(self.encrypt_key.dot(UpperCAmelCase__ ) ).T.tolist()[ 0 ] snake_case : Dict = ''''''.join( self.replace_digits(UpperCAmelCase__ ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Optional[int] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: snake_case : int = det % len(self.key_string ) snake_case : Dict = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: snake_case : Any = i break snake_case : Any = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(UpperCAmelCase__ ) ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Any = self.make_decrypt_key() snake_case : Optional[Any] = self.process_text(text.upper() ) snake_case : int = '''''' for i in range(0 , len(UpperCAmelCase__ ) - self.break_key + 1 , self.break_key ): snake_case : Any = text[i : i + self.break_key] snake_case : int = [self.replace_letters(UpperCAmelCase__ ) for char in batch] snake_case : List[str] = numpy.array([vec] ).T snake_case : Optional[Any] = self.modulus(decrypt_key.dot(UpperCAmelCase__ ) ).T.tolist()[0] snake_case : int = ''''''.join( self.replace_digits(UpperCAmelCase__ ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def a_ ( ) -> None: """simple docstring""" snake_case : Any = int(input('''Enter the order of the encryption key: ''' ) ) snake_case : List[Any] = [] print('''Enter each row of the encryption key with space separated integers''' ) for _ in range(__magic_name__ ): snake_case : Optional[Any] = [int(__magic_name__ ) for x in input().split()] hill_matrix.append(__magic_name__ ) snake_case : List[str] = HillCipher(numpy.array(__magic_name__ ) ) print('''Would you like to encrypt or decrypt some text? (1 or 2)''' ) snake_case : int = input('''\n1. Encrypt\n2. Decrypt\n''' ) if option == "1": snake_case : List[Any] = input('''What text would you like to encrypt?: ''' ) print('''Your encrypted text is:''' ) print(hc.encrypt(__magic_name__ ) ) elif option == "2": snake_case : int = input('''What text would you like to decrypt?: ''' ) print('''Your decrypted text is:''' ) print(hc.decrypt(__magic_name__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
84
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu _a : List[Any] = [ 'EAGER', 'AOT_EAGER', 'INDUCTOR', 'NVFUSER', 'AOT_NVFUSER', 'AOT_CUDAGRAPHS', 'OFI', 'FX2TRT', 'ONNXRT', 'IPEX', ] def a_ ( __magic_name__ , __magic_name__=None , __magic_name__=None , __magic_name__=None ) -> Union[str, Any]: """simple docstring""" snake_case : Tuple = True while ask_again: snake_case : Union[str, Any] = input(__lowercase ) try: if default is not None and len(__lowercase ) == 0: return default return convert_value(__lowercase ) if convert_value is not None else result except Exception: if error_message is not None: print(__lowercase ) def a_ ( __magic_name__ , __magic_name__=[] , __magic_name__=None , __magic_name__=0 ) -> Dict: """simple docstring""" snake_case : List[Any] = BulletMenu(__lowercase , __lowercase ) snake_case : Union[str, Any] = menu.run(default_choice=__lowercase ) return convert_value(__lowercase ) if convert_value is not None else result def a_ ( __magic_name__ ) -> Dict: """simple docstring""" snake_case : Dict = int(__lowercase ) return ComputeEnvironment(['''LOCAL_MACHINE''', '''AMAZON_SAGEMAKER'''][value] ) def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" snake_case : int = int(__lowercase ) return DistributedType(['''NO''', '''MULTI_CPU''', '''MULTI_XPU''', '''MULTI_GPU''', '''MULTI_NPU''', '''TPU'''][value] ) def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" snake_case : Any = int(__lowercase ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def a_ ( __magic_name__ ) -> int: """simple docstring""" snake_case : Tuple = int(__lowercase ) return PrecisionType(['''no''', '''fp16''', '''bf16''', '''fp8'''][value] ) def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" snake_case : Union[str, Any] = int(__lowercase ) return SageMakerDistributedType(['''NO''', '''DATA_PARALLEL''', '''MODEL_PARALLEL'''][value] ) def a_ ( __magic_name__ ) -> Optional[int]: """simple docstring""" return {"yes": True, "no": False}[value.lower()] class a_ ( argparse.RawDescriptionHelpFormatter ): def lowerCAmelCase( self : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple ): """simple docstring""" snake_case : Optional[Any] = super()._format_usage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : Union[str, Any] = usage.replace('''<command> [<args>] ''' , '''''' ) return usage
704
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class a_ ( a ): A__ : List[Any] = 'Salesforce/blip-image-captioning-base' A__ : Dict = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) A__ : str = 'image_captioner' A__ : Dict = AutoModelForVisionaSeq A__ : Optional[Any] = ['image'] A__ : List[str] = ['text'] def __init__( self : List[str] , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : "Image" ): """simple docstring""" return self.pre_processor(images=UpperCAmelCase__ , return_tensors='''pt''' ) def lowerCAmelCase( self : Any , UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" return self.model.generate(**UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : List[Any] ): """simple docstring""" return self.pre_processor.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ )[0].strip()
84
0
'''simple docstring''' from __future__ import annotations import math def a_ ( __magic_name__ ) -> Union[str, Any]: """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(__snake_case ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def a_ ( __magic_name__ ) -> Optional[Any]: """simple docstring""" snake_case : Union[str, Any] = str(__snake_case ) snake_case : str = [n] for i in range(1 , len(__snake_case ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def a_ ( __magic_name__ ) -> Optional[int]: """simple docstring""" if len(str(__snake_case ) ) > 3: if not is_prime(int(str(__snake_case )[-3:] ) ) or not is_prime(int(str(__snake_case )[:3] ) ): return False return True def a_ ( __magic_name__ = 11 ) -> int: """simple docstring""" snake_case : List[str] = [] snake_case : Tuple = 13 while len(__snake_case ) != count: if validate(__snake_case ): snake_case : Any = list_truncated_nums(__snake_case ) if all(is_prime(__snake_case ) for i in list_nums ): list_truncated_primes.append(__snake_case ) num += 2 return list_truncated_primes def a_ ( ) -> List[str]: """simple docstring""" return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
705
def a_ ( __magic_name__ ) -> bool: """simple docstring""" if p < 2: raise ValueError('''p should not be less than 2!''' ) elif p == 2: return True snake_case : int = 4 snake_case : Optional[Any] = (1 << p) - 1 for _ in range(p - 2 ): snake_case : Optional[Any] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
84
0
from ...processing_utils import ProcessorMixin class a_ ( __a ): A__ : Tuple = '''SpeechT5FeatureExtractor''' A__ : List[Any] = '''SpeechT5Tokenizer''' def __init__( self : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ): """simple docstring""" super().__init__(snake_case__ , snake_case__ ) def __call__( self : str , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : int ): """simple docstring""" snake_case : str = kwargs.pop('''audio''' , snake_case__ ) snake_case : Dict = kwargs.pop('''text''' , snake_case__ ) snake_case : List[Any] = kwargs.pop('''text_target''' , snake_case__ ) snake_case : Union[str, Any] = kwargs.pop('''audio_target''' , snake_case__ ) snake_case : int = kwargs.pop('''sampling_rate''' , snake_case__ ) if audio is not None and text is not None: raise ValueError( '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?''' ) if audio_target is not None and text_target is not None: raise ValueError( '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?''' ) if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.''' ) if audio is not None: snake_case : Union[str, Any] = self.feature_extractor(snake_case__ , *snake_case__ , sampling_rate=snake_case__ , **snake_case__ ) elif text is not None: snake_case : Optional[int] = self.tokenizer(snake_case__ , **snake_case__ ) else: snake_case : List[str] = None if audio_target is not None: snake_case : Dict = self.feature_extractor(audio_target=snake_case__ , *snake_case__ , sampling_rate=snake_case__ , **snake_case__ ) snake_case : Dict = targets['''input_values'''] elif text_target is not None: snake_case : Optional[Any] = self.tokenizer(snake_case__ , **snake_case__ ) snake_case : List[Any] = targets['''input_ids'''] else: snake_case : Optional[int] = None if inputs is None: return targets if targets is not None: snake_case : Optional[Any] = labels snake_case : List[Any] = targets.get('''attention_mask''' ) if decoder_attention_mask is not None: snake_case : int = decoder_attention_mask return inputs def lowerCAmelCase( self : Any , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Dict = kwargs.pop('''input_values''' , snake_case__ ) snake_case : Union[str, Any] = kwargs.pop('''input_ids''' , snake_case__ ) snake_case : List[str] = kwargs.pop('''labels''' , snake_case__ ) if input_values is not None and input_ids is not None: raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.''' ) if input_values is None and input_ids is None and labels is None: raise ValueError( '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.''' ) if input_values is not None: snake_case : List[str] = self.feature_extractor.pad(snake_case__ , *snake_case__ , **snake_case__ ) elif input_ids is not None: snake_case : Union[str, Any] = self.tokenizer.pad(snake_case__ , **snake_case__ ) else: snake_case : Any = None if labels is not None: if "input_ids" in labels or (isinstance(snake_case__ , snake_case__ ) and "input_ids" in labels[0]): snake_case : Tuple = self.tokenizer.pad(snake_case__ , **snake_case__ ) snake_case : Optional[int] = targets['''input_ids'''] else: snake_case : Union[str, Any] = self.feature_extractor.feature_size snake_case : Dict = self.feature_extractor.num_mel_bins snake_case : List[Any] = self.feature_extractor.pad(snake_case__ , *snake_case__ , **snake_case__ ) snake_case : str = feature_size_hack snake_case : Dict = targets['''input_values'''] else: snake_case : Optional[int] = None if inputs is None: return targets if targets is not None: snake_case : Dict = labels snake_case : List[Any] = targets.get('''attention_mask''' ) if decoder_attention_mask is not None: snake_case : Optional[Any] = decoder_attention_mask return inputs def lowerCAmelCase( self : Optional[int] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Tuple ): """simple docstring""" return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ ) def lowerCAmelCase( self : Tuple , *UpperCAmelCase__ : str , **UpperCAmelCase__ : Optional[int] ): """simple docstring""" return self.tokenizer.decode(*snake_case__ , **snake_case__ )
706
from sklearn.metrics import fa_score import datasets _a : List[str] = '\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n' _a : Dict = '\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {\'f1\': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results[\'f1\'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results[\'f1\'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")\n >>> print(round(results[\'f1\'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {\'f1\': array([0.8, 0. , 0. ])}\n' _a : List[Any] = '\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' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : Any ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'''] , ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : List[str]="binary" , UpperCAmelCase__ : str=None ): """simple docstring""" snake_case : List[Any] = fa_score( UpperCAmelCase__ , UpperCAmelCase__ , labels=UpperCAmelCase__ , pos_label=UpperCAmelCase__ , average=UpperCAmelCase__ , sample_weight=UpperCAmelCase__ ) return {"f1": float(UpperCAmelCase__ ) if score.size == 1 else score}
84
0
from __future__ import annotations def a_ ( __magic_name__ = 4 ) -> str: """simple docstring""" snake_case : Tuple = abs(lowerCAmelCase_ ) or 4 return [[1 + x + y * row_size for x in range(lowerCAmelCase_ )] for y in range(lowerCAmelCase_ )] def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" return reverse_row(transpose(lowerCAmelCase_ ) ) # OR.. transpose(reverse_column(matrix)) def a_ ( __magic_name__ ) -> Optional[Any]: """simple docstring""" return reverse_row(reverse_column(lowerCAmelCase_ ) ) # OR.. reverse_column(reverse_row(matrix)) def a_ ( __magic_name__ ) -> List[str]: """simple docstring""" return reverse_column(transpose(lowerCAmelCase_ ) ) # OR.. transpose(reverse_row(matrix)) def a_ ( __magic_name__ ) -> Any: """simple docstring""" snake_case : Optional[int] = [list(lowerCAmelCase_ ) for x in zip(*lowerCAmelCase_ )] return matrix def a_ ( __magic_name__ ) -> Any: """simple docstring""" snake_case : Optional[Any] = matrix[::-1] return matrix def a_ ( __magic_name__ ) -> Any: """simple docstring""" snake_case : Optional[int] = [x[::-1] for x in matrix] return matrix def a_ ( __magic_name__ ) -> str: """simple docstring""" for i in matrix: print(*lowerCAmelCase_ ) if __name__ == "__main__": _a : Any = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 90 counterclockwise:\n') print_matrix(rotate_aa(matrix)) _a : Dict = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 180:\n') print_matrix(rotate_aaa(matrix)) _a : Dict = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 270 counterclockwise:\n') print_matrix(rotate_aaa(matrix))
707
def a_ ( __magic_name__ ) -> int: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ): raise TypeError('''only integers accepted as input''' ) else: snake_case : str = str(abs(__magic_name__ ) ) snake_case : Optional[Any] = [list(__magic_name__ ) for char in range(len(__magic_name__ ) )] for index in range(len(__magic_name__ ) ): num_transpositions[index].pop(__magic_name__ ) return max( int(''''''.join(list(__magic_name__ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
84
0
import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class a_ : def lowerCAmelCase( self : str ): """simple docstring""" torch.manual_seed(0 ) snake_case : List[str] = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) snake_case : Tuple = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) snake_case : List[Any] = UNetaDConditionModel( sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) snake_case : int = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , thresholding=UpperCAmelCase__ , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) snake_case : Dict = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" torch.manual_seed(0 ) snake_case : Tuple = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) snake_case : List[str] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) snake_case : str = UNetaDConditionModel( sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , class_embed_type='''timestep''' , mid_block_scale_factor=1.414 , time_embedding_act_fn='''gelu''' , time_embedding_dim=32 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) snake_case : int = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , thresholding=UpperCAmelCase__ , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) snake_case : Union[str, Any] = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , ) torch.manual_seed(0 ) snake_case : List[Any] = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Tuple = self.get_dummy_components() snake_case : Optional[Any] = self.pipeline_class(**UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) snake_case : int = self.get_dummy_inputs(UpperCAmelCase__ ) snake_case : str = inputs['''prompt'''] snake_case : Union[str, Any] = inputs['''generator'''] snake_case : List[Any] = inputs['''num_inference_steps'''] snake_case : Union[str, Any] = inputs['''output_type'''] if "image" in inputs: snake_case : Union[str, Any] = inputs['''image'''] else: snake_case : List[Any] = None if "mask_image" in inputs: snake_case : str = inputs['''mask_image'''] else: snake_case : Any = None if "original_image" in inputs: snake_case : str = inputs['''original_image'''] else: snake_case : List[str] = None snake_case , snake_case : List[str] = pipe.encode_prompt(UpperCAmelCase__ ) # inputs with prompt converted to embeddings snake_case : Any = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: snake_case : Union[str, Any] = image if mask_image is not None: snake_case : Optional[int] = mask_image if original_image is not None: snake_case : int = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : int = pipe(**UpperCAmelCase__ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(UpperCAmelCase__ ) snake_case : Optional[Any] = self.pipeline_class.from_pretrained(UpperCAmelCase__ ) pipe_loaded.to(UpperCAmelCase__ ) pipe_loaded.set_progress_bar_config(disable=UpperCAmelCase__ ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) is None , F"`{optional_component}` did not stay set to None after loading." , ) snake_case : Optional[int] = self.get_dummy_inputs(UpperCAmelCase__ ) snake_case : List[str] = inputs['''generator'''] snake_case : str = inputs['''num_inference_steps'''] snake_case : str = inputs['''output_type'''] # inputs with prompt converted to embeddings snake_case : List[Any] = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: snake_case : str = image if mask_image is not None: snake_case : str = mask_image if original_image is not None: snake_case : Optional[int] = original_image snake_case : Union[str, Any] = pipe_loaded(**UpperCAmelCase__ )[0] snake_case : Union[str, Any] = np.abs(to_np(UpperCAmelCase__ ) - to_np(UpperCAmelCase__ ) ).max() self.assertLess(UpperCAmelCase__ , 1e-4 ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = self.get_dummy_components() snake_case : Union[str, Any] = self.pipeline_class(**UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) snake_case : List[str] = self.get_dummy_inputs(UpperCAmelCase__ ) snake_case : List[str] = pipe(**UpperCAmelCase__ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(UpperCAmelCase__ ) snake_case : List[Any] = self.pipeline_class.from_pretrained(UpperCAmelCase__ ) pipe_loaded.to(UpperCAmelCase__ ) pipe_loaded.set_progress_bar_config(disable=UpperCAmelCase__ ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests snake_case : Dict = self.get_dummy_inputs(UpperCAmelCase__ ) snake_case : Tuple = pipe_loaded(**UpperCAmelCase__ )[0] snake_case : List[Any] = np.abs(to_np(UpperCAmelCase__ ) - to_np(UpperCAmelCase__ ) ).max() self.assertLess(UpperCAmelCase__ , 1e-4 )
708
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class a_ : def __init__( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any]=99 , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Any=9 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : Tuple=32 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=37 , UpperCAmelCase__ : Union[str, Any]=8 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : str=0.002 , UpperCAmelCase__ : str=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : Union[str, Any]=0 , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=None , ): """simple docstring""" snake_case : Union[str, Any] = parent snake_case : Union[str, Any] = batch_size snake_case : Any = encoder_seq_length snake_case : str = decoder_seq_length # For common tests snake_case : Optional[int] = self.decoder_seq_length snake_case : Optional[Any] = is_training snake_case : List[Any] = use_attention_mask snake_case : Union[str, Any] = use_labels snake_case : Any = vocab_size snake_case : Optional[int] = hidden_size snake_case : List[str] = num_hidden_layers snake_case : Union[str, Any] = num_attention_heads snake_case : Any = d_ff snake_case : Any = relative_attention_num_buckets snake_case : Optional[Any] = dropout_rate snake_case : int = initializer_factor snake_case : Optional[Any] = eos_token_id snake_case : Dict = pad_token_id snake_case : Optional[Any] = decoder_start_token_id snake_case : Union[str, Any] = None snake_case : List[str] = decoder_layers def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return TaConfig.from_pretrained('''google/umt5-base''' ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=None , ): """simple docstring""" if attention_mask is None: snake_case : Union[str, Any] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: snake_case : Any = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: snake_case : List[Any] = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=UpperCAmelCase__ ) if decoder_head_mask is None: snake_case : Tuple = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=UpperCAmelCase__ ) if cross_attn_head_mask is None: snake_case : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=UpperCAmelCase__ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input snake_case : List[str] = input_ids.clamp(self.pad_token_id + 1 ) snake_case : List[str] = decoder_input_ids.clamp(self.pad_token_id + 1 ) snake_case : str = self.get_config() snake_case : Tuple = config.num_attention_heads snake_case : List[Any] = self.prepare_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, input_dict def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : List[str] = self.prepare_config_and_inputs() return config, inputs_dict def lowerCAmelCase( self : Dict ): """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def lowerCAmelCase( self : Tuple ): """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , ): """simple docstring""" snake_case : str = UMTaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : str = model( input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , ) snake_case : int = model(input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ ) snake_case : int = result.last_hidden_state snake_case : Dict = result.past_key_values snake_case : Dict = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(UpperCAmelCase__ ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , ): """simple docstring""" snake_case : int = UMTaModel(config=UpperCAmelCase__ ).get_decoder().to(UpperCAmelCase__ ).eval() # first forward pass snake_case : List[Any] = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) snake_case : List[Any] = model(UpperCAmelCase__ ) snake_case : Any = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) self.parent.assertTrue(len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) ) self.parent.assertTrue(len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) + 1 ) snake_case , snake_case : List[str] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids snake_case : Any = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and snake_case : Union[str, Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case : Any = model(UpperCAmelCase__ )['''last_hidden_state'''] snake_case : Optional[Any] = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )['''last_hidden_state'''] # select random slice snake_case : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() snake_case : Tuple = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , ): """simple docstring""" snake_case : int = UMTaModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).half().eval() snake_case : str = model(**UpperCAmelCase__ )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(UpperCAmelCase__ ).any().item() ) @require_torch class a_ ( a , a , a , unittest.TestCase ): A__ : str = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) A__ : str = (UMTaForConditionalGeneration,) if is_torch_available() else () A__ : Any = ( { 'conversational': UMTaForConditionalGeneration, 'feature-extraction': UMTaModel, 'summarization': UMTaForConditionalGeneration, 'text2text-generation': UMTaForConditionalGeneration, 'translation': UMTaForConditionalGeneration, 'question-answering': UMTaForQuestionAnswering, } if is_torch_available() else {} ) A__ : Dict = True A__ : List[str] = False A__ : Optional[int] = False A__ : Optional[int] = True A__ : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests A__ : int = [0.8, 0.9] def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Union[str, Any] = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Tuple = self.model_tester.prepare_config_and_inputs() snake_case : Optional[Any] = UMTaModel(config_and_inputs[0] ).to(UpperCAmelCase__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( UpperCAmelCase__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=UpperCAmelCase__ , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : Optional[int] = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() snake_case : int = config_and_inputs[0] snake_case : Union[str, Any] = UMTaForConditionalGeneration(UpperCAmelCase__ ).eval() model.to(UpperCAmelCase__ ) snake_case : str = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=UpperCAmelCase__ ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ), } for attn_name, (name, mask) in zip(UpperCAmelCase__ , head_masking.items() ): snake_case : int = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": snake_case : List[str] = torch.ones( config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ) snake_case : Union[str, Any] = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=UpperCAmelCase__ , return_dict_in_generate=UpperCAmelCase__ , **UpperCAmelCase__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step snake_case : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def lowerCAmelCase( self : Any ): """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class a_ ( unittest.TestCase ): @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[Any] = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=UpperCAmelCase__ ).to(UpperCAmelCase__ ) snake_case : int = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=UpperCAmelCase__ , legacy=UpperCAmelCase__ ) snake_case : List[str] = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] snake_case : Dict = tokenizer(UpperCAmelCase__ , return_tensors='''pt''' , padding=UpperCAmelCase__ ).input_ids # fmt: off snake_case : Optional[Any] = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : List[Any] = model.generate(input_ids.to(UpperCAmelCase__ ) ) snake_case : int = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] snake_case : Tuple = tokenizer.batch_decode(UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
84
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class a_ ( lowerCAmelCase__ ): A__ : Union[str, Any] = "naver-clova-ix/donut-base-finetuned-docvqa" A__ : List[Any] = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) A__ : Tuple = "document_qa" A__ : Union[str, Any] = AutoProcessor A__ : str = VisionEncoderDecoderModel A__ : List[str] = ["image", "text"] A__ : Tuple = ["text"] def __init__( self : List[Any] , *UpperCAmelCase__ : str , **UpperCAmelCase__ : str ): """simple docstring""" if not is_vision_available(): raise ValueError('''Pillow must be installed to use the DocumentQuestionAnsweringTool.''' ) super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowerCAmelCase( self : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Dict = '''<s_docvqa><s_question>{user_input}</s_question><s_answer>''' snake_case : Optional[int] = task_prompt.replace('''{user_input}''' , _SCREAMING_SNAKE_CASE ) snake_case : List[str] = self.pre_processor.tokenizer( _SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).input_ids snake_case : Union[str, Any] = self.pre_processor(_SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def lowerCAmelCase( self : int , UpperCAmelCase__ : List[str] ): """simple docstring""" return self.model.generate( inputs['''pixel_values'''].to(self.device ) , decoder_input_ids=inputs['''decoder_input_ids'''].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=_SCREAMING_SNAKE_CASE , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=_SCREAMING_SNAKE_CASE , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=_SCREAMING_SNAKE_CASE , ).sequences def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Optional[Any] ): """simple docstring""" snake_case : int = self.pre_processor.batch_decode(_SCREAMING_SNAKE_CASE )[0] snake_case : List[Any] = sequence.replace(self.pre_processor.tokenizer.eos_token , '''''' ) snake_case : int = sequence.replace(self.pre_processor.tokenizer.pad_token , '''''' ) snake_case : Optional[int] = re.sub(r'''<.*?>''' , '''''' , _SCREAMING_SNAKE_CASE , count=1 ).strip() # remove first task start token snake_case : Union[str, Any] = self.pre_processor.tokenajson(_SCREAMING_SNAKE_CASE ) return sequence["answer"]
709
import torch from diffusers import DiffusionPipeline class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): """simple docstring""" super().__init__() self.register_modules(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) def __call__( self : Optional[int] ): """simple docstring""" snake_case : Any = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) snake_case : Dict = 1 snake_case : Optional[Any] = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample snake_case : List[Any] = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ).prev_sample snake_case : List[Any] = scheduler_output - scheduler_output + torch.ones_like(UpperCAmelCase__ ) return result
84
0
from __future__ import annotations from typing import TypedDict class a_ ( _A ): A__ : Tuple = 42 A__ : int = 42 def a_ ( __magic_name__ ) -> int: """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 a_ ( __magic_name__ ) -> str: """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 : List[Any] = 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 : int = { '''bwt_string''': ''''''.join([word[-1] for word in rotations] ), '''idx_original_string''': rotations.index(A_ ), } return response def a_ ( __magic_name__ , __magic_name__ ) -> Union[str, Any]: """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 : int = 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 : List[str] = [''''''] * len(A_ ) for _ in range(len(A_ ) ): for i in range(len(A_ ) ): snake_case : Any = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": _a : Tuple = 'Provide a string that I will generate its BWT transform: ' _a : List[Any] = input(entry_msg).strip() _a : List[Any] = bwt_transform(s) print( f"Burrows Wheeler transform for string \'{s}\' results " f"in \'{result['bwt_string']}\'" ) _a : Optional[Any] = 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}\'" )
710
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a_ ( a ): A__ : List[str] = ['image_processor', 'tokenizer'] A__ : Any = 'CLIPImageProcessor' A__ : Optional[int] = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : Union[str, Any] , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , UpperCAmelCase__ , ) snake_case : List[Any] = kwargs.pop('''feature_extractor''' ) snake_case : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(UpperCAmelCase__ , UpperCAmelCase__ ) def __call__( self : Any , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: snake_case : int = self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if images is not None: snake_case : Dict = self.image_processor(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if text is not None and images is not None: snake_case : Tuple = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase__ ) , tensor_type=UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : int ): """simple docstring""" return self.tokenizer.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : str ): """simple docstring""" return self.tokenizer.decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : int = self.tokenizer.model_input_names snake_case : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , UpperCAmelCase__ , ) return self.image_processor_class @property def lowerCAmelCase( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , UpperCAmelCase__ , ) return self.image_processor
84
0
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch _a : Optional[Any] = random.Random() def a_ ( __magic_name__ , __magic_name__=1.0 , __magic_name__=None , __magic_name__=None ) -> Dict: """simple docstring""" if rng is None: snake_case : List[Any] = global_rng snake_case : List[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class a_ ( unittest.TestCase ): def __init__( self : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict=7 , UpperCAmelCase__ : Dict=400 , UpperCAmelCase__ : str=2_000 , UpperCAmelCase__ : Optional[Any]=10 , UpperCAmelCase__ : int=160 , UpperCAmelCase__ : int=8 , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Optional[Any]=4_000 , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Tuple=True , ): """simple docstring""" snake_case : int = parent snake_case : Optional[Any] = batch_size snake_case : Any = min_seq_length snake_case : Optional[Any] = max_seq_length snake_case : Union[str, Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) snake_case : Optional[Any] = padding_value snake_case : Optional[int] = sampling_rate snake_case : Optional[int] = return_attention_mask snake_case : Optional[int] = do_normalize snake_case : Optional[int] = feature_size snake_case : Union[str, Any] = chunk_length snake_case : Dict = hop_length def lowerCAmelCase( self : Any ): """simple docstring""" return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Union[str, Any]=False ): """simple docstring""" def _flatten(UpperCAmelCase__ : List[str] ): return list(itertools.chain(*_A ) ) if equal_length: snake_case : Any = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size snake_case : int = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: snake_case : List[str] = [np.asarray(_A ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class a_ ( snake_case__ , unittest.TestCase ): A__ : Optional[int] = WhisperFeatureExtractor if is_speech_available() else None def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : Union[str, Any] = WhisperFeatureExtractionTester(self ) def lowerCAmelCase( self : str ): """simple docstring""" snake_case : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case : int = feat_extract_first.save_pretrained(_A )[0] check_json_file_has_correct_format(_A ) snake_case : Optional[int] = self.feature_extraction_class.from_pretrained(_A ) snake_case : Dict = feat_extract_first.to_dict() snake_case : int = feat_extract_second.to_dict() snake_case : int = feat_extract_first.mel_filters snake_case : int = feat_extract_second.mel_filters self.assertTrue(np.allclose(_A , _A ) ) self.assertEqual(_A , _A ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case : Dict = os.path.join(_A , '''feat_extract.json''' ) feat_extract_first.to_json_file(_A ) snake_case : str = self.feature_extraction_class.from_json_file(_A ) snake_case : Optional[Any] = feat_extract_first.to_dict() snake_case : Dict = feat_extract_second.to_dict() snake_case : Union[str, Any] = feat_extract_first.mel_filters snake_case : Any = feat_extract_second.mel_filters self.assertTrue(np.allclose(_A , _A ) ) self.assertEqual(_A , _A ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus snake_case : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 snake_case : str = [floats_list((1, x) )[0] for x in range(800 , 1_400 , 200 )] snake_case : Optional[int] = [np.asarray(_A ) for speech_input in speech_inputs] # Test feature size snake_case : Any = feature_extractor(_A , padding='''max_length''' , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input snake_case : Dict = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features snake_case : Any = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(_A , _A , atol=1e-3 ) ) # Test batched snake_case : Any = feature_extractor(_A , return_tensors='''np''' ).input_features snake_case : int = feature_extractor(_A , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(_A , _A ): self.assertTrue(np.allclose(_A , _A , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. snake_case : Tuple = [floats_list((1, x) )[0] for x in (800, 800, 800)] snake_case : Tuple = np.asarray(_A ) snake_case : Union[str, Any] = feature_extractor(_A , return_tensors='''np''' ).input_features snake_case : List[Any] = feature_extractor(_A , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(_A , _A ): self.assertTrue(np.allclose(_A , _A , atol=1e-3 ) ) # Test truncation required snake_case : List[str] = [floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] snake_case : Optional[Any] = [np.asarray(_A ) for speech_input in speech_inputs] snake_case : str = [x[: feature_extractor.n_samples] for x in speech_inputs] snake_case : Any = [np.asarray(_A ) for speech_input in speech_inputs_truncated] snake_case : str = feature_extractor(_A , return_tensors='''np''' ).input_features snake_case : List[Any] = feature_extractor(_A , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(_A , _A ): self.assertTrue(np.allclose(_A , _A , atol=1e-3 ) ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" import torch snake_case : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case : Union[str, Any] = np.random.rand(100 , 32 ).astype(np.floataa ) snake_case : Optional[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: snake_case : Tuple = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) snake_case : Any = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Tuple ): """simple docstring""" snake_case : List[str] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech snake_case : List[Any] = ds.sort('''id''' ).select(range(_A ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def lowerCAmelCase( self : Dict ): """simple docstring""" # fmt: off snake_case : List[Any] = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ] ) # fmt: on snake_case : Tuple = self._load_datasamples(1 ) snake_case : List[str] = WhisperFeatureExtractor() snake_case : Any = feature_extractor(_A , return_tensors='''pt''' ).input_features self.assertEqual(input_features.shape , (1, 80, 3_000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , _A , atol=1e-4 ) ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) snake_case : Tuple = self._load_datasamples(1 )[0] snake_case : Tuple = ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535 # Rescale to [0, 65535] to show issue snake_case : Tuple = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=_A )[0] self.assertTrue(np.all(np.mean(_A ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(_A ) - 1 ) < 1e-3 ) )
711
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _a : Optional[Any] = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' _a : str = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' _a : List[Any] = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : Any ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/krishnap25/mauve''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/krishnap25/mauve'''] , reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] , ) def lowerCAmelCase( self : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : List[str]="auto" , UpperCAmelCase__ : Tuple=-1 , UpperCAmelCase__ : Optional[int]=0.9 , UpperCAmelCase__ : List[Any]=5 , UpperCAmelCase__ : List[Any]=500 , UpperCAmelCase__ : Union[str, Any]="gpt2-large" , UpperCAmelCase__ : Optional[Any]=-1 , UpperCAmelCase__ : int=1_024 , UpperCAmelCase__ : List[Any]=25 , UpperCAmelCase__ : Union[str, Any]=5 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[Any]=25 , ): """simple docstring""" snake_case : List[str] = compute_mauve( p_text=UpperCAmelCase__ , q_text=UpperCAmelCase__ , p_features=UpperCAmelCase__ , q_features=UpperCAmelCase__ , p_tokens=UpperCAmelCase__ , q_tokens=UpperCAmelCase__ , num_buckets=UpperCAmelCase__ , pca_max_data=UpperCAmelCase__ , kmeans_explained_var=UpperCAmelCase__ , kmeans_num_redo=UpperCAmelCase__ , kmeans_max_iter=UpperCAmelCase__ , featurize_model_name=UpperCAmelCase__ , device_id=UpperCAmelCase__ , max_text_length=UpperCAmelCase__ , divergence_curve_discretization_size=UpperCAmelCase__ , mauve_scaling_factor=UpperCAmelCase__ , verbose=UpperCAmelCase__ , seed=UpperCAmelCase__ , ) return out
84
0
def a_ ( __magic_name__ ) -> Optional[Any]: """simple docstring""" stooge(__snake_case , 0 , len(__snake_case ) - 1 ) return arr def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> List[Any]: """simple docstring""" if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: snake_case , snake_case : Tuple = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: snake_case : Optional[int] = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(__snake_case , __snake_case , (h - t) ) # Recursively sort last 2/3 elements stooge(__snake_case , i + t , (__snake_case) ) # Recursively sort first 2/3 elements stooge(__snake_case , __snake_case , (h - t) ) if __name__ == "__main__": _a : Dict = input('Enter numbers separated by a comma:\n').strip() _a : Tuple = [int(item) for item in user_input.split(',')] print(stooge_sort(unsorted))
712
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" if "cls_token" in name: snake_case : Tuple = name.replace('''cls_token''' , '''vit.embeddings.cls_token''' ) if "mask_token" in name: snake_case : Optional[int] = name.replace('''mask_token''' , '''decoder.mask_token''' ) if "decoder_pos_embed" in name: snake_case : List[str] = name.replace('''decoder_pos_embed''' , '''decoder.decoder_pos_embed''' ) if "pos_embed" in name and "decoder" not in name: snake_case : List[str] = name.replace('''pos_embed''' , '''vit.embeddings.position_embeddings''' ) if "patch_embed.proj" in name: snake_case : List[Any] = name.replace('''patch_embed.proj''' , '''vit.embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: snake_case : int = name.replace('''patch_embed.norm''' , '''vit.embeddings.norm''' ) if "decoder_blocks" in name: snake_case : int = name.replace('''decoder_blocks''' , '''decoder.decoder_layers''' ) if "blocks" in name: snake_case : Optional[Any] = name.replace('''blocks''' , '''vit.encoder.layer''' ) if "attn.proj" in name: snake_case : str = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: snake_case : Any = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: snake_case : List[str] = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: snake_case : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: snake_case : Tuple = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: snake_case : Tuple = name.replace('''mlp.fc2''' , '''output.dense''' ) if "decoder_embed" in name: snake_case : Dict = name.replace('''decoder_embed''' , '''decoder.decoder_embed''' ) if "decoder_norm" in name: snake_case : Dict = name.replace('''decoder_norm''' , '''decoder.decoder_norm''' ) if "decoder_pred" in name: snake_case : Dict = name.replace('''decoder_pred''' , '''decoder.decoder_pred''' ) if "norm.weight" in name and "decoder" not in name: snake_case : Optional[int] = name.replace('''norm.weight''' , '''vit.layernorm.weight''' ) if "norm.bias" in name and "decoder" not in name: snake_case : List[str] = name.replace('''norm.bias''' , '''vit.layernorm.bias''' ) return name def a_ ( __magic_name__ , __magic_name__ ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): snake_case : Union[str, Any] = orig_state_dict.pop(__magic_name__ ) if "qkv" in key: snake_case : Optional[int] = key.split('''.''' ) snake_case : int = int(key_split[1] ) if "decoder_blocks" in key: snake_case : List[str] = config.decoder_hidden_size snake_case : List[Any] = '''decoder.decoder_layers.''' if "weight" in key: snake_case : str = val[:dim, :] snake_case : Optional[Any] = val[dim : dim * 2, :] snake_case : Any = val[-dim:, :] elif "bias" in key: snake_case : Optional[Any] = val[:dim] snake_case : List[Any] = val[dim : dim * 2] snake_case : List[Any] = val[-dim:] else: snake_case : Optional[int] = config.hidden_size snake_case : Tuple = '''vit.encoder.layer.''' if "weight" in key: snake_case : Optional[Any] = val[:dim, :] snake_case : str = val[dim : dim * 2, :] snake_case : Union[str, Any] = val[-dim:, :] elif "bias" in key: snake_case : Tuple = val[:dim] snake_case : int = val[dim : dim * 2] snake_case : Optional[Any] = val[-dim:] else: snake_case : Optional[Any] = val return orig_state_dict def a_ ( __magic_name__ , __magic_name__ ) -> Any: """simple docstring""" snake_case : List[str] = ViTMAEConfig() if "large" in checkpoint_url: snake_case : str = 1_024 snake_case : Tuple = 4_096 snake_case : Optional[Any] = 24 snake_case : List[Any] = 16 elif "huge" in checkpoint_url: snake_case : Tuple = 14 snake_case : int = 1_280 snake_case : Dict = 5_120 snake_case : Tuple = 32 snake_case : Optional[Any] = 16 snake_case : Optional[Any] = ViTMAEForPreTraining(__magic_name__ ) snake_case : Optional[Any] = torch.hub.load_state_dict_from_url(__magic_name__ , map_location='''cpu''' )['''model'''] snake_case : int = ViTMAEImageProcessor(size=config.image_size ) snake_case : Dict = convert_state_dict(__magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ ) model.eval() snake_case : Tuple = '''https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg''' snake_case : List[Any] = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) snake_case : Dict = ViTMAEImageProcessor(size=config.image_size ) snake_case : str = image_processor(images=__magic_name__ , return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) snake_case : Union[str, Any] = model(**__magic_name__ ) snake_case : Optional[Any] = outputs.logits if "large" in checkpoint_url: snake_case : Any = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] ) elif "huge" in checkpoint_url: snake_case : List[Any] = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] ) else: snake_case : Dict = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , __magic_name__ , atol=1e-4 ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__magic_name__ ) if __name__ == "__main__": _a : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) _a : str = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
84
0
import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class a_ ( lowercase_ , unittest.TestCase ): A__ : Dict = MobileBertTokenizer A__ : Dict = MobileBertTokenizerFast A__ : List[Any] = True A__ : str = True A__ : Any = filter_non_english A__ : Dict = 'google/mobilebert-uncased' def lowerCAmelCase( self : Tuple ): """simple docstring""" super().setUp() snake_case : Optional[int] = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] snake_case : int = 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 : str = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : int ): """simple docstring""" snake_case : Optional[Any] = """UNwant\u00E9d,running""" snake_case : Any = """unwanted, running""" return input_text, output_text def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Tuple = self.tokenizer_class(self.vocab_file ) snake_case : List[str] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(lowerCamelCase_ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , [9, 6, 7, 12, 10, 11] ) def lowerCAmelCase( self : int ): """simple docstring""" if not self.test_rust_tokenizer: return snake_case : int = self.get_tokenizer() snake_case : Optional[Any] = self.get_rust_tokenizer() snake_case : Optional[int] = """UNwant\u00E9d,running""" snake_case : Optional[int] = tokenizer.tokenize(lowerCamelCase_ ) snake_case : List[Any] = rust_tokenizer.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) snake_case : List[str] = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) snake_case : Optional[int] = rust_tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) snake_case : Optional[int] = self.get_rust_tokenizer() snake_case : List[Any] = tokenizer.encode(lowerCamelCase_ ) snake_case : Union[str, Any] = rust_tokenizer.encode(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) # With lower casing snake_case : List[str] = self.get_tokenizer(do_lower_case=lowerCamelCase_ ) snake_case : Optional[Any] = self.get_rust_tokenizer(do_lower_case=lowerCamelCase_ ) snake_case : List[Any] = """UNwant\u00E9d,running""" snake_case : Tuple = tokenizer.tokenize(lowerCamelCase_ ) snake_case : Any = rust_tokenizer.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) snake_case : Tuple = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) snake_case : Union[str, Any] = rust_tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) snake_case : int = self.get_rust_tokenizer() snake_case : Dict = tokenizer.encode(lowerCamelCase_ ) snake_case : int = rust_tokenizer.encode(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Optional[int] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : List[Any] = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : List[str] = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : Tuple = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : int = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : List[str] = BasicTokenizer(do_lower_case=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : int = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Dict = BasicTokenizer(do_lower_case=lowerCamelCase_ , strip_accents=lowerCamelCase_ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : List[str] = BasicTokenizer(do_lower_case=lowerCamelCase_ , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : Tuple = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] snake_case : List[str] = {} for i, token in enumerate(lowerCamelCase_ ): snake_case : List[str] = i snake_case : Union[str, Any] = WordpieceTokenizer(vocab=lowerCamelCase_ , 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 lowerCAmelCase( self : Dict ): """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 lowerCAmelCase( self : Tuple ): """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 lowerCAmelCase( self : Any ): """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 lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : int = self.get_tokenizer() snake_case : List[str] = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(lowerCamelCase_ ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(lowerCamelCase_ ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : List[Any] = self.tokenizer_class.from_pretrained('''google/mobilebert-uncased''' ) snake_case : List[Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=lowerCamelCase_ ) snake_case : Optional[int] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=lowerCamelCase_ ) snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ ) snake_case : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ , lowerCamelCase_ ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def lowerCAmelCase( self : Tuple ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case : Optional[Any] = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) snake_case : Tuple = F"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." snake_case : List[Any] = tokenizer_r.encode_plus( lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , return_token_type_ids=lowerCamelCase_ , return_offsets_mapping=lowerCamelCase_ , add_special_tokens=lowerCamelCase_ , ) snake_case : int = tokenizer_r.do_lower_case if hasattr(lowerCamelCase_ , '''do_lower_case''' ) else False snake_case : Dict = ( [ ((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 lowerCAmelCase( self : Any ): """simple docstring""" snake_case : List[str] = ["""的""", """人""", """有"""] snake_case : Tuple = """""".join(lowerCamelCase_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case : str = True snake_case : Optional[Any] = self.tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) snake_case : str = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) snake_case : List[Any] = tokenizer_p.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) snake_case : Optional[Any] = tokenizer_r.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) snake_case : List[Any] = tokenizer_r.convert_ids_to_tokens(lowerCamelCase_ ) snake_case : Optional[Any] = tokenizer_p.convert_ids_to_tokens(lowerCamelCase_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) snake_case : Optional[int] = False snake_case : int = self.rust_tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) snake_case : List[str] = self.tokenizer_class.from_pretrained(lowerCamelCase_ , **lowerCamelCase_ ) snake_case : Any = tokenizer_r.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) snake_case : List[str] = tokenizer_p.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) snake_case : str = tokenizer_r.convert_ids_to_tokens(lowerCamelCase_ ) snake_case : Any = tokenizer_p.convert_ids_to_tokens(lowerCamelCase_ ) # it is expected that only the first Chinese character is not preceded by "##". snake_case : List[str] = [ F"##{token}" if idx != 0 else token for idx, token in enumerate(lowerCamelCase_ ) ] self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ )
713
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _a : Optional[Any] = 16 _a : Union[str, Any] = 32 def a_ ( __magic_name__ , __magic_name__ = 16 ) -> Dict: """simple docstring""" snake_case : Tuple = AutoTokenizer.from_pretrained('''bert-base-cased''' ) snake_case : Any = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__magic_name__ ): # max_length=None => use the model max length (it's actually the default) snake_case : Union[str, Any] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__magic_name__ , max_length=__magic_name__ ) 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( __magic_name__ , batched=__magic_name__ , 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(__magic_name__ ): # On TPU it's best to pad everything to the same length or training will be very slow. snake_case : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": snake_case : Tuple = 16 elif accelerator.mixed_precision != "no": snake_case : Dict = 8 else: snake_case : Union[str, Any] = None return tokenizer.pad( __magic_name__ , padding='''longest''' , max_length=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_tensors='''pt''' , ) # Instantiate dataloaders. snake_case : str = DataLoader( tokenized_datasets['''train'''] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) snake_case : List[str] = DataLoader( tokenized_datasets['''validation'''] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders _a : Optional[int] = mocked_dataloaders # noqa: F811 def a_ ( __magic_name__ , __magic_name__ ) -> Optional[Any]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , __magic_name__ ) == "1": snake_case : Optional[int] = 2 # Initialize accelerator snake_case : 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 : Dict = config['''lr'''] snake_case : Any = int(config['''num_epochs'''] ) snake_case : List[str] = int(config['''seed'''] ) snake_case : List[Any] = int(config['''batch_size'''] ) snake_case : Tuple = evaluate.load('''glue''' , '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=__magic_name__ ) def inner_training_loop(__magic_name__ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(__magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) snake_case : str = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=__magic_name__ ) # 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 : Optional[int] = model.to(accelerator.device ) # Instantiate optimizer snake_case : Optional[int] = AdamW(params=model.parameters() , lr=__magic_name__ ) snake_case , snake_case : List[Any] = get_dataloaders(__magic_name__ , __magic_name__ ) # Instantiate scheduler snake_case : int = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=100 , num_training_steps=(len(__magic_name__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. snake_case , snake_case , snake_case , snake_case , snake_case : Tuple = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # Now we train the model for epoch in range(__magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) snake_case : int = model(**__magic_name__ ) snake_case : Optional[int] = outputs.loss accelerator.backward(__magic_name__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): snake_case : List[str] = model(**__magic_name__ ) snake_case : List[Any] = outputs.logits.argmax(dim=-1 ) snake_case , snake_case : Dict = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) snake_case : Tuple = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , __magic_name__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def a_ ( ) -> Union[str, Any]: """simple docstring""" snake_case : int = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=__magic_name__ , default=__magic_name__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) snake_case : Optional[Any] = parser.parse_args() snake_case : Optional[int] = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
84
0
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. _a : List[str] = abspath(join(dirname(__file__), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def a_ ( __magic_name__ ) -> Optional[int]: """simple docstring""" config.addinivalue_line( '''markers''' , '''is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested''' ) config.addinivalue_line( '''markers''' , '''is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested''' ) config.addinivalue_line('''markers''' , '''is_pipeline_test: mark test to run only when pipelines are tested''' ) config.addinivalue_line('''markers''' , '''is_staging_test: mark test to run only in the staging environment''' ) config.addinivalue_line('''markers''' , '''accelerate_tests: mark test that require accelerate''' ) config.addinivalue_line('''markers''' , '''tool_tests: mark the tool tests that are run on their specific schedule''' ) def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(A__ ) def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" from transformers.testing_utils import pytest_terminal_summary_main snake_case : str = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(A__ , id=A__ ) def a_ ( __magic_name__ , __magic_name__ ) -> Optional[Any]: """simple docstring""" if exitstatus == 5: snake_case : List[Any] = 0 # Doctest custom flag to ignore output. _a : Tuple = doctest.register_optionflag('IGNORE_RESULT') _a : List[str] = doctest.OutputChecker class a_ ( __lowerCamelCase ): def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any ): """simple docstring""" if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) _a : Any = CustomOutputChecker _a : Dict = HfDoctestModule _a : Tuple = HfDocTestParser
714
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract _a : Dict = logging.get_logger(__name__) def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> List[Any]: """simple docstring""" return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def a_ ( __magic_name__ , __magic_name__ , __magic_name__ = None ) -> str: """simple docstring""" snake_case : Any = tesseract_config if tesseract_config is not None else '''''' # apply OCR snake_case : str = to_pil_image(__magic_name__ ) snake_case , snake_case : Union[str, Any] = pil_image.size snake_case : List[Any] = pytesseract.image_to_data(__magic_name__ , lang=__magic_name__ , output_type='''dict''' , config=__magic_name__ ) snake_case , snake_case , snake_case , snake_case , snake_case : Optional[Any] = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates snake_case : Union[str, Any] = [idx for idx, word in enumerate(__magic_name__ ) if not word.strip()] snake_case : Union[str, Any] = [word for idx, word in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : Optional[Any] = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format snake_case : List[Any] = [] for x, y, w, h in zip(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): snake_case : Optional[int] = [x, y, x + w, y + h] actual_boxes.append(__magic_name__ ) # finally, normalize the bounding boxes snake_case : List[Any] = [] for box in actual_boxes: normalized_boxes.append(normalize_box(__magic_name__ , __magic_name__ , __magic_name__ ) ) assert len(__magic_name__ ) == len(__magic_name__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class a_ ( a ): A__ : int = ['pixel_values'] def __init__( self : Optional[int] , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = "" , **UpperCAmelCase__ : int , ): """simple docstring""" super().__init__(**UpperCAmelCase__ ) snake_case : Any = size if size is not None else {'''height''': 224, '''width''': 224} snake_case : Tuple = get_size_dict(UpperCAmelCase__ ) snake_case : Dict = do_resize snake_case : str = size snake_case : Optional[int] = resample snake_case : Union[str, Any] = apply_ocr snake_case : int = ocr_lang snake_case : Union[str, Any] = tesseract_config def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Any , ): """simple docstring""" snake_case : Dict = get_size_dict(UpperCAmelCase__ ) 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(UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : List[Any] , ): """simple docstring""" snake_case : Tuple = do_resize if do_resize is not None else self.do_resize snake_case : List[Any] = size if size is not None else self.size snake_case : Tuple = get_size_dict(UpperCAmelCase__ ) snake_case : str = resample if resample is not None else self.resample snake_case : Optional[int] = apply_ocr if apply_ocr is not None else self.apply_ocr snake_case : Any = ocr_lang if ocr_lang is not None else self.ocr_lang snake_case : Optional[int] = tesseract_config if tesseract_config is not None else self.tesseract_config snake_case : List[str] = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) # All transformations expect numpy arrays. snake_case : Any = [to_numpy_array(UpperCAmelCase__ ) for image in images] if apply_ocr: requires_backends(self , '''pytesseract''' ) snake_case : Optional[int] = [] snake_case : Union[str, Any] = [] for image in images: snake_case , snake_case : List[Any] = apply_tesseract(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) words_batch.append(UpperCAmelCase__ ) boxes_batch.append(UpperCAmelCase__ ) if do_resize: snake_case : Any = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) snake_case : int = [flip_channel_order(UpperCAmelCase__ ) for image in images] snake_case : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] snake_case : List[Any] = BatchFeature(data={'''pixel_values''': images} , tensor_type=UpperCAmelCase__ ) if apply_ocr: snake_case : Dict = words_batch snake_case : Dict = boxes_batch return data
84
0
'''simple docstring''' import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": _a : List[str] = argparse.ArgumentParser( description=( 'Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='bert', choices=['bert']) parser.add_argument('--model_name', default='bert-base-uncased', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_bert-base-uncased_0247911.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') _a : Tuple = parser.parse_args() if args.model_type == "bert": _a : List[Any] = BertForMaskedLM.from_pretrained(args.model_name) _a : List[str] = 'bert' else: raise ValueError('args.model_type should be "bert".') _a : Optional[Any] = model.state_dict() _a : Union[str, Any] = {} for w in ["word_embeddings", "position_embeddings"]: _a : Optional[int] = state_dict[f"{prefix}.embeddings.{w}.weight"] for w in ["weight", "bias"]: _a : int = state_dict[f"{prefix}.embeddings.LayerNorm.{w}"] _a : Any = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: _a : Dict = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}" ] _a : List[Any] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}" ] _a : Optional[int] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}" ] _a : List[str] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}" ] _a : Optional[int] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}" ] _a : Optional[int] = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}" ] _a : int = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}" ] _a : Tuple = state_dict[ f"{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}" ] std_idx += 1 _a : str = state_dict['cls.predictions.decoder.weight'] _a : Dict = state_dict['cls.predictions.bias'] if args.vocab_transform: for w in ["weight", "bias"]: _a : List[Any] = state_dict[f"cls.predictions.transform.dense.{w}"] _a : List[Any] = state_dict[f"cls.predictions.transform.LayerNorm.{w}"] print(f"N layers selected for distillation: {std_idx}") print(f"Number of params transferred for distillation: {len(compressed_sd.keys())}") print(f"Save transferred checkpoint to {args.dump_checkpoint}.") torch.save(compressed_sd, args.dump_checkpoint)
715
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class a_ : def __init__( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any]=13 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : List[Any]=24 , UpperCAmelCase__ : Union[str, Any]=16 , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : int=32 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : Optional[int]=37 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Optional[int]=10 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : Optional[Any]=2 , ): """simple docstring""" snake_case : Tuple = parent snake_case : Dict = batch_size snake_case : str = patch_size snake_case : Union[str, Any] = max_length snake_case : str = num_mel_bins snake_case : Any = is_training snake_case : Union[str, Any] = use_labels snake_case : Tuple = hidden_size snake_case : Dict = num_hidden_layers snake_case : Any = num_attention_heads snake_case : Any = intermediate_size snake_case : List[Any] = hidden_act snake_case : str = hidden_dropout_prob snake_case : str = attention_probs_dropout_prob snake_case : str = type_sequence_label_size snake_case : Optional[int] = initializer_range snake_case : str = scope snake_case : int = frequency_stride snake_case : Union[str, Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) snake_case : Optional[int] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 snake_case : Any = (self.max_length - self.patch_size) // self.time_stride + 1 snake_case : Union[str, Any] = frequency_out_dimension * time_out_dimension snake_case : Union[str, Any] = num_patches + 2 def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Optional[int] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) snake_case : str = None if self.use_labels: snake_case : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case : List[str] = self.get_config() return config, input_values, labels def lowerCAmelCase( self : Any ): """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : str = ASTModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : Any = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : int = self.prepare_config_and_inputs() ( ( snake_case ) , ( snake_case ) , ( snake_case ) , ) : int = config_and_inputs snake_case : Tuple = {'''input_values''': input_values} return config, inputs_dict @require_torch class a_ ( a , a , unittest.TestCase ): A__ : List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) A__ : int = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) A__ : Optional[Any] = False A__ : Dict = False A__ : int = False A__ : Optional[int] = False def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int ): """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[int] = ASTModelTester(self ) snake_case : Optional[int] = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=37 ) def lowerCAmelCase( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def lowerCAmelCase( self : Tuple ): """simple docstring""" pass def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Optional[Any] = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case : Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , nn.Linear ) ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Any = model_class(UpperCAmelCase__ ) snake_case : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case : str = [*signature.parameters.keys()] snake_case : List[str] = ['''input_values'''] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) @slow def lowerCAmelCase( self : List[str] ): """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : List[str] = ASTModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def a_ ( ) -> Dict: """simple docstring""" snake_case : Dict = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) snake_case , snake_case : int = torchaudio.load(__magic_name__ ) return audio, sampling_rate @require_torch @require_torchaudio class a_ ( unittest.TestCase ): @cached_property def lowerCAmelCase( self : Any ): """simple docstring""" return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : List[str] = self.default_feature_extractor snake_case : str = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(UpperCAmelCase__ ) snake_case : str = self.default_feature_extractor snake_case , snake_case : int = prepare_audio() snake_case : Optional[int] = audio.squeeze().numpy() snake_case : Optional[Any] = feature_extractor(UpperCAmelCase__ , sampling_rate=UpperCAmelCase__ , return_tensors='''pt''' ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): snake_case : Union[str, Any] = model(**UpperCAmelCase__ ) # verify the logits snake_case : Any = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) snake_case : str = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1e-4 ) )
84
0
import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class a_ ( a , unittest.TestCase ): A__ : Union[str, Any] = BarthezTokenizer A__ : int = BarthezTokenizerFast A__ : str = True A__ : List[Any] = True def lowerCAmelCase( self : int ): """simple docstring""" super().setUp() snake_case : Tuple = BarthezTokenizerFast.from_pretrained('''moussaKam/mbarthez''' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=lowercase_ ) snake_case : Dict = tokenizer def lowerCAmelCase( self : str ): """simple docstring""" snake_case : List[Any] = '''<pad>''' snake_case : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_ ) , lowercase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_ ) , lowercase_ ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''<mask>''' ) self.assertEqual(len(lowercase_ ) , 101_122 ) def lowerCAmelCase( self : str ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 101_122 ) @require_torch def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : List[str] = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] snake_case : Union[str, Any] = [0, 57, 3_018, 70_307, 91, 2] snake_case : Dict = self.tokenizer( lowercase_ , max_length=len(lowercase_ ) , padding=lowercase_ , truncation=lowercase_ , return_tensors='''pt''' ) self.assertIsInstance(lowercase_ , lowercase_ ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) snake_case : Optional[int] = batch.input_ids.tolist()[0] self.assertListEqual(lowercase_ , lowercase_ ) def lowerCAmelCase( self : str ): """simple docstring""" if not self.test_rust_tokenizer: return snake_case : Tuple = self.get_tokenizer() snake_case : int = self.get_rust_tokenizer() snake_case : int = '''I was born in 92000, and this is falsé.''' snake_case : str = tokenizer.tokenize(lowercase_ ) snake_case : Tuple = rust_tokenizer.tokenize(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) snake_case : List[str] = tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ ) snake_case : Union[str, Any] = rust_tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) snake_case : List[str] = self.get_rust_tokenizer() snake_case : List[Any] = tokenizer.encode(lowercase_ ) snake_case : Dict = rust_tokenizer.encode(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) @slow def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : List[str] = {'''input_ids''': [[0, 490, 14_328, 4_507, 354, 47, 43_669, 95, 25, 78_117, 20_215, 19_779, 190, 22, 400, 4, 35_343, 80_310, 603, 86, 24_937, 105, 33_438, 94_762, 196, 39_642, 7, 15, 15_933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10_534, 87, 25, 66, 3_358, 196, 55_289, 8, 82_961, 81, 2_204, 75_203, 7, 15, 763, 12_956, 216, 178, 14_328, 9_595, 1_377, 69_693, 7, 448, 71_021, 196, 18_106, 1_437, 13_974, 108, 9_083, 4, 49_315, 7, 39, 86, 1_326, 2_793, 46_333, 4, 448, 196, 74_588, 7, 49_315, 7, 39, 21, 822, 38_470, 74, 21, 66_723, 62_480, 8, 22_050, 5, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. snake_case : Union[str, Any] = [ '''Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ''' '''utilisé principalement dans le domaine du traitement automatique des langues (TAL).''', '''À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ''' '''pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ''' '''telles que la traduction et la synthèse de texte.''', ] self.tokenizer_integration_test_util( expected_encoding=lowercase_ , model_name='''moussaKam/mbarthez''' , revision='''c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6''' , sequences=lowercase_ , )
716
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _a : Union[str, Any] = logging.getLogger(__name__) def a_ ( __magic_name__ , __magic_name__ ) -> Optional[int]: """simple docstring""" return (preds == labels).mean() @dataclass class a_ : A__ : str = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class a_ : A__ : str = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys() )} ) A__ : str = field(metadata={'help': 'Should contain the data files for the task.'} ) A__ : int = field( default=128 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) A__ : bool = field( default=a , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def a_ ( ) -> Dict: """simple docstring""" snake_case : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) snake_case , snake_case , snake_case : Tuple = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"Output directory ({training_args.output_dir}) already exists and is not empty. Use" ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , __magic_name__ ) # Set seed set_seed(training_args.seed ) try: snake_case : int = processors[data_args.task_name]() snake_case : List[str] = processor.get_labels() snake_case : str = len(__magic_name__ ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case : List[Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__magic_name__ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) snake_case : str = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) snake_case : Any = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__magic_name__ , cache_dir=model_args.cache_dir , ) # Get datasets snake_case : Optional[int] = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) snake_case : Any = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(__magic_name__ ) -> Dict: snake_case : str = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(__magic_name__ , p.label_ids )} # Data collator snake_case : Dict = DataCollatorWithPadding(__magic_name__ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer snake_case : List[Any] = Trainer( model=__magic_name__ , args=__magic_name__ , train_dataset=__magic_name__ , eval_dataset=__magic_name__ , compute_metrics=__magic_name__ , data_collator=__magic_name__ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation snake_case : Optional[int] = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) snake_case : Optional[Any] = trainer.evaluate() snake_case : Union[str, Any] = os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_master(): with open(__magic_name__ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''' , __magic_name__ , __magic_name__ ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__magic_name__ ) return results def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" main() if __name__ == "__main__": main()
84
0
import random def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> int: """simple docstring""" snake_case : Tuple = a[left_index] snake_case : Tuple = left_index + 1 for j in range(left_index + 1 , snake_case__ ): if a[j] < pivot: snake_case , snake_case : int = a[i], a[j] i += 1 snake_case , snake_case : Union[str, Any] = a[i - 1], a[left_index] return i - 1 def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> Union[str, Any]: """simple docstring""" if left < right: snake_case : List[Any] = random.randint(snake_case__ , right - 1 ) snake_case , snake_case : List[Any] = ( a[left], a[pivot], ) # switches the pivot with the left most bound snake_case : List[Any] = partition(snake_case__ , snake_case__ , snake_case__ ) quick_sort_random( snake_case__ , snake_case__ , snake_case__ ) # recursive quicksort to the left of the pivot point quick_sort_random( snake_case__ , pivot_index + 1 , snake_case__ ) # recursive quicksort to the right of the pivot point def a_ ( ) -> Optional[int]: """simple docstring""" snake_case : Optional[int] = input('''Enter numbers separated by a comma:\n''' ).strip() snake_case : int = [int(snake_case__ ) for item in user_input.split(''',''' )] quick_sort_random(snake_case__ , 0 , len(snake_case__ ) ) print(snake_case__ ) if __name__ == "__main__": main()
717
import re def a_ ( __magic_name__ ) -> bool: """simple docstring""" snake_case : List[str] = re.compile( R'''^(?:0|94|\+94|0{2}94)''' R'''7(0|1|2|4|5|6|7|8)''' R'''(-| |)''' R'''\d{7}$''' ) return bool(re.search(__magic_name__ , __magic_name__ ) ) if __name__ == "__main__": _a : Any = '0094702343221' print(is_sri_lankan_phone_number(phone))
84
0
from __future__ import annotations def a_ ( __magic_name__ , __magic_name__ ) -> tuple[int, int]: """simple docstring""" if b == 0: return (1, 0) (snake_case) : Union[str, Any] = extended_euclid(__magic_name__ , a % b ) snake_case : int = a // b return (y, x - k * y) def a_ ( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: """simple docstring""" (snake_case) : int = extended_euclid(__magic_name__ , __magic_name__ ) snake_case : Optional[Any] = na * na snake_case : Any = ra * x * na + ra * y * na return (n % m + m) % m def a_ ( __magic_name__ , __magic_name__ ) -> int: """simple docstring""" (snake_case) : Optional[int] = extended_euclid(__magic_name__ , __magic_name__ ) if b < 0: snake_case : int = (b % n + n) % n return b def a_ ( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: """simple docstring""" snake_case : List[str] = invert_modulo(__magic_name__ , __magic_name__ ), invert_modulo(__magic_name__ , __magic_name__ ) snake_case : List[str] = na * na snake_case : str = ra * x * na + ra * y * na return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name='chinese_remainder_theorem', verbose=True) testmod(name='chinese_remainder_theorem2', verbose=True) testmod(name='invert_modulo', verbose=True) testmod(name='extended_euclid', verbose=True)
718
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class a_ ( unittest.TestCase ): def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : int=18 , UpperCAmelCase__ : Optional[int]=30 , UpperCAmelCase__ : Optional[int]=400 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : int=True , ): """simple docstring""" snake_case : int = size if size is not None else {'''height''': 18, '''width''': 18} snake_case : Optional[Any] = parent snake_case : Any = batch_size snake_case : Any = num_channels snake_case : Union[str, Any] = image_size snake_case : Dict = min_resolution snake_case : Dict = max_resolution snake_case : int = do_resize snake_case : List[str] = size snake_case : List[Any] = apply_ocr def lowerCAmelCase( self : int ): """simple docstring""" return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class a_ ( a , unittest.TestCase ): A__ : List[Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : Optional[Any] = LayoutLMvaImageProcessingTester(self ) @property def lowerCAmelCase( self : Dict ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''apply_ocr''' ) ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def lowerCAmelCase( self : str ): """simple docstring""" pass def lowerCAmelCase( self : Dict ): """simple docstring""" # Initialize image_processing snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image ) # Test not batched input snake_case : Optional[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , UpperCAmelCase__ ) self.assertIsInstance(encoding.boxes , UpperCAmelCase__ ) # Test batched snake_case : Dict = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" # Initialize image_processing snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray ) # 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 : List[Any] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" # Initialize image_processing snake_case : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , 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 : Tuple = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" # with apply_OCR = True snake_case : int = LayoutLMvaImageProcessor() from datasets import load_dataset snake_case : List[Any] = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) snake_case : List[Any] = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) snake_case : Any = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 snake_case : Optional[Any] = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 snake_case : Union[str, Any] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , UpperCAmelCase__ ) self.assertListEqual(encoding.boxes , UpperCAmelCase__ ) # with apply_OCR = False snake_case : str = LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase__ ) snake_case : Optional[Any] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
84
0
from sklearn.metrics import matthews_corrcoef import datasets _a : Optional[Any] = '\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction. The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n' _a : List[str] = '\nArgs:\n predictions (list of int): Predicted labels, as returned by a model.\n references (list of int): Ground truth labels.\n sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n Example 1, a basic example with only predictions and references as inputs:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.54\n\n Example 2, the same example as above, but also including sample weights:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 3, 1, 1, 1, 2])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.1\n\n Example 3, the same example as above, but with sample weights that cause a negative correlation:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 1, 0, 0, 0, 1])\n >>> print(round(results[\'matthews_correlation\'], 2))\n -0.25\n' _a : Optional[Any] = '\\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' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : Tuple ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html''' ] , ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[Any]=None ): """simple docstring""" return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sample_weight=SCREAMING_SNAKE_CASE_ ) ), }
719
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _a : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name _a : Dict = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def a_ ( __magic_name__ , __magic_name__ , __magic_name__=8 ) -> str: """simple docstring""" snake_case : List[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 snake_case : Tuple = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a_ ( a ): def __init__( self : Optional[int] , UpperCAmelCase__ : UNetaDConditionModel , UpperCAmelCase__ : DDPMScheduler , UpperCAmelCase__ : VQModel , ): """simple docstring""" super().__init__() self.register_modules( unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , movq=UpperCAmelCase__ , ) snake_case : List[Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCAmelCase( self : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any ): """simple docstring""" if latents is None: snake_case : int = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) else: if latents.shape != shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}" ) snake_case : Optional[Any] = latents.to(UpperCAmelCase__ ) snake_case : List[Any] = latents * scheduler.init_noise_sigma return latents def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Optional[int]=0 ): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) snake_case : Union[str, Any] = torch.device(F"cuda:{gpu_id}" ) snake_case : Dict = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Any=0 ): """simple docstring""" if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) snake_case : Optional[int] = torch.device(F"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=UpperCAmelCase__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) snake_case : List[str] = None for cpu_offloaded_model in [self.unet, self.movq]: snake_case , snake_case : Optional[int] = cpu_offload_with_hook(UpperCAmelCase__ , UpperCAmelCase__ , prev_module_hook=UpperCAmelCase__ ) # We'll offload the last model manually. snake_case : Tuple = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(UpperCAmelCase__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase__ : torch.FloatTensor , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 100 , UpperCAmelCase__ : float = 4.0 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[torch.FloatTensor] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" snake_case : Optional[int] = self._execution_device snake_case : Union[str, Any] = guidance_scale > 1.0 if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : Any = torch.cat(UpperCAmelCase__ , dim=0 ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : Union[str, Any] = torch.cat(UpperCAmelCase__ , dim=0 ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : int = torch.cat(UpperCAmelCase__ , dim=0 ) snake_case : List[Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: snake_case : Dict = image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Optional[Any] = negative_image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Tuple = hint.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Optional[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase__ ) snake_case : List[str] = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase__ ) self.scheduler.set_timesteps(UpperCAmelCase__ , device=UpperCAmelCase__ ) snake_case : str = self.scheduler.timesteps snake_case : Optional[Any] = self.movq.config.latent_channels snake_case , snake_case : Optional[Any] = downscale_height_and_width(UpperCAmelCase__ , UpperCAmelCase__ , self.movq_scale_factor ) # create initial latent snake_case : Dict = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(UpperCAmelCase__ ) ): # expand the latents if we are doing classifier free guidance snake_case : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case : Optional[int] = {'''image_embeds''': image_embeds, '''hint''': hint} snake_case : Any = self.unet( sample=UpperCAmelCase__ , timestep=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , added_cond_kwargs=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , )[0] if do_classifier_free_guidance: snake_case , snake_case : Dict = noise_pred.split(latents.shape[1] , dim=1 ) snake_case , snake_case : Any = noise_pred.chunk(2 ) snake_case , snake_case : Dict = variance_pred.chunk(2 ) snake_case : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) snake_case : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): snake_case , snake_case : Tuple = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 snake_case : List[Any] = self.scheduler.step( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , generator=UpperCAmelCase__ , )[0] # post-processing snake_case : List[Any] = self.movq.decode(UpperCAmelCase__ , force_not_quantize=UpperCAmelCase__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: snake_case : Optional[Any] = image * 0.5 + 0.5 snake_case : int = image.clamp(0 , 1 ) snake_case : List[str] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": snake_case : str = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
84
0
from sklearn.metrics import mean_squared_error import datasets _a : List[Any] = """\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ _a : Dict = """\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. """ _a : Union[str, Any] = """ Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. \"raw_values\" : Returns a full set of errors in case of multioutput input. \"uniform_average\" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric(\"mse\") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {'mse': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {'mse': 0.6123724356957945} If you're using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {'mse': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {'mse': array([0.41666667, 1. ])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : int ): """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 lowerCAmelCase( self : Dict ): """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 lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : str="uniform_average" , UpperCAmelCase__ : List[str]=True ): """simple docstring""" snake_case : Optional[Any] = mean_squared_error( snake_case_ , snake_case_ , sample_weight=snake_case_ , multioutput=snake_case_ , squared=snake_case_ ) return {"mse": mse}
720
import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _a : List[Any] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class a_ ( a , unittest.TestCase ): A__ : Dict = ReformerTokenizer A__ : Optional[int] = ReformerTokenizerFast A__ : str = True A__ : Tuple = False A__ : str = True def lowerCAmelCase( self : List[Any] ): """simple docstring""" super().setUp() snake_case : str = ReformerTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : int = '''<s>''' snake_case : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''j''' ) self.assertEqual(len(UpperCAmelCase__ ) , 1_000 ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def lowerCAmelCase( self : Dict ): """simple docstring""" if not self.test_rust_tokenizer: return snake_case : Any = self.get_tokenizer() snake_case : str = self.get_rust_tokenizer() snake_case : Tuple = '''I was born in 92000, and this is falsé.''' snake_case : str = tokenizer.tokenize(UpperCAmelCase__ ) snake_case : int = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : Union[str, Any] = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) snake_case : List[str] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : List[str] = self.get_rust_tokenizer() snake_case : Optional[int] = tokenizer.encode(UpperCAmelCase__ ) snake_case : Optional[Any] = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : List[Any]=15 ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case : str = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) # Simple input snake_case : Union[str, Any] = '''This is a simple input''' snake_case : List[str] = ['''This is a simple input 1''', '''This is a simple input 2'''] snake_case : int = ('''This is a simple input''', '''This is a pair''') snake_case : int = [ ('''This is a simple input 1''', '''This is a simple input 2'''), ('''This is a simple pair 1''', '''This is a simple pair 2'''), ] # Simple input tests self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Simple input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Simple input self.assertRaises( UpperCAmelCase__ , tokenizer_r.batch_encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' , ) # Pair input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Pair input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Pair input self.assertRaises( UpperCAmelCase__ , tokenizer_r.batch_encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' , ) def lowerCAmelCase( self : str ): """simple docstring""" pass def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Union[str, Any] = ReformerTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) snake_case : List[str] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [285, 46, 10, 170, 382] , ) snake_case : int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) snake_case : int = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) snake_case : List[Any] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def lowerCAmelCase( self : Tuple ): """simple docstring""" return ReformerTokenizer.from_pretrained('''google/reformer-crime-and-punishment''' ) @slow def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Any = '''Hello World!''' snake_case : Optional[Any] = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @slow def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[Any] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) snake_case : Dict = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @require_torch @slow def lowerCAmelCase( self : List[Any] ): """simple docstring""" import torch from transformers import ReformerConfig, ReformerModel # Build sequence snake_case : Any = list(self.big_tokenizer.get_vocab().keys() )[:10] snake_case : Union[str, Any] = ''' '''.join(UpperCAmelCase__ ) snake_case : Optional[int] = self.big_tokenizer.encode_plus(UpperCAmelCase__ , return_tensors='''pt''' ) snake_case : List[str] = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors='''pt''' ) snake_case : Optional[Any] = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) snake_case : Tuple = encoded_sequence['''input_ids'''].shape snake_case : List[Any] = ReformerModel(UpperCAmelCase__ ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**UpperCAmelCase__ ) model(**UpperCAmelCase__ ) @slow def lowerCAmelCase( self : Optional[int] ): """simple docstring""" # fmt: off snake_case : Tuple = {'''input_ids''': [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 snake_case : Tuple = [ '''This is a very simple sentence.''', '''The quick brown fox jumps over the lazy dog.''', ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''google/reformer-crime-and-punishment''' , revision='''0e6c3decb8211d49bf881013425dc8b0448b3f5a''' , padding=UpperCAmelCase__ , sequences=UpperCAmelCase__ , )
84
0
import unittest from transformers import GPTNeoXJapaneseConfig, is_torch_available from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer from transformers.testing_utils import require_torch, slow, torch_device 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 GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel class a_ : def __init__( self : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any]=13 , UpperCAmelCase__ : Any=7 , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Tuple=99 , UpperCAmelCase__ : Optional[int]=32 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : List[Any]=4 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : Optional[Any]=0.0 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Any=512 , UpperCAmelCase__ : List[str]=16 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Optional[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : Optional[Any]=4 , UpperCAmelCase__ : Optional[int]=None , ): snake_case : Optional[int] = parent snake_case : Tuple = batch_size snake_case : Optional[int] = seq_length snake_case : Optional[Any] = is_training snake_case : Any = use_input_mask snake_case : Any = use_token_type_ids snake_case : Dict = use_labels snake_case : Any = vocab_size snake_case : int = hidden_size snake_case : List[Any] = num_hidden_layers snake_case : str = num_attention_heads snake_case : Optional[int] = intermediate_multiple_size snake_case : str = hidden_act snake_case : List[Any] = hidden_dropout snake_case : Tuple = attention_dropout snake_case : Optional[int] = weight_tying snake_case : List[Any] = max_position_embeddings snake_case : Union[str, Any] = type_vocab_size snake_case : Optional[int] = type_sequence_label_size snake_case : List[str] = initializer_range snake_case : List[Any] = num_labels snake_case : Union[str, Any] = num_choices snake_case : Union[str, Any] = scope def lowerCAmelCase( self : List[Any] ): snake_case : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case : Tuple = None if self.use_input_mask: snake_case : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case : Tuple = None if self.use_labels: snake_case : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case : Tuple = self.get_config() return config, input_ids, input_mask, token_labels def lowerCAmelCase( self : Union[str, Any] ): return GPTNeoXJapaneseConfig( 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_multiple_size=self.intermediate_multiple_size , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , weight_tying=self.weight_tying , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def lowerCAmelCase( self : Optional[Any] ): snake_case : Optional[int] = self.prepare_config_and_inputs() snake_case : Dict = True return config, input_ids, input_mask, token_labels def lowerCAmelCase( self : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ): snake_case : int = GPTNeoXJapaneseModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : List[Any] = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) snake_case : Optional[Any] = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict ): snake_case : str = True snake_case : Dict = GPTNeoXJapaneseModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : int = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] ): snake_case : int = GPTNeoXJapaneseForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : Union[str, Any] = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int ): snake_case : int = True snake_case : Optional[Any] = GPTNeoXJapaneseForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # first forward pass snake_case : Tuple = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) snake_case : Dict = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids snake_case : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) snake_case : Optional[Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and snake_case : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case : Union[str, Any] = torch.cat([input_mask, next_mask] , dim=-1 ) snake_case : List[Any] = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ ) snake_case : Any = output_from_no_past['''hidden_states'''][0] snake_case : Optional[int] = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , )['''hidden_states'''][0] # select random slice snake_case : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case : List[Any] = output_from_no_past[:, -3:, random_slice_idx].detach() snake_case : int = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) def lowerCAmelCase( self : Tuple ): snake_case : Optional[Any] = self.prepare_config_and_inputs() snake_case : Union[str, Any] = config_and_inputs snake_case : Optional[int] = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class a_ ( lowercase__ , lowercase__ , unittest.TestCase ): A__ : str = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else () A__ : Optional[int] = (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else () A__ : str = ( {'feature-extraction': GPTNeoXJapaneseModel, 'text-generation': GPTNeoXJapaneseForCausalLM} if is_torch_available() else {} ) A__ : str = False A__ : Tuple = False A__ : Dict = False A__ : Dict = False def lowerCAmelCase( self : Tuple ): snake_case : Union[str, Any] = GPTNeoXJapaneseModelTester(self ) snake_case : str = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37 ) def lowerCAmelCase( self : Any ): self.config_tester.run_common_tests() def lowerCAmelCase( self : int ): snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : Any ): snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple ): snake_case : Tuple = self.model_tester.prepare_config_and_inputs_for_decoder() snake_case : Any = None self.model_tester.create_and_check_model_as_decoder(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] ): snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : str ): snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*UpperCAmelCase__ ) @slow def lowerCAmelCase( self : int ): snake_case : Any = '''abeja/gpt-neox-japanese-2.7b''' snake_case : Optional[int] = ['''データサイエンティストとは、''', '''100年後に必要とされる会社は、''', '''フルリモートの環境で働くために必要なことは、''', '''国境の長いトンネルを抜けると''', '''美味しい日本食といえば、'''] snake_case : Any = [ '''データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。''', '''100年後に必要とされる会社は、「人」が中心の会社です。''', '''フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。''', '''国境の長いトンネルを抜けると、そこは雪国だった。''', '''美味しい日本食といえば、やっぱりお寿司ですよね。''', ] snake_case : Optional[int] = GPTNeoXJapaneseTokenizer.from_pretrained(UpperCAmelCase__ ) snake_case : List[Any] = GPTNeoXJapaneseForCausalLM.from_pretrained(UpperCAmelCase__ ) snake_case : List[str] = [] for prompt in prompts: snake_case : Optional[Any] = tokenizer(UpperCAmelCase__ , return_tensors='''pt''' ).input_ids snake_case : List[Any] = model.generate(UpperCAmelCase__ , max_length=50 ) snake_case : List[str] = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) predicted_outputs += generated_string self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
721
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" snake_case , snake_case : Any = image.size snake_case , snake_case : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 snake_case : List[str] = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) snake_case : Dict = np.array(__magic_name__ ).astype(np.floataa ) / 255.0 snake_case : Optional[Any] = image[None].transpose(0 , 3 , 1 , 2 ) snake_case : Tuple = torch.from_numpy(__magic_name__ ) return 2.0 * image - 1.0 class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : VQModel , UpperCAmelCase__ : UNetaDModel , UpperCAmelCase__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ): """simple docstring""" super().__init__() self.register_modules(vqvae=UpperCAmelCase__ , unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) @torch.no_grad() def __call__( self : Any , UpperCAmelCase__ : Union[torch.Tensor, PIL.Image.Image] = None , UpperCAmelCase__ : Optional[int] = 1 , UpperCAmelCase__ : Optional[int] = 100 , UpperCAmelCase__ : Optional[float] = 0.0 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" if isinstance(UpperCAmelCase__ , PIL.Image.Image ): snake_case : Optional[int] = 1 elif isinstance(UpperCAmelCase__ , torch.Tensor ): snake_case : Any = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(UpperCAmelCase__ )}" ) if isinstance(UpperCAmelCase__ , PIL.Image.Image ): snake_case : Optional[Any] = preprocess(UpperCAmelCase__ ) snake_case , snake_case : Union[str, Any] = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image snake_case : List[Any] = (batch_size, self.unet.config.in_channels // 2, height, width) snake_case : str = next(self.unet.parameters() ).dtype snake_case : Dict = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=self.device , dtype=UpperCAmelCase__ ) snake_case : Any = image.to(device=self.device , dtype=UpperCAmelCase__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(UpperCAmelCase__ , device=self.device ) snake_case : Optional[Any] = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler snake_case : Union[str, Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] snake_case : Any = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case : Optional[Any] = {} if accepts_eta: snake_case : Dict = eta for t in self.progress_bar(UpperCAmelCase__ ): # concat latents and low resolution image in the channel dimension. snake_case : Optional[int] = torch.cat([latents, image] , dim=1 ) snake_case : str = self.scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) # predict the noise residual snake_case : int = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case : Any = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample # decode the image latents with the VQVAE snake_case : Optional[int] = self.vqvae.decode(UpperCAmelCase__ ).sample snake_case : int = torch.clamp(UpperCAmelCase__ , -1.0 , 1.0 ) snake_case : Dict = image / 2 + 0.5 snake_case : int = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case : Any = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
84
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _a : int = logging.get_logger(__name__) _a : int = { 'studio-ousia/luke-base': 'https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json', 'studio-ousia/luke-large': 'https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json', } class a_ ( __UpperCAmelCase ): A__ : List[Any] = "luke" def __init__( self : Optional[int] , UpperCAmelCase__ : List[str]=50_267 , UpperCAmelCase__ : List[Any]=500_000 , UpperCAmelCase__ : int=768 , UpperCAmelCase__ : Tuple=256 , UpperCAmelCase__ : str=12 , UpperCAmelCase__ : Tuple=12 , UpperCAmelCase__ : Union[str, Any]=3_072 , UpperCAmelCase__ : List[str]="gelu" , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : Tuple=512 , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1e-1_2 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=1 , UpperCAmelCase__ : str=0 , UpperCAmelCase__ : List[Any]=2 , **UpperCAmelCase__ : Tuple , ): """simple docstring""" super().__init__(pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase ) snake_case : List[str] = vocab_size snake_case : Optional[int] = entity_vocab_size snake_case : str = hidden_size snake_case : Any = entity_emb_size snake_case : int = num_hidden_layers snake_case : Optional[Any] = num_attention_heads snake_case : int = hidden_act snake_case : Optional[Any] = intermediate_size snake_case : Optional[int] = hidden_dropout_prob snake_case : Optional[Any] = attention_probs_dropout_prob snake_case : Optional[int] = max_position_embeddings snake_case : List[Any] = type_vocab_size snake_case : List[Any] = initializer_range snake_case : List[Any] = layer_norm_eps snake_case : List[str] = use_entity_aware_attention snake_case : Union[str, Any] = classifier_dropout
700
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class a_ ( a ): def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = tempfile.mkdtemp() snake_case : Dict = 5 # Realm tok snake_case : str = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] snake_case : Tuple = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) snake_case : Any = os.path.join(UpperCAmelCase__ , 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 : Tuple = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def lowerCAmelCase( self : Any ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Any = RealmConfig(num_block_records=self.num_block_records ) return config def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[int] = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Dict = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=UpperCAmelCase__ , ) return block_records def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Tuple = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[str] = self.get_config() snake_case : Optional[Any] = self.get_dummy_retriever() snake_case : Optional[int] = retriever.tokenizer snake_case : Dict = np.array([0, 3] , dtype='''long''' ) snake_case : Optional[int] = tokenizer(['''Test question'''] ).input_ids snake_case : Union[str, Any] = tokenizer( ['''the fourth'''] , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ).input_ids snake_case : Optional[Any] = config.reader_seq_len snake_case , snake_case , snake_case , snake_case : List[str] = retriever( UpperCAmelCase__ , UpperCAmelCase__ , answer_ids=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors='''np''' ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = self.get_config() snake_case : Optional[int] = self.get_dummy_retriever() snake_case : List[str] = retriever.tokenizer snake_case : Optional[Any] = np.array([0, 3, 5] , dtype='''long''' ) snake_case : Optional[int] = tokenizer(['''Test question'''] ).input_ids snake_case : Any = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ).input_ids snake_case : List[Any] = config.reader_seq_len snake_case , snake_case , snake_case , snake_case : Union[str, Any] = retriever( UpperCAmelCase__ , UpperCAmelCase__ , answer_ids=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors='''np''' ) self.assertEqual([False, True, True] , UpperCAmelCase__ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , UpperCAmelCase__ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : int = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path snake_case : Optional[Any] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: snake_case : Any = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) snake_case : Any = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
84
0
import os def a_ ( ) -> Optional[Any]: """simple docstring""" snake_case : int = os.path.join(os.path.dirname(lowerCamelCase_ ) , '''num.txt''' ) with open(lowerCamelCase_ ) as file_hand: return str(sum(int(lowerCamelCase_ ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
701
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _a : str = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = ['EncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Dict = ['TFEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = ['FlaxEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys _a : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
84
0
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def a_ ( __magic_name__ ) -> tuple: """simple docstring""" return (data["data"], data["target"]) def a_ ( __magic_name__ , __magic_name__ ) -> XGBClassifier: """simple docstring""" snake_case : str = XGBClassifier() classifier.fit(UpperCamelCase__ , UpperCamelCase__ ) return classifier def a_ ( ) -> None: """simple docstring""" snake_case : Optional[Any] = load_iris() snake_case , snake_case : List[str] = data_handling(UpperCamelCase__ ) snake_case , snake_case , snake_case , snake_case : Dict = train_test_split( UpperCamelCase__ , UpperCamelCase__ , test_size=0.25 ) snake_case : Dict = iris['''target_names'''] # Create an XGBoost Classifier from the training data snake_case : Tuple = xgboost(UpperCamelCase__ , UpperCamelCase__ ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , display_labels=UpperCamelCase__ , cmap='''Blues''' , normalize='''true''' , ) plt.title('''Normalized Confusion Matrix - IRIS Dataset''' ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
702
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer _a : str = logging.get_logger(__name__) _a : Optional[int] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Optional[Any] = { 'vocab_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json' ), }, } _a : Union[str, Any] = { 'yjernite/retribert-base-uncased': 512, } _a : Tuple = { 'yjernite/retribert-base-uncased': {'do_lower_case': True}, } class a_ ( a ): A__ : List[str] = VOCAB_FILES_NAMES A__ : Any = PRETRAINED_VOCAB_FILES_MAP A__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Any = PRETRAINED_INIT_CONFIGURATION A__ : Optional[Any] = RetriBertTokenizer A__ : Any = ['input_ids', 'attention_mask'] def __init__( self : Optional[int] , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Dict="[UNK]" , UpperCAmelCase__ : str="[SEP]" , UpperCAmelCase__ : Union[str, Any]="[PAD]" , UpperCAmelCase__ : Dict="[CLS]" , UpperCAmelCase__ : Optional[Any]="[MASK]" , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=None , **UpperCAmelCase__ : Dict , ): """simple docstring""" super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , do_lower_case=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , tokenize_chinese_chars=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ , **UpperCAmelCase__ , ) snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCAmelCase__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCAmelCase__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCAmelCase__ ) != tokenize_chinese_chars ): snake_case : int = getattr(UpperCAmelCase__ , normalizer_state.pop('''type''' ) ) snake_case : List[Any] = do_lower_case snake_case : Union[str, Any] = strip_accents snake_case : int = tokenize_chinese_chars snake_case : int = normalizer_class(**UpperCAmelCase__ ) snake_case : Union[str, Any] = do_lower_case def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=None ): """simple docstring""" snake_case : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ): """simple docstring""" snake_case : List[Any] = [self.sep_token_id] snake_case : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ): """simple docstring""" snake_case : Tuple = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ )
84
0
import requests from bsa import BeautifulSoup def a_ ( __magic_name__ = "https://www.worldometers.info/coronavirus" ) -> Any: """simple docstring""" snake_case : int = BeautifulSoup(requests.get(__SCREAMING_SNAKE_CASE ).text , '''html.parser''' ) snake_case : List[str] = soup.findAll('''h1''' ) snake_case : List[Any] = soup.findAll('''div''' , {'''class''': '''maincounter-number'''} ) keys += soup.findAll('''span''' , {'''class''': '''panel-title'''} ) values += soup.findAll('''div''' , {'''class''': '''number-table-main'''} ) return {key.text.strip(): value.text.strip() for key, value in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(f"{key}\n{value}\n")
703
import string import numpy def a_ ( __magic_name__ , __magic_name__ ) -> int: """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , __magic_name__ ) class a_ : A__ : List[Any] = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) A__ : List[str] = numpy.vectorize(lambda a : x % 36 ) A__ : Dict = numpy.vectorize(a ) def __init__( self : List[str] , UpperCAmelCase__ : numpy.ndarray ): """simple docstring""" snake_case : int = self.modulus(UpperCAmelCase__ ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key snake_case : List[str] = encrypt_key.shape[0] def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : str ): """simple docstring""" return self.key_string.index(UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : int ): """simple docstring""" return self.key_string[round(UpperCAmelCase__ )] def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: snake_case : Tuple = det % len(self.key_string ) snake_case : Tuple = len(self.key_string ) if greatest_common_divisor(UpperCAmelCase__ , len(self.key_string ) ) != 1: snake_case : List[Any] = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[int] = [char for char in text.upper() if char in self.key_string] snake_case : Optional[int] = chars[-1] while len(UpperCAmelCase__ ) % self.break_key != 0: chars.append(UpperCAmelCase__ ) return "".join(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[int] = self.process_text(text.upper() ) snake_case : Optional[int] = '''''' for i in range(0 , len(UpperCAmelCase__ ) - self.break_key + 1 , self.break_key ): snake_case : int = text[i : i + self.break_key] snake_case : int = [self.replace_letters(UpperCAmelCase__ ) for char in batch] snake_case : Tuple = numpy.array([vec] ).T snake_case : Optional[Any] = self.modulus(self.encrypt_key.dot(UpperCAmelCase__ ) ).T.tolist()[ 0 ] snake_case : Dict = ''''''.join( self.replace_digits(UpperCAmelCase__ ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Optional[int] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: snake_case : int = det % len(self.key_string ) snake_case : Dict = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: snake_case : Any = i break snake_case : Any = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(UpperCAmelCase__ ) ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Any = self.make_decrypt_key() snake_case : Optional[Any] = self.process_text(text.upper() ) snake_case : int = '''''' for i in range(0 , len(UpperCAmelCase__ ) - self.break_key + 1 , self.break_key ): snake_case : Any = text[i : i + self.break_key] snake_case : int = [self.replace_letters(UpperCAmelCase__ ) for char in batch] snake_case : List[str] = numpy.array([vec] ).T snake_case : Optional[Any] = self.modulus(decrypt_key.dot(UpperCAmelCase__ ) ).T.tolist()[0] snake_case : int = ''''''.join( self.replace_digits(UpperCAmelCase__ ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def a_ ( ) -> None: """simple docstring""" snake_case : Any = int(input('''Enter the order of the encryption key: ''' ) ) snake_case : List[Any] = [] print('''Enter each row of the encryption key with space separated integers''' ) for _ in range(__magic_name__ ): snake_case : Optional[Any] = [int(__magic_name__ ) for x in input().split()] hill_matrix.append(__magic_name__ ) snake_case : List[str] = HillCipher(numpy.array(__magic_name__ ) ) print('''Would you like to encrypt or decrypt some text? (1 or 2)''' ) snake_case : int = input('''\n1. Encrypt\n2. Decrypt\n''' ) if option == "1": snake_case : List[Any] = input('''What text would you like to encrypt?: ''' ) print('''Your encrypted text is:''' ) print(hc.encrypt(__magic_name__ ) ) elif option == "2": snake_case : int = input('''What text would you like to decrypt?: ''' ) print('''Your decrypted text is:''' ) print(hc.decrypt(__magic_name__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
84
0
import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def a_ ( __magic_name__ ) -> Optional[Any]: """simple docstring""" snake_case : int = [ '''decoder.version''', '''decoder.output_projection.weight''', '''_float_tensor''', '''decoder.embed_positions._float_tensor''', ] for k in ignore_keys: state_dict.pop(__magic_name__ , __magic_name__ ) def a_ ( __magic_name__ ) -> int: """simple docstring""" snake_case , snake_case : Optional[int] = emb.weight.shape snake_case : Optional[int] = nn.Linear(__magic_name__ , __magic_name__ , bias=__magic_name__ ) snake_case : Optional[Any] = emb.weight.data return lin_layer def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" snake_case : Tuple = torch.load(__magic_name__ , map_location='''cpu''' ) snake_case : Union[str, Any] = Namespace(**checkpoint['''cfg''']['''model'''] ) snake_case : Optional[Any] = checkpoint['''model'''] remove_ignore_keys_(__magic_name__ ) snake_case : Optional[int] = state_dict['''decoder.embed_tokens.weight'''].shape[0] snake_case : str = {key.replace('''decoder''' , '''model''' ): val for key, val in state_dict.items()} snake_case : List[Any] = XGLMConfig( vocab_size=__magic_name__ , max_position_embeddings=args.max_target_positions , num_layers=args.decoder_layers , attention_heads=args.decoder_attention_heads , ffn_dim=args.decoder_ffn_embed_dim , d_model=args.decoder_embed_dim , layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='''gelu''' , scale_embedding=not args.no_scale_embedding , tie_word_embeddings=args.share_decoder_input_output_embed , ) snake_case : Optional[int] = XGLMForCausalLM(__magic_name__ ) snake_case : int = model.load_state_dict(__magic_name__ , strict=__magic_name__ ) print(__magic_name__ ) snake_case : Tuple = make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": _a : int = 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.') _a : Optional[int] = parser.parse_args() _a : Dict = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
704
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class a_ ( a ): A__ : List[Any] = 'Salesforce/blip-image-captioning-base' A__ : Dict = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) A__ : str = 'image_captioner' A__ : Dict = AutoModelForVisionaSeq A__ : Optional[Any] = ['image'] A__ : List[str] = ['text'] def __init__( self : List[str] , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : "Image" ): """simple docstring""" return self.pre_processor(images=UpperCAmelCase__ , return_tensors='''pt''' ) def lowerCAmelCase( self : Any , UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" return self.model.generate(**UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : List[Any] ): """simple docstring""" return self.pre_processor.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ )[0].strip()
84
0
'''simple docstring''' import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _a : Any = logging.get_logger(__name__) # pylint: disable=invalid-name def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''' , _lowerCamelCase , ) if isinstance(_lowerCamelCase , torch.Tensor ): return image elif isinstance(_lowerCamelCase , PIL.Image.Image ): snake_case : int = [image] if isinstance(image[0] , PIL.Image.Image ): snake_case : Union[str, Any] = image[0].size snake_case : List[Any] = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 snake_case : Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] snake_case : Dict = np.concatenate(_lowerCamelCase , axis=0 ) snake_case : Any = np.array(_lowerCamelCase ).astype(np.floataa ) / 255.0 snake_case : Union[str, Any] = image.transpose(0 , 3 , 1 , 2 ) snake_case : Optional[int] = 2.0 * image - 1.0 snake_case : List[str] = torch.from_numpy(_lowerCamelCase ) elif isinstance(image[0] , torch.Tensor ): snake_case : Dict = torch.cat(_lowerCamelCase , dim=0 ) return image def a_ ( __magic_name__ ) -> Optional[int]: """simple docstring""" if isinstance(_lowerCamelCase , torch.Tensor ): return mask elif isinstance(_lowerCamelCase , PIL.Image.Image ): snake_case : Any = [mask] if isinstance(mask[0] , PIL.Image.Image ): snake_case : Optional[int] = mask[0].size snake_case : List[Any] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 snake_case : List[str] = [np.array(m.convert('''L''' ).resize((w, h) , resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] snake_case : Dict = np.concatenate(_lowerCamelCase , axis=0 ) snake_case : Any = mask.astype(np.floataa ) / 255.0 snake_case : List[str] = 0 snake_case : Dict = 1 snake_case : List[Any] = torch.from_numpy(_lowerCamelCase ) elif isinstance(mask[0] , torch.Tensor ): snake_case : Optional[Any] = torch.cat(_lowerCamelCase , dim=0 ) return mask class a_ ( __lowercase ): A__ : Tuple = 42 A__ : str = 42 def __init__( self : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ): """simple docstring""" super().__init__() self.register_modules(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) @torch.no_grad() def __call__( self : Union[str, Any] , UpperCAmelCase__ : Union[torch.Tensor, PIL.Image.Image] , UpperCAmelCase__ : Union[torch.Tensor, PIL.Image.Image] , UpperCAmelCase__ : int = 250 , UpperCAmelCase__ : float = 0.0 , UpperCAmelCase__ : int = 10 , UpperCAmelCase__ : int = 10 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" snake_case : Tuple = image snake_case : Optional[Any] = _preprocess_image(UpperCAmelCase__ ) snake_case : Optional[int] = original_image.to(device=self.device , dtype=self.unet.dtype ) snake_case : Dict = _preprocess_mask(UpperCAmelCase__ ) snake_case : Any = mask_image.to(device=self.device , dtype=self.unet.dtype ) snake_case : str = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and len(UpperCAmelCase__ ) != batch_size: raise ValueError( F"You have passed a list of generators of length {len(UpperCAmelCase__ )}, but requested an effective batch" F" size of {batch_size}. Make sure the batch size matches the length of the generators." ) snake_case : List[str] = original_image.shape snake_case : List[Any] = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , self.device ) snake_case : Tuple = eta snake_case : List[str] = self.scheduler.timesteps[0] + 1 snake_case : str = generator[0] if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual snake_case : Union[str, Any] = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample # compute previous image: x_t -> x_t-1 snake_case : Tuple = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ).prev_sample else: # compute the reverse: x_t-1 -> x_t snake_case : List[str] = self.scheduler.undo_step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : Dict = t snake_case : Union[str, Any] = (image / 2 + 0.5).clamp(0 , 1 ) snake_case : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case : str = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
705
def a_ ( __magic_name__ ) -> bool: """simple docstring""" if p < 2: raise ValueError('''p should not be less than 2!''' ) elif p == 2: return True snake_case : int = 4 snake_case : Optional[Any] = (1 << p) - 1 for _ in range(p - 2 ): snake_case : Optional[Any] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
84
0
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class a_ ( a ): A__ : Any = 'EncodecFeatureExtractor' A__ : Tuple = ('T5Tokenizer', 'T5TokenizerFast') def __init__( self : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple ): """simple docstring""" super().__init__(__UpperCamelCase , __UpperCamelCase ) snake_case : Dict = self.feature_extractor snake_case : List[Any] = False def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=True ): """simple docstring""" return self.tokenizer.get_decoder_prompt_ids(task=__UpperCamelCase , language=__UpperCamelCase , no_timestamps=__UpperCamelCase ) def __call__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : Tuple ): """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*__UpperCamelCase , **__UpperCamelCase ) snake_case : List[str] = kwargs.pop('''audio''' , __UpperCamelCase ) snake_case : List[Any] = kwargs.pop('''sampling_rate''' , __UpperCamelCase ) snake_case : Any = kwargs.pop('''text''' , __UpperCamelCase ) if len(__UpperCamelCase ) > 0: snake_case : Union[str, Any] = args[0] snake_case : Optional[Any] = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if text is not None: snake_case : Tuple = self.tokenizer(__UpperCamelCase , **__UpperCamelCase ) if audio is not None: snake_case : Tuple = self.feature_extractor(__UpperCamelCase , *__UpperCamelCase , sampling_rate=__UpperCamelCase , **__UpperCamelCase ) if audio is None: return inputs elif text is None: return audio_inputs else: snake_case : str = audio_inputs['''input_values'''] if "padding_mask" in audio_inputs: snake_case : List[str] = audio_inputs['''padding_mask'''] return inputs def lowerCAmelCase( self : Any , *UpperCAmelCase__ : Tuple , **UpperCAmelCase__ : Dict ): """simple docstring""" snake_case : Optional[Any] = kwargs.pop('''audio''' , __UpperCamelCase ) snake_case : List[str] = kwargs.pop('''padding_mask''' , __UpperCamelCase ) if len(__UpperCamelCase ) > 0: snake_case : Dict = args[0] snake_case : Dict = args[1:] if audio_values is not None: return self._decode_audio(__UpperCamelCase , padding_mask=__UpperCamelCase ) else: return self.tokenizer.batch_decode(*__UpperCamelCase , **__UpperCamelCase ) def lowerCAmelCase( self : str , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" return self.tokenizer.decode(*__UpperCamelCase , **__UpperCamelCase ) def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional = None ): """simple docstring""" snake_case : int = to_numpy(__UpperCamelCase ) snake_case , snake_case , snake_case : List[str] = audio_values.shape if padding_mask is None: return list(__UpperCamelCase ) snake_case : int = to_numpy(__UpperCamelCase ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) snake_case : Union[str, Any] = seq_len - padding_mask.shape[-1] snake_case : int = 1 - self.feature_extractor.padding_value snake_case : Dict = np.pad(__UpperCamelCase , ((0, 0), (0, difference)) , '''constant''' , constant_values=__UpperCamelCase ) snake_case : List[Any] = audio_values.tolist() for i in range(__UpperCamelCase ): snake_case : Union[str, Any] = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] snake_case : Optional[int] = sliced_audio.reshape(__UpperCamelCase , -1 ) return audio_values
706
from sklearn.metrics import fa_score import datasets _a : List[str] = '\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n' _a : Dict = '\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {\'f1\': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results[\'f1\'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results[\'f1\'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")\n >>> print(round(results[\'f1\'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {\'f1\': array([0.8, 0. , 0. ])}\n' _a : List[Any] = '\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' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : Any ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'''] , ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : List[str]="binary" , UpperCAmelCase__ : str=None ): """simple docstring""" snake_case : List[Any] = fa_score( UpperCAmelCase__ , UpperCAmelCase__ , labels=UpperCAmelCase__ , pos_label=UpperCAmelCase__ , average=UpperCAmelCase__ , sample_weight=UpperCAmelCase__ ) return {"f1": float(UpperCAmelCase__ ) if score.size == 1 else score}
84
0
import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class a_ ( unittest.TestCase ): @property def lowerCAmelCase( self : Tuple ): """simple docstring""" torch.manual_seed(0 ) snake_case : Dict = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : int = self.dummy_uncond_unet snake_case : int = PNDMScheduler() snake_case : int = PNDMPipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pndm.to(UpperCAmelCase__ ) pndm.set_progress_bar_config(disable=UpperCAmelCase__ ) snake_case : Dict = torch.manual_seed(0 ) snake_case : Dict = pndm(generator=UpperCAmelCase__ , num_inference_steps=20 , output_type='''numpy''' ).images snake_case : int = torch.manual_seed(0 ) snake_case : Optional[Any] = pndm(generator=UpperCAmelCase__ , num_inference_steps=20 , output_type='''numpy''' , return_dict=UpperCAmelCase__ )[0] snake_case : int = image[0, -3:, -3:, -1] snake_case : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) snake_case : Union[str, Any] = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class a_ ( unittest.TestCase ): def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : Optional[Any] = """google/ddpm-cifar10-32""" snake_case : Optional[Any] = UNetaDModel.from_pretrained(UpperCAmelCase__ ) snake_case : List[Any] = PNDMScheduler() snake_case : List[str] = PNDMPipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pndm.to(UpperCAmelCase__ ) pndm.set_progress_bar_config(disable=UpperCAmelCase__ ) snake_case : Tuple = torch.manual_seed(0 ) snake_case : Optional[int] = pndm(generator=UpperCAmelCase__ , output_type='''numpy''' ).images snake_case : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) snake_case : Any = np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
707
def a_ ( __magic_name__ ) -> int: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ): raise TypeError('''only integers accepted as input''' ) else: snake_case : str = str(abs(__magic_name__ ) ) snake_case : Optional[Any] = [list(__magic_name__ ) for char in range(len(__magic_name__ ) )] for index in range(len(__magic_name__ ) ): num_transpositions[index].pop(__magic_name__ ) return max( int(''''''.join(list(__magic_name__ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
84
0
from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class a_ ( __A ): def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : Any = SMALL_MODEL_IDENTIFIER snake_case : List[Any] = 'pt' snake_case : Tuple = 'tf' def lowerCAmelCase( self : str , UpperCAmelCase__ : int ): """simple docstring""" snake_case : Dict = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(UpperCamelCase__ ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : List[str] ): """simple docstring""" snake_case : int = TFAutoModel.from_pretrained(self.test_model , from_pt=UpperCamelCase__ ) model_tf.save_pretrained(UpperCamelCase__ ) def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Union[str, Any] = 'mock_framework' # Framework provided - return whatever the user provides snake_case : Union[str, Any] = FeaturesManager.determine_framework(self.test_model , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(UpperCamelCase__ ) snake_case : Dict = FeaturesManager.determine_framework(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(UpperCamelCase__ ) snake_case : List[str] = FeaturesManager.determine_framework(UpperCamelCase__ , UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowerCAmelCase( self : List[str] ): """simple docstring""" # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(UpperCamelCase__ ) snake_case : Optional[Any] = FeaturesManager.determine_framework(UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(UpperCamelCase__ ) snake_case : Union[str, Any] = FeaturesManager.determine_framework(UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(UpperCamelCase__ ): snake_case : Any = FeaturesManager.determine_framework(UpperCamelCase__ ) def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[Any] = MagicMock(return_value=UpperCamelCase__ ) with patch('''transformers.onnx.features.is_tf_available''' , UpperCamelCase__ ): snake_case : str = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(UpperCamelCase__ , self.framework_pt ) # PyTorch not in environment -> use TensorFlow snake_case : List[str] = MagicMock(return_value=UpperCamelCase__ ) with patch('''transformers.onnx.features.is_torch_available''' , UpperCamelCase__ ): snake_case : Optional[Any] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(UpperCamelCase__ , self.framework_tf ) # Both in environment -> use PyTorch snake_case : Union[str, Any] = MagicMock(return_value=UpperCamelCase__ ) snake_case : Tuple = MagicMock(return_value=UpperCamelCase__ ) with patch('''transformers.onnx.features.is_tf_available''' , UpperCamelCase__ ), patch( '''transformers.onnx.features.is_torch_available''' , UpperCamelCase__ ): snake_case : Union[str, Any] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(UpperCamelCase__ , self.framework_pt ) # Both not in environment -> raise error snake_case : Tuple = MagicMock(return_value=UpperCamelCase__ ) snake_case : Any = MagicMock(return_value=UpperCamelCase__ ) with patch('''transformers.onnx.features.is_tf_available''' , UpperCamelCase__ ), patch( '''transformers.onnx.features.is_torch_available''' , UpperCamelCase__ ): with self.assertRaises(UpperCamelCase__ ): snake_case : Optional[int] = FeaturesManager.determine_framework(self.test_model )
708
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class a_ : def __init__( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any]=99 , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Any=9 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : Tuple=32 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=37 , UpperCAmelCase__ : Union[str, Any]=8 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : str=0.002 , UpperCAmelCase__ : str=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : Union[str, Any]=0 , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=None , ): """simple docstring""" snake_case : Union[str, Any] = parent snake_case : Union[str, Any] = batch_size snake_case : Any = encoder_seq_length snake_case : str = decoder_seq_length # For common tests snake_case : Optional[int] = self.decoder_seq_length snake_case : Optional[Any] = is_training snake_case : List[Any] = use_attention_mask snake_case : Union[str, Any] = use_labels snake_case : Any = vocab_size snake_case : Optional[int] = hidden_size snake_case : List[str] = num_hidden_layers snake_case : Union[str, Any] = num_attention_heads snake_case : Any = d_ff snake_case : Any = relative_attention_num_buckets snake_case : Optional[Any] = dropout_rate snake_case : int = initializer_factor snake_case : Optional[Any] = eos_token_id snake_case : Dict = pad_token_id snake_case : Optional[Any] = decoder_start_token_id snake_case : Union[str, Any] = None snake_case : List[str] = decoder_layers def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return TaConfig.from_pretrained('''google/umt5-base''' ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=None , ): """simple docstring""" if attention_mask is None: snake_case : Union[str, Any] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: snake_case : Any = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: snake_case : List[Any] = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=UpperCAmelCase__ ) if decoder_head_mask is None: snake_case : Tuple = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=UpperCAmelCase__ ) if cross_attn_head_mask is None: snake_case : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=UpperCAmelCase__ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input snake_case : List[str] = input_ids.clamp(self.pad_token_id + 1 ) snake_case : List[str] = decoder_input_ids.clamp(self.pad_token_id + 1 ) snake_case : str = self.get_config() snake_case : Tuple = config.num_attention_heads snake_case : List[Any] = self.prepare_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, input_dict def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : List[str] = self.prepare_config_and_inputs() return config, inputs_dict def lowerCAmelCase( self : Dict ): """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def lowerCAmelCase( self : Tuple ): """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , ): """simple docstring""" snake_case : str = UMTaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : str = model( input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , ) snake_case : int = model(input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ ) snake_case : int = result.last_hidden_state snake_case : Dict = result.past_key_values snake_case : Dict = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(UpperCAmelCase__ ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , ): """simple docstring""" snake_case : int = UMTaModel(config=UpperCAmelCase__ ).get_decoder().to(UpperCAmelCase__ ).eval() # first forward pass snake_case : List[Any] = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) snake_case : List[Any] = model(UpperCAmelCase__ ) snake_case : Any = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) self.parent.assertTrue(len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) ) self.parent.assertTrue(len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) + 1 ) snake_case , snake_case : List[str] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids snake_case : Any = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and snake_case : Union[str, Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case : Any = model(UpperCAmelCase__ )['''last_hidden_state'''] snake_case : Optional[Any] = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )['''last_hidden_state'''] # select random slice snake_case : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() snake_case : Tuple = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , ): """simple docstring""" snake_case : int = UMTaModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).half().eval() snake_case : str = model(**UpperCAmelCase__ )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(UpperCAmelCase__ ).any().item() ) @require_torch class a_ ( a , a , a , unittest.TestCase ): A__ : str = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) A__ : str = (UMTaForConditionalGeneration,) if is_torch_available() else () A__ : Any = ( { 'conversational': UMTaForConditionalGeneration, 'feature-extraction': UMTaModel, 'summarization': UMTaForConditionalGeneration, 'text2text-generation': UMTaForConditionalGeneration, 'translation': UMTaForConditionalGeneration, 'question-answering': UMTaForQuestionAnswering, } if is_torch_available() else {} ) A__ : Dict = True A__ : List[str] = False A__ : Optional[int] = False A__ : Optional[int] = True A__ : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests A__ : int = [0.8, 0.9] def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Union[str, Any] = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Tuple = self.model_tester.prepare_config_and_inputs() snake_case : Optional[Any] = UMTaModel(config_and_inputs[0] ).to(UpperCAmelCase__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( UpperCAmelCase__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=UpperCAmelCase__ , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : Optional[int] = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() snake_case : int = config_and_inputs[0] snake_case : Union[str, Any] = UMTaForConditionalGeneration(UpperCAmelCase__ ).eval() model.to(UpperCAmelCase__ ) snake_case : str = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=UpperCAmelCase__ ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ), } for attn_name, (name, mask) in zip(UpperCAmelCase__ , head_masking.items() ): snake_case : int = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": snake_case : List[str] = torch.ones( config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ) snake_case : Union[str, Any] = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=UpperCAmelCase__ , return_dict_in_generate=UpperCAmelCase__ , **UpperCAmelCase__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step snake_case : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def lowerCAmelCase( self : Any ): """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class a_ ( unittest.TestCase ): @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[Any] = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=UpperCAmelCase__ ).to(UpperCAmelCase__ ) snake_case : int = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=UpperCAmelCase__ , legacy=UpperCAmelCase__ ) snake_case : List[str] = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] snake_case : Dict = tokenizer(UpperCAmelCase__ , return_tensors='''pt''' , padding=UpperCAmelCase__ ).input_ids # fmt: off snake_case : Optional[Any] = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : List[Any] = model.generate(input_ids.to(UpperCAmelCase__ ) ) snake_case : int = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] snake_case : Tuple = tokenizer.batch_decode(UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
84
0
import unittest from transformers import RoFormerTokenizer, RoFormerTokenizerFast from transformers.testing_utils import require_rjieba, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_rjieba @require_tokenizers class a_ ( a__ , unittest.TestCase ): A__ : Tuple = RoFormerTokenizer A__ : Tuple = RoFormerTokenizerFast A__ : Optional[Any] = True A__ : int = True def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" super().setUp() def lowerCAmelCase( self : int , **UpperCAmelCase__ : Optional[Any] ): """simple docstring""" return self.tokenizer_class.from_pretrained('''junnyu/roformer_chinese_base''' , **lowerCamelCase_ ) def lowerCAmelCase( self : Any , **UpperCAmelCase__ : Optional[Any] ): """simple docstring""" return self.rust_tokenizer_class.from_pretrained('''junnyu/roformer_chinese_base''' , **lowerCamelCase_ ) def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : str = '''永和服装饰品有限公司,今天天气非常好''' snake_case : Optional[int] = '''永和 服装 饰品 有限公司 , 今 天 天 气 非常 好''' return input_text, output_text def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Union[str, Any] = self.get_tokenizer() snake_case , snake_case : List[Any] = self.get_chinese_input_output_texts() snake_case : Optional[Any] = tokenizer.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , output_text.split() ) snake_case : int = tokens + [tokenizer.unk_token] snake_case : Optional[int] = [22_943, 21_332, 34_431, 45_904, 117, 306, 1_231, 1_231, 2_653, 33_994, 1_266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , lowerCamelCase_ ) def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Optional[Any] = self.get_rust_tokenizer() snake_case , snake_case : Union[str, Any] = self.get_chinese_input_output_texts() snake_case : Any = tokenizer.tokenize(lowerCamelCase_ ) self.assertListEqual(lowerCamelCase_ , output_text.split() ) snake_case : Union[str, Any] = tokens + [tokenizer.unk_token] snake_case : Any = [22_943, 21_332, 34_431, 45_904, 117, 306, 1_231, 1_231, 2_653, 33_994, 1_266, 100] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase_ ) , lowerCamelCase_ ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" pass def lowerCAmelCase( self : int ): """simple docstring""" pass def lowerCAmelCase( self : str ): """simple docstring""" pass
709
import torch from diffusers import DiffusionPipeline class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): """simple docstring""" super().__init__() self.register_modules(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) def __call__( self : Optional[int] ): """simple docstring""" snake_case : Any = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) snake_case : Dict = 1 snake_case : Optional[Any] = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample snake_case : List[Any] = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ).prev_sample snake_case : List[Any] = scheduler_output - scheduler_output + torch.ones_like(UpperCAmelCase__ ) return result
84
0
import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class a_ ( lowercase_ ): def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Union[str, Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCamelCase__ , '''hidden_sizes''' ) ) self.parent.assertTrue(hasattr(UpperCamelCase__ , '''neck_hidden_sizes''' ) ) self.parent.assertTrue(hasattr(UpperCamelCase__ , '''num_attention_heads''' ) ) class a_ : def __init__( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple=13 , UpperCAmelCase__ : Any=32 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Optional[Any]=3 , UpperCAmelCase__ : Union[str, Any]=640 , UpperCAmelCase__ : Optional[Any]=4 , UpperCAmelCase__ : Optional[int]="silu" , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : str=32 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Union[str, Any]=0.02 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : str=10 , UpperCAmelCase__ : List[str]=None , ): """simple docstring""" snake_case : Any = parent snake_case : str = batch_size snake_case : Optional[int] = image_size snake_case : int = patch_size snake_case : Tuple = num_channels snake_case : int = last_hidden_size snake_case : Optional[int] = num_attention_heads snake_case : List[Any] = hidden_act snake_case : List[Any] = conv_kernel_size snake_case : Optional[int] = output_stride snake_case : Any = hidden_dropout_prob snake_case : List[Any] = attention_probs_dropout_prob snake_case : Tuple = classifier_dropout_prob snake_case : Union[str, Any] = use_labels snake_case : Optional[Any] = is_training snake_case : int = num_labels snake_case : Dict = initializer_range snake_case : Tuple = scope def lowerCAmelCase( self : int ): """simple docstring""" snake_case : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case : Union[str, Any] = None snake_case : List[str] = None if self.use_labels: snake_case : Dict = ids_tensor([self.batch_size] , self.num_labels ) snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case : str = self.get_config() return config, pixel_values, labels, pixel_labels def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def lowerCAmelCase( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" snake_case : Union[str, Any] = MobileViTModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() snake_case : Optional[int] = model(UpperCamelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int ): """simple docstring""" snake_case : Tuple = self.num_labels snake_case : List[str] = MobileViTForImageClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() snake_case : List[Any] = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[str] ): """simple docstring""" snake_case : Optional[Any] = self.num_labels snake_case : str = MobileViTForSemanticSegmentation(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() snake_case : Tuple = model(UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) snake_case : Dict = model(UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Dict = self.prepare_config_and_inputs() snake_case , snake_case , snake_case , snake_case : str = config_and_inputs snake_case : List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class a_ ( lowercase_ , lowercase_ , unittest.TestCase ): A__ : Optional[int] = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) A__ : List[str] = ( { '''feature-extraction''': MobileViTModel, '''image-classification''': MobileViTForImageClassification, '''image-segmentation''': MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) A__ : int = False A__ : int = False A__ : Optional[int] = False A__ : List[str] = False def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Union[str, Any] = MobileViTModelTester(self ) snake_case : Optional[Any] = MobileViTConfigTester(self , config_class=UpperCamelCase__ , has_text_modality=UpperCamelCase__ ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViT does not use inputs_embeds''' ) def lowerCAmelCase( self : Any ): """simple docstring""" pass @unittest.skip(reason='''MobileViT does not support input and output embeddings''' ) def lowerCAmelCase( self : List[str] ): """simple docstring""" pass @unittest.skip(reason='''MobileViT does not output attentions''' ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" pass def lowerCAmelCase( self : List[Any] ): """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 : int = model_class(UpperCamelCase__ ) snake_case : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case : List[Any] = [*signature.parameters.keys()] snake_case : Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCamelCase__ ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def lowerCAmelCase( self : List[str] ): """simple docstring""" pass def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" def check_hidden_states_output(UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ): snake_case : Union[str, Any] = model_class(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() with torch.no_grad(): snake_case : Any = model(**self._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ ) ) snake_case : List[Any] = outputs.hidden_states snake_case : Dict = 5 self.assertEqual(len(UpperCamelCase__ ) , UpperCamelCase__ ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. snake_case : List[str] = 2 for i in range(len(UpperCamelCase__ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) snake_case , snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Dict = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case : Union[str, Any] = True check_hidden_states_output(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__ ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__ ) @slow def lowerCAmelCase( self : List[Any] ): """simple docstring""" for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : Union[str, Any] = MobileViTModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) def a_ ( ) -> Optional[Any]: """simple docstring""" snake_case : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): @cached_property def lowerCAmelCase( self : List[Any] ): """simple docstring""" return MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small''' ) if is_vision_available() else None @slow def lowerCAmelCase( self : str ): """simple docstring""" snake_case : str = MobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small''' ).to(UpperCamelCase__ ) snake_case : Union[str, Any] = self.default_image_processor snake_case : List[str] = prepare_img() snake_case : Tuple = image_processor(images=UpperCamelCase__ , return_tensors='''pt''' ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): snake_case : Optional[Any] = model(**UpperCamelCase__ ) # verify the logits snake_case : Tuple = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase__ ) snake_case : Dict = torch.tensor([-1.9364, -1.2327, -0.4653] ).to(UpperCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Union[str, Any] = MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) snake_case : Union[str, Any] = model.to(UpperCamelCase__ ) snake_case : Optional[int] = MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) snake_case : Union[str, Any] = prepare_img() snake_case : Union[str, Any] = image_processor(images=UpperCamelCase__ , return_tensors='''pt''' ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): snake_case : int = model(**UpperCamelCase__ ) snake_case : Optional[Any] = outputs.logits # verify the logits snake_case : str = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , UpperCamelCase__ ) snake_case : Any = torch.tensor( [ [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]], [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]], [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]], ] , device=UpperCamelCase__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCamelCase__ , atol=1e-4 ) ) @slow def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : List[Any] = MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) snake_case : Any = model.to(UpperCamelCase__ ) snake_case : Tuple = MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''' ) snake_case : Optional[int] = prepare_img() snake_case : Optional[Any] = image_processor(images=UpperCamelCase__ , return_tensors='''pt''' ).to(UpperCamelCase__ ) # forward pass with torch.no_grad(): snake_case : Any = model(**UpperCamelCase__ ) snake_case : Dict = outputs.logits.detach().cpu() snake_case : str = image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ , target_sizes=[(50, 60)] ) snake_case : Optional[int] = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , UpperCamelCase__ ) snake_case : Any = image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ ) snake_case : Optional[Any] = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , UpperCamelCase__ )
710
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a_ ( a ): A__ : List[str] = ['image_processor', 'tokenizer'] A__ : Any = 'CLIPImageProcessor' A__ : Optional[int] = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : Union[str, Any] , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , UpperCAmelCase__ , ) snake_case : List[Any] = kwargs.pop('''feature_extractor''' ) snake_case : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(UpperCAmelCase__ , UpperCAmelCase__ ) def __call__( self : Any , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: snake_case : int = self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if images is not None: snake_case : Dict = self.image_processor(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if text is not None and images is not None: snake_case : Tuple = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase__ ) , tensor_type=UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : int ): """simple docstring""" return self.tokenizer.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : str ): """simple docstring""" return self.tokenizer.decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : int = self.tokenizer.model_input_names snake_case : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , UpperCAmelCase__ , ) return self.image_processor_class @property def lowerCAmelCase( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , UpperCAmelCase__ , ) return self.image_processor
84
0
'''simple docstring''' def a_ ( __magic_name__ = 100 ) -> int: """simple docstring""" snake_case : int = set() snake_case : Optional[Any] = 0 snake_case : int = n + 1 # maximum limit for a in range(2 , __lowerCAmelCase ): for b in range(2 , __lowerCAmelCase ): snake_case : List[str] = a**b # calculates the current power collect_powers.add(__lowerCAmelCase ) # adds the result to the set return len(__lowerCAmelCase ) if __name__ == "__main__": print('Number of terms ', solution(int(str(input()).strip())))
711
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _a : Optional[Any] = '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n' _a : str = '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n' _a : List[Any] = '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: "c" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric(\'mauve\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : Any ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/krishnap25/mauve''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/krishnap25/mauve'''] , reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] , ) def lowerCAmelCase( self : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : List[str]="auto" , UpperCAmelCase__ : Tuple=-1 , UpperCAmelCase__ : Optional[int]=0.9 , UpperCAmelCase__ : List[Any]=5 , UpperCAmelCase__ : List[Any]=500 , UpperCAmelCase__ : Union[str, Any]="gpt2-large" , UpperCAmelCase__ : Optional[Any]=-1 , UpperCAmelCase__ : int=1_024 , UpperCAmelCase__ : List[Any]=25 , UpperCAmelCase__ : Union[str, Any]=5 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[Any]=25 , ): """simple docstring""" snake_case : List[str] = compute_mauve( p_text=UpperCAmelCase__ , q_text=UpperCAmelCase__ , p_features=UpperCAmelCase__ , q_features=UpperCAmelCase__ , p_tokens=UpperCAmelCase__ , q_tokens=UpperCAmelCase__ , num_buckets=UpperCAmelCase__ , pca_max_data=UpperCAmelCase__ , kmeans_explained_var=UpperCAmelCase__ , kmeans_num_redo=UpperCAmelCase__ , kmeans_max_iter=UpperCAmelCase__ , featurize_model_name=UpperCAmelCase__ , device_id=UpperCAmelCase__ , max_text_length=UpperCAmelCase__ , divergence_curve_discretization_size=UpperCAmelCase__ , mauve_scaling_factor=UpperCAmelCase__ , verbose=UpperCAmelCase__ , seed=UpperCAmelCase__ , ) return out
84
0
def a_ ( __magic_name__ = 50_000_000 ) -> int: """simple docstring""" snake_case : str = set() snake_case : Optional[int] = int((limit - 24) ** (1 / 2) ) snake_case : List[str] = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , a_ ) ) ) for primea in primes: snake_case : int = primea * primea for primea in primes: snake_case : Tuple = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: snake_case : Optional[Any] = primea * primea * primea * primea snake_case : List[str] = square + cube + tetr if total >= limit: break ret.add(a_ ) return len(a_ ) if __name__ == "__main__": print(f"{solution() = }")
712
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" if "cls_token" in name: snake_case : Tuple = name.replace('''cls_token''' , '''vit.embeddings.cls_token''' ) if "mask_token" in name: snake_case : Optional[int] = name.replace('''mask_token''' , '''decoder.mask_token''' ) if "decoder_pos_embed" in name: snake_case : List[str] = name.replace('''decoder_pos_embed''' , '''decoder.decoder_pos_embed''' ) if "pos_embed" in name and "decoder" not in name: snake_case : List[str] = name.replace('''pos_embed''' , '''vit.embeddings.position_embeddings''' ) if "patch_embed.proj" in name: snake_case : List[Any] = name.replace('''patch_embed.proj''' , '''vit.embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: snake_case : int = name.replace('''patch_embed.norm''' , '''vit.embeddings.norm''' ) if "decoder_blocks" in name: snake_case : int = name.replace('''decoder_blocks''' , '''decoder.decoder_layers''' ) if "blocks" in name: snake_case : Optional[Any] = name.replace('''blocks''' , '''vit.encoder.layer''' ) if "attn.proj" in name: snake_case : str = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: snake_case : Any = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: snake_case : List[str] = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: snake_case : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: snake_case : Tuple = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: snake_case : Tuple = name.replace('''mlp.fc2''' , '''output.dense''' ) if "decoder_embed" in name: snake_case : Dict = name.replace('''decoder_embed''' , '''decoder.decoder_embed''' ) if "decoder_norm" in name: snake_case : Dict = name.replace('''decoder_norm''' , '''decoder.decoder_norm''' ) if "decoder_pred" in name: snake_case : Dict = name.replace('''decoder_pred''' , '''decoder.decoder_pred''' ) if "norm.weight" in name and "decoder" not in name: snake_case : Optional[int] = name.replace('''norm.weight''' , '''vit.layernorm.weight''' ) if "norm.bias" in name and "decoder" not in name: snake_case : List[str] = name.replace('''norm.bias''' , '''vit.layernorm.bias''' ) return name def a_ ( __magic_name__ , __magic_name__ ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): snake_case : Union[str, Any] = orig_state_dict.pop(__magic_name__ ) if "qkv" in key: snake_case : Optional[int] = key.split('''.''' ) snake_case : int = int(key_split[1] ) if "decoder_blocks" in key: snake_case : List[str] = config.decoder_hidden_size snake_case : List[Any] = '''decoder.decoder_layers.''' if "weight" in key: snake_case : str = val[:dim, :] snake_case : Optional[Any] = val[dim : dim * 2, :] snake_case : Any = val[-dim:, :] elif "bias" in key: snake_case : Optional[Any] = val[:dim] snake_case : List[Any] = val[dim : dim * 2] snake_case : List[Any] = val[-dim:] else: snake_case : Optional[int] = config.hidden_size snake_case : Tuple = '''vit.encoder.layer.''' if "weight" in key: snake_case : Optional[Any] = val[:dim, :] snake_case : str = val[dim : dim * 2, :] snake_case : Union[str, Any] = val[-dim:, :] elif "bias" in key: snake_case : Tuple = val[:dim] snake_case : int = val[dim : dim * 2] snake_case : Optional[Any] = val[-dim:] else: snake_case : Optional[Any] = val return orig_state_dict def a_ ( __magic_name__ , __magic_name__ ) -> Any: """simple docstring""" snake_case : List[str] = ViTMAEConfig() if "large" in checkpoint_url: snake_case : str = 1_024 snake_case : Tuple = 4_096 snake_case : Optional[Any] = 24 snake_case : List[Any] = 16 elif "huge" in checkpoint_url: snake_case : Tuple = 14 snake_case : int = 1_280 snake_case : Dict = 5_120 snake_case : Tuple = 32 snake_case : Optional[Any] = 16 snake_case : Optional[Any] = ViTMAEForPreTraining(__magic_name__ ) snake_case : Optional[Any] = torch.hub.load_state_dict_from_url(__magic_name__ , map_location='''cpu''' )['''model'''] snake_case : int = ViTMAEImageProcessor(size=config.image_size ) snake_case : Dict = convert_state_dict(__magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ ) model.eval() snake_case : Tuple = '''https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg''' snake_case : List[Any] = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) snake_case : Dict = ViTMAEImageProcessor(size=config.image_size ) snake_case : str = image_processor(images=__magic_name__ , return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) snake_case : Union[str, Any] = model(**__magic_name__ ) snake_case : Optional[Any] = outputs.logits if "large" in checkpoint_url: snake_case : Any = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] ) elif "huge" in checkpoint_url: snake_case : List[Any] = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] ) else: snake_case : Dict = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , __magic_name__ , atol=1e-4 ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__magic_name__ ) if __name__ == "__main__": _a : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) _a : str = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
84
0
_a : Dict = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '&': '.-...', '@': '.--.-.', ':': '---...', ',': '--..--', '.': '.-.-.-', '\'': '.----.', '"': '.-..-.', '?': '..--..', '/': '-..-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '(': '-.--.', ')': '-.--.-', '!': '-.-.--', ' ': '/' } # Exclamation mark is not in ITU-R recommendation # fmt: on _a : List[Any] = {value: key for key, value in MORSE_CODE_DICT.items()} def a_ ( __magic_name__ ) -> Optional[int]: """simple docstring""" return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def a_ ( __magic_name__ ) -> Optional[Any]: """simple docstring""" return "".join(REVERSE_DICT[char] for char in message.split() ) def a_ ( ) -> List[Any]: """simple docstring""" snake_case : Optional[int] = '''Morse code here!''' print(UpperCAmelCase__ ) snake_case : Tuple = encrypt(UpperCAmelCase__ ) print(UpperCAmelCase__ ) snake_case : Any = decrypt(UpperCAmelCase__ ) print(UpperCAmelCase__ ) if __name__ == "__main__": main()
713
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _a : Optional[Any] = 16 _a : Union[str, Any] = 32 def a_ ( __magic_name__ , __magic_name__ = 16 ) -> Dict: """simple docstring""" snake_case : Tuple = AutoTokenizer.from_pretrained('''bert-base-cased''' ) snake_case : Any = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__magic_name__ ): # max_length=None => use the model max length (it's actually the default) snake_case : Union[str, Any] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__magic_name__ , max_length=__magic_name__ ) 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( __magic_name__ , batched=__magic_name__ , 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(__magic_name__ ): # On TPU it's best to pad everything to the same length or training will be very slow. snake_case : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": snake_case : Tuple = 16 elif accelerator.mixed_precision != "no": snake_case : Dict = 8 else: snake_case : Union[str, Any] = None return tokenizer.pad( __magic_name__ , padding='''longest''' , max_length=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_tensors='''pt''' , ) # Instantiate dataloaders. snake_case : str = DataLoader( tokenized_datasets['''train'''] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) snake_case : List[str] = DataLoader( tokenized_datasets['''validation'''] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders _a : Optional[int] = mocked_dataloaders # noqa: F811 def a_ ( __magic_name__ , __magic_name__ ) -> Optional[Any]: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , __magic_name__ ) == "1": snake_case : Optional[int] = 2 # Initialize accelerator snake_case : 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 : Dict = config['''lr'''] snake_case : Any = int(config['''num_epochs'''] ) snake_case : List[str] = int(config['''seed'''] ) snake_case : List[Any] = int(config['''batch_size'''] ) snake_case : Tuple = evaluate.load('''glue''' , '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=__magic_name__ ) def inner_training_loop(__magic_name__ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(__magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) snake_case : str = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=__magic_name__ ) # 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 : Optional[int] = model.to(accelerator.device ) # Instantiate optimizer snake_case : Optional[int] = AdamW(params=model.parameters() , lr=__magic_name__ ) snake_case , snake_case : List[Any] = get_dataloaders(__magic_name__ , __magic_name__ ) # Instantiate scheduler snake_case : int = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=100 , num_training_steps=(len(__magic_name__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. snake_case , snake_case , snake_case , snake_case , snake_case : Tuple = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # Now we train the model for epoch in range(__magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) snake_case : int = model(**__magic_name__ ) snake_case : Optional[int] = outputs.loss accelerator.backward(__magic_name__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): snake_case : List[str] = model(**__magic_name__ ) snake_case : List[Any] = outputs.logits.argmax(dim=-1 ) snake_case , snake_case : Dict = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) snake_case : Tuple = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , __magic_name__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def a_ ( ) -> Union[str, Any]: """simple docstring""" snake_case : int = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=__magic_name__ , default=__magic_name__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) snake_case : Optional[Any] = parser.parse_args() snake_case : Optional[int] = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
84
0
import os from pathlib import Path def a_ ( ) -> Dict: """simple docstring""" from torch.utils.cpp_extension import load snake_case : int = Path(UpperCAmelCase__ ).resolve().parent.parent.parent / '''kernels''' / '''deformable_detr''' snake_case : Dict = [ root / filename for filename in [ '''vision.cpp''', os.path.join('''cpu''' , '''ms_deform_attn_cpu.cpp''' ), os.path.join('''cuda''' , '''ms_deform_attn_cuda.cu''' ), ] ] load( '''MultiScaleDeformableAttention''' , UpperCAmelCase__ , with_cuda=UpperCAmelCase__ , extra_include_paths=[str(UpperCAmelCase__ )] , extra_cflags=['''-DWITH_CUDA=1'''] , extra_cuda_cflags=[ '''-DCUDA_HAS_FP16=1''', '''-D__CUDA_NO_HALF_OPERATORS__''', '''-D__CUDA_NO_HALF_CONVERSIONS__''', '''-D__CUDA_NO_HALF2_OPERATORS__''', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
714
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract _a : Dict = logging.get_logger(__name__) def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> List[Any]: """simple docstring""" return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def a_ ( __magic_name__ , __magic_name__ , __magic_name__ = None ) -> str: """simple docstring""" snake_case : Any = tesseract_config if tesseract_config is not None else '''''' # apply OCR snake_case : str = to_pil_image(__magic_name__ ) snake_case , snake_case : Union[str, Any] = pil_image.size snake_case : List[Any] = pytesseract.image_to_data(__magic_name__ , lang=__magic_name__ , output_type='''dict''' , config=__magic_name__ ) snake_case , snake_case , snake_case , snake_case , snake_case : Optional[Any] = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates snake_case : Union[str, Any] = [idx for idx, word in enumerate(__magic_name__ ) if not word.strip()] snake_case : Union[str, Any] = [word for idx, word in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : Optional[Any] = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] snake_case : int = [coord for idx, coord in enumerate(__magic_name__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format snake_case : List[Any] = [] for x, y, w, h in zip(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ): snake_case : Optional[int] = [x, y, x + w, y + h] actual_boxes.append(__magic_name__ ) # finally, normalize the bounding boxes snake_case : List[Any] = [] for box in actual_boxes: normalized_boxes.append(normalize_box(__magic_name__ , __magic_name__ , __magic_name__ ) ) assert len(__magic_name__ ) == len(__magic_name__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class a_ ( a ): A__ : int = ['pixel_values'] def __init__( self : Optional[int] , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = "" , **UpperCAmelCase__ : int , ): """simple docstring""" super().__init__(**UpperCAmelCase__ ) snake_case : Any = size if size is not None else {'''height''': 224, '''width''': 224} snake_case : Tuple = get_size_dict(UpperCAmelCase__ ) snake_case : Dict = do_resize snake_case : str = size snake_case : Optional[int] = resample snake_case : Union[str, Any] = apply_ocr snake_case : int = ocr_lang snake_case : Union[str, Any] = tesseract_config def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Dict[str, int] , UpperCAmelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Any , ): """simple docstring""" snake_case : Dict = get_size_dict(UpperCAmelCase__ ) 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(UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Dict[str, int] = None , UpperCAmelCase__ : PILImageResampling = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : List[Any] , ): """simple docstring""" snake_case : Tuple = do_resize if do_resize is not None else self.do_resize snake_case : List[Any] = size if size is not None else self.size snake_case : Tuple = get_size_dict(UpperCAmelCase__ ) snake_case : str = resample if resample is not None else self.resample snake_case : Optional[int] = apply_ocr if apply_ocr is not None else self.apply_ocr snake_case : Any = ocr_lang if ocr_lang is not None else self.ocr_lang snake_case : Optional[int] = tesseract_config if tesseract_config is not None else self.tesseract_config snake_case : List[str] = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) # All transformations expect numpy arrays. snake_case : Any = [to_numpy_array(UpperCAmelCase__ ) for image in images] if apply_ocr: requires_backends(self , '''pytesseract''' ) snake_case : Optional[int] = [] snake_case : Union[str, Any] = [] for image in images: snake_case , snake_case : List[Any] = apply_tesseract(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) words_batch.append(UpperCAmelCase__ ) boxes_batch.append(UpperCAmelCase__ ) if do_resize: snake_case : Any = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) snake_case : int = [flip_channel_order(UpperCAmelCase__ ) for image in images] snake_case : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] snake_case : List[Any] = BatchFeature(data={'''pixel_values''': images} , tensor_type=UpperCAmelCase__ ) if apply_ocr: snake_case : Dict = words_batch snake_case : Dict = boxes_batch return data
84
0
'''simple docstring''' from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch('''socket.socket''' ) @patch('''builtins.open''' ) def a_ ( __magic_name__ , __magic_name__ ) -> Optional[Any]: """simple docstring""" snake_case : int = Mock() snake_case : List[str] = conn, Mock() snake_case : Optional[int] = iter([1, None] ) snake_case : Any = lambda __magic_name__ : next(_UpperCamelCase ) # ===== invoke ===== send_file(filename='''mytext.txt''' , testing=_UpperCamelCase ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
715
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class a_ : def __init__( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any]=13 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : List[Any]=24 , UpperCAmelCase__ : Union[str, Any]=16 , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : int=32 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : Optional[int]=37 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Optional[int]=10 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : Optional[Any]=2 , ): """simple docstring""" snake_case : Tuple = parent snake_case : Dict = batch_size snake_case : str = patch_size snake_case : Union[str, Any] = max_length snake_case : str = num_mel_bins snake_case : Any = is_training snake_case : Union[str, Any] = use_labels snake_case : Tuple = hidden_size snake_case : Dict = num_hidden_layers snake_case : Any = num_attention_heads snake_case : Any = intermediate_size snake_case : List[Any] = hidden_act snake_case : str = hidden_dropout_prob snake_case : str = attention_probs_dropout_prob snake_case : str = type_sequence_label_size snake_case : Optional[int] = initializer_range snake_case : str = scope snake_case : int = frequency_stride snake_case : Union[str, Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) snake_case : Optional[int] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 snake_case : Any = (self.max_length - self.patch_size) // self.time_stride + 1 snake_case : Union[str, Any] = frequency_out_dimension * time_out_dimension snake_case : Union[str, Any] = num_patches + 2 def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Optional[int] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) snake_case : str = None if self.use_labels: snake_case : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case : List[str] = self.get_config() return config, input_values, labels def lowerCAmelCase( self : Any ): """simple docstring""" return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def lowerCAmelCase( self : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : str = ASTModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : Any = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : int = self.prepare_config_and_inputs() ( ( snake_case ) , ( snake_case ) , ( snake_case ) , ) : int = config_and_inputs snake_case : Tuple = {'''input_values''': input_values} return config, inputs_dict @require_torch class a_ ( a , a , unittest.TestCase ): A__ : List[Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) A__ : int = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) A__ : Optional[Any] = False A__ : Dict = False A__ : int = False A__ : Optional[int] = False def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int ): """simple docstring""" if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[int] = ASTModelTester(self ) snake_case : Optional[int] = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=37 ) def lowerCAmelCase( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def lowerCAmelCase( self : Tuple ): """simple docstring""" pass def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Optional[Any] = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case : Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , nn.Linear ) ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case : Any = model_class(UpperCAmelCase__ ) snake_case : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case : str = [*signature.parameters.keys()] snake_case : List[str] = ['''input_values'''] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) @slow def lowerCAmelCase( self : List[str] ): """simple docstring""" for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : List[str] = ASTModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def a_ ( ) -> Dict: """simple docstring""" snake_case : Dict = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) snake_case , snake_case : int = torchaudio.load(__magic_name__ ) return audio, sampling_rate @require_torch @require_torchaudio class a_ ( unittest.TestCase ): @cached_property def lowerCAmelCase( self : Any ): """simple docstring""" return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : List[str] = self.default_feature_extractor snake_case : str = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(UpperCAmelCase__ ) snake_case : str = self.default_feature_extractor snake_case , snake_case : int = prepare_audio() snake_case : Optional[int] = audio.squeeze().numpy() snake_case : Optional[Any] = feature_extractor(UpperCAmelCase__ , sampling_rate=UpperCAmelCase__ , return_tensors='''pt''' ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): snake_case : Union[str, Any] = model(**UpperCAmelCase__ ) # verify the logits snake_case : Any = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) snake_case : str = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1e-4 ) )
84
0
def a_ ( __magic_name__ = 1_000_000 ) -> List[str]: """simple docstring""" snake_case : Union[str, Any] = 1 snake_case : int = 1 snake_case : Union[str, Any] = {1: 1} for inputa in range(2 , __magic_name__ ): snake_case : int = 0 snake_case : List[Any] = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: snake_case : int = (3 * number) + 1 counter += 1 if inputa not in counters: snake_case : List[Any] = counter if counter > pre_counter: snake_case : Optional[int] = inputa snake_case : str = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
716
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process _a : Union[str, Any] = logging.getLogger(__name__) def a_ ( __magic_name__ , __magic_name__ ) -> Optional[int]: """simple docstring""" return (preds == labels).mean() @dataclass class a_ : A__ : str = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) A__ : Optional[str] = field( default=a , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class a_ : A__ : str = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys() )} ) A__ : str = field(metadata={'help': 'Should contain the data files for the task.'} ) A__ : int = field( default=128 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) A__ : bool = field( default=a , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def a_ ( ) -> Dict: """simple docstring""" snake_case : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) snake_case , snake_case , snake_case : Tuple = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"Output directory ({training_args.output_dir}) already exists and is not empty. Use" ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , __magic_name__ ) # Set seed set_seed(training_args.seed ) try: snake_case : int = processors[data_args.task_name]() snake_case : List[str] = processor.get_labels() snake_case : str = len(__magic_name__ ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case : List[Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__magic_name__ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) snake_case : str = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) snake_case : Any = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=__magic_name__ , cache_dir=model_args.cache_dir , ) # Get datasets snake_case : Optional[int] = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) snake_case : Any = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=__magic_name__ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(__magic_name__ ) -> Dict: snake_case : str = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(__magic_name__ , p.label_ids )} # Data collator snake_case : Dict = DataCollatorWithPadding(__magic_name__ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer snake_case : List[Any] = Trainer( model=__magic_name__ , args=__magic_name__ , train_dataset=__magic_name__ , eval_dataset=__magic_name__ , compute_metrics=__magic_name__ , data_collator=__magic_name__ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation snake_case : Optional[int] = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) snake_case : Optional[Any] = trainer.evaluate() snake_case : Union[str, Any] = os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_master(): with open(__magic_name__ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''' , __magic_name__ , __magic_name__ ) writer.write('''%s = %s\n''' % (key, value) ) results.update(__magic_name__ ) return results def a_ ( __magic_name__ ) -> List[Any]: """simple docstring""" main() if __name__ == "__main__": main()
84
0
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class a_ ( __lowerCAmelCase ): A__ : List[Any] = (DEISMultistepScheduler,) A__ : Union[str, Any] = (("num_inference_steps", 25),) def lowerCAmelCase( self : str , **UpperCAmelCase__ : Any ): """simple docstring""" snake_case : int = { '''num_train_timesteps''': 1_000, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''solver_order''': 2, } config.update(**lowerCamelCase__ ) return config def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : List[Any]=0 , **UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Optional[Any] = dict(self.forward_default_kwargs ) snake_case : Optional[Any] = kwargs.pop('''num_inference_steps''' , lowerCamelCase__ ) snake_case : Optional[Any] = self.dummy_sample snake_case : Dict = 0.1 * sample snake_case : List[str] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: snake_case : Optional[int] = self.get_scheduler_config(**lowerCamelCase__ ) snake_case : Optional[int] = scheduler_class(**lowerCamelCase__ ) scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residuals snake_case : Optional[Any] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase__ ) snake_case : int = scheduler_class.from_pretrained(lowerCamelCase__ ) new_scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residuals snake_case : Tuple = dummy_past_residuals[: new_scheduler.config.solver_order] snake_case : List[Any] = sample, sample for t in range(lowerCamelCase__ , time_step + scheduler.config.solver_order + 1 ): snake_case : Optional[int] = scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample snake_case : Dict = new_scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowerCAmelCase( self : Dict ): """simple docstring""" pass def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Dict=0 , **UpperCAmelCase__ : Any ): """simple docstring""" snake_case : Union[str, Any] = dict(self.forward_default_kwargs ) snake_case : str = kwargs.pop('''num_inference_steps''' , lowerCamelCase__ ) snake_case : Optional[Any] = self.dummy_sample snake_case : Dict = 0.1 * sample snake_case : Any = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: snake_case : Dict = self.get_scheduler_config() snake_case : Optional[int] = scheduler_class(**lowerCamelCase__ ) scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residuals (must be after setting timesteps) snake_case : Any = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase__ ) snake_case : str = scheduler_class.from_pretrained(lowerCamelCase__ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residual (must be after setting timesteps) snake_case : Union[str, Any] = dummy_past_residuals[: new_scheduler.config.solver_order] snake_case : List[Any] = scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample snake_case : int = new_scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : Tuple=None , **UpperCAmelCase__ : int ): """simple docstring""" if scheduler is None: snake_case : str = self.scheduler_classes[0] snake_case : Any = self.get_scheduler_config(**lowerCamelCase__ ) snake_case : int = scheduler_class(**lowerCamelCase__ ) snake_case : Any = self.scheduler_classes[0] snake_case : Union[str, Any] = self.get_scheduler_config(**lowerCamelCase__ ) snake_case : str = scheduler_class(**lowerCamelCase__ ) snake_case : List[str] = 10 snake_case : List[Any] = self.dummy_model() snake_case : Optional[int] = self.dummy_sample_deter scheduler.set_timesteps(lowerCamelCase__ ) for i, t in enumerate(scheduler.timesteps ): snake_case : str = model(lowerCamelCase__ , lowerCamelCase__ ) snake_case : Dict = scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ).prev_sample return sample def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[str] = dict(self.forward_default_kwargs ) snake_case : Union[str, Any] = kwargs.pop('''num_inference_steps''' , lowerCamelCase__ ) for scheduler_class in self.scheduler_classes: snake_case : Any = self.get_scheduler_config() snake_case : Any = scheduler_class(**lowerCamelCase__ ) snake_case : Union[str, Any] = self.dummy_sample snake_case : str = 0.1 * sample if num_inference_steps is not None and hasattr(lowerCamelCase__ , '''set_timesteps''' ): scheduler.set_timesteps(lowerCamelCase__ ) elif num_inference_steps is not None and not hasattr(lowerCamelCase__ , '''set_timesteps''' ): snake_case : Any = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) snake_case : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.10] snake_case : Dict = dummy_past_residuals[: scheduler.config.solver_order] snake_case : Any = scheduler.timesteps[5] snake_case : str = scheduler.timesteps[6] snake_case : Any = scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample snake_case : Union[str, Any] = scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Optional[Any] = DEISMultistepScheduler(**self.get_scheduler_config() ) snake_case : Any = self.full_loop(scheduler=lowerCamelCase__ ) snake_case : Tuple = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1e-3 snake_case : Dict = DPMSolverSinglestepScheduler.from_config(scheduler.config ) snake_case : Optional[int] = DPMSolverMultistepScheduler.from_config(scheduler.config ) snake_case : Union[str, Any] = UniPCMultistepScheduler.from_config(scheduler.config ) snake_case : Any = DEISMultistepScheduler.from_config(scheduler.config ) snake_case : Union[str, Any] = self.full_loop(scheduler=lowerCamelCase__ ) snake_case : Optional[Any] = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1e-3 def lowerCAmelCase( self : Dict ): """simple docstring""" for timesteps in [25, 50, 100, 999, 1_000]: self.check_over_configs(num_train_timesteps=lowerCamelCase__ ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" self.check_over_configs(thresholding=lowerCamelCase__ ) for order in [1, 2, 3]: for solver_type in ["logrho"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=lowerCamelCase__ , prediction_type=lowerCamelCase__ , sample_max_value=lowerCamelCase__ , algorithm_type='''deis''' , solver_order=lowerCamelCase__ , solver_type=lowerCamelCase__ , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowerCamelCase__ ) def lowerCAmelCase( self : Tuple ): """simple docstring""" for algorithm_type in ["deis"]: for solver_type in ["logrho"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=lowerCamelCase__ , solver_type=lowerCamelCase__ , prediction_type=lowerCamelCase__ , algorithm_type=lowerCamelCase__ , ) snake_case : Tuple = self.full_loop( solver_order=lowerCamelCase__ , solver_type=lowerCamelCase__ , prediction_type=lowerCamelCase__ , algorithm_type=lowerCamelCase__ , ) assert not torch.isnan(lowerCamelCase__ ).any(), "Samples have nan numbers" def lowerCAmelCase( self : str ): """simple docstring""" self.check_over_configs(lower_order_final=lowerCamelCase__ ) self.check_over_configs(lower_order_final=lowerCamelCase__ ) def lowerCAmelCase( self : Tuple ): """simple docstring""" for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1_000]: self.check_over_forward(num_inference_steps=lowerCamelCase__ , time_step=0 ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Tuple = self.full_loop() snake_case : List[Any] = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.2_3916 ) < 1e-3 def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Dict = self.full_loop(prediction_type='''v_prediction''' ) snake_case : List[Any] = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_mean.item() - 0.091 ) < 1e-3 def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : Dict = self.scheduler_classes[0] snake_case : Optional[int] = self.get_scheduler_config(thresholding=lowerCamelCase__ , dynamic_thresholding_ratio=0 ) snake_case : Dict = scheduler_class(**lowerCamelCase__ ) snake_case : str = 10 snake_case : Union[str, Any] = self.dummy_model() snake_case : Dict = self.dummy_sample_deter.half() scheduler.set_timesteps(lowerCamelCase__ ) for i, t in enumerate(scheduler.timesteps ): snake_case : Dict = model(lowerCamelCase__ , lowerCamelCase__ ) snake_case : Optional[int] = scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ).prev_sample assert sample.dtype == torch.floataa
717
import re def a_ ( __magic_name__ ) -> bool: """simple docstring""" snake_case : List[str] = re.compile( R'''^(?:0|94|\+94|0{2}94)''' R'''7(0|1|2|4|5|6|7|8)''' R'''(-| |)''' R'''\d{7}$''' ) return bool(re.search(__magic_name__ , __magic_name__ ) ) if __name__ == "__main__": _a : Any = '0094702343221' print(is_sri_lankan_phone_number(phone))
84
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class a_ ( unittest.TestCase ): def __init__( self : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Dict=30 , UpperCAmelCase__ : Union[str, Any]=400 , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : str=0.9 , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : List[Any]=[0.5, 0.5, 0.5] , UpperCAmelCase__ : int=[0.5, 0.5, 0.5] , ): """simple docstring""" snake_case : Optional[Any] = size if size is not None else {'''shortest_edge''': 30} snake_case : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 30, '''width''': 30} snake_case : List[str] = parent snake_case : Optional[Any] = batch_size snake_case : str = num_channels snake_case : Any = min_resolution snake_case : Optional[int] = max_resolution snake_case : Dict = do_resize_and_center_crop snake_case : Optional[Any] = size snake_case : List[Any] = crop_pct snake_case : List[str] = crop_size snake_case : List[str] = do_normalize snake_case : Dict = image_mean snake_case : Tuple = image_std def lowerCAmelCase( self : Any ): """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class a_ ( UpperCamelCase_ , unittest.TestCase ): A__ : Any = PoolFormerImageProcessor if is_vision_available() else None def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Any = PoolFormerImageProcessingTester(self ) @property def lowerCAmelCase( self : str ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize_and_center_crop''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''crop_pct''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_normalize''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_mean''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''image_std''' ) ) def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 30} ) self.assertEqual(image_processor.crop_size , {'''height''': 30, '''width''': 30} ) snake_case : Any = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" pass def lowerCAmelCase( self : str ): """simple docstring""" # Initialize image_processing snake_case : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image ) # Test not batched input snake_case : Optional[int] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case : List[Any] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCAmelCase( self : Dict ): """simple docstring""" # Initialize image_processing snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray ) # Test not batched input snake_case : List[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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case : int = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def lowerCAmelCase( self : Dict ): """simple docstring""" # Initialize image_processing snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , torch.Tensor ) # Test not batched input snake_case : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case : Any = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
718
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class a_ ( unittest.TestCase ): def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : int=18 , UpperCAmelCase__ : Optional[int]=30 , UpperCAmelCase__ : Optional[int]=400 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : int=True , ): """simple docstring""" snake_case : int = size if size is not None else {'''height''': 18, '''width''': 18} snake_case : Optional[Any] = parent snake_case : Any = batch_size snake_case : Any = num_channels snake_case : Union[str, Any] = image_size snake_case : Dict = min_resolution snake_case : Dict = max_resolution snake_case : int = do_resize snake_case : List[str] = size snake_case : List[Any] = apply_ocr def lowerCAmelCase( self : int ): """simple docstring""" return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class a_ ( a , unittest.TestCase ): A__ : List[Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : Optional[Any] = LayoutLMvaImageProcessingTester(self ) @property def lowerCAmelCase( self : Dict ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase__ , '''do_resize''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''size''' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , '''apply_ocr''' ) ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Optional[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) snake_case : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def lowerCAmelCase( self : str ): """simple docstring""" pass def lowerCAmelCase( self : Dict ): """simple docstring""" # Initialize image_processing snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image ) # Test not batched input snake_case : Optional[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , UpperCAmelCase__ ) self.assertIsInstance(encoding.boxes , UpperCAmelCase__ ) # Test batched snake_case : Dict = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" # Initialize image_processing snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray ) # 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 : List[Any] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" # Initialize image_processing snake_case : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , 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 : Tuple = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" # with apply_OCR = True snake_case : int = LayoutLMvaImageProcessor() from datasets import load_dataset snake_case : List[Any] = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) snake_case : List[Any] = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) snake_case : Any = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 snake_case : Optional[Any] = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 snake_case : Union[str, Any] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , UpperCAmelCase__ ) self.assertListEqual(encoding.boxes , UpperCAmelCase__ ) # with apply_OCR = False snake_case : str = LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase__ ) snake_case : Optional[Any] = image_processing(UpperCAmelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
84
0
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor _a : Any = logging.get_logger(__name__) class a_ ( lowercase_ ): def __init__( self : List[Any] , *UpperCAmelCase__ : str , **UpperCAmelCase__ : List[str] ): """simple docstring""" warnings.warn( '''The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use DeformableDetrImageProcessor instead.''' , UpperCAmelCase__ , ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ )
719
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _a : Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name _a : Dict = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def a_ ( __magic_name__ , __magic_name__ , __magic_name__=8 ) -> str: """simple docstring""" snake_case : List[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 snake_case : Tuple = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a_ ( a ): def __init__( self : Optional[int] , UpperCAmelCase__ : UNetaDConditionModel , UpperCAmelCase__ : DDPMScheduler , UpperCAmelCase__ : VQModel , ): """simple docstring""" super().__init__() self.register_modules( unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , movq=UpperCAmelCase__ , ) snake_case : List[Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCAmelCase( self : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any ): """simple docstring""" if latents is None: snake_case : int = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) else: if latents.shape != shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}" ) snake_case : Optional[Any] = latents.to(UpperCAmelCase__ ) snake_case : List[Any] = latents * scheduler.init_noise_sigma return latents def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Optional[int]=0 ): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) snake_case : Union[str, Any] = torch.device(F"cuda:{gpu_id}" ) snake_case : Dict = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Any=0 ): """simple docstring""" if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) snake_case : Optional[int] = torch.device(F"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=UpperCAmelCase__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) snake_case : List[str] = None for cpu_offloaded_model in [self.unet, self.movq]: snake_case , snake_case : Optional[int] = cpu_offload_with_hook(UpperCAmelCase__ , UpperCAmelCase__ , prev_module_hook=UpperCAmelCase__ ) # We'll offload the last model manually. snake_case : Tuple = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(UpperCAmelCase__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase__ : torch.FloatTensor , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 100 , UpperCAmelCase__ : float = 4.0 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[torch.FloatTensor] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" snake_case : Optional[int] = self._execution_device snake_case : Union[str, Any] = guidance_scale > 1.0 if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : Any = torch.cat(UpperCAmelCase__ , dim=0 ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : Union[str, Any] = torch.cat(UpperCAmelCase__ , dim=0 ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : int = torch.cat(UpperCAmelCase__ , dim=0 ) snake_case : List[Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: snake_case : Dict = image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Optional[Any] = negative_image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Tuple = hint.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Optional[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase__ ) snake_case : List[str] = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase__ ) self.scheduler.set_timesteps(UpperCAmelCase__ , device=UpperCAmelCase__ ) snake_case : str = self.scheduler.timesteps snake_case : Optional[Any] = self.movq.config.latent_channels snake_case , snake_case : Optional[Any] = downscale_height_and_width(UpperCAmelCase__ , UpperCAmelCase__ , self.movq_scale_factor ) # create initial latent snake_case : Dict = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(UpperCAmelCase__ ) ): # expand the latents if we are doing classifier free guidance snake_case : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case : Optional[int] = {'''image_embeds''': image_embeds, '''hint''': hint} snake_case : Any = self.unet( sample=UpperCAmelCase__ , timestep=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , added_cond_kwargs=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , )[0] if do_classifier_free_guidance: snake_case , snake_case : Dict = noise_pred.split(latents.shape[1] , dim=1 ) snake_case , snake_case : Any = noise_pred.chunk(2 ) snake_case , snake_case : Dict = variance_pred.chunk(2 ) snake_case : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) snake_case : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): snake_case , snake_case : Tuple = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 snake_case : List[Any] = self.scheduler.step( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , generator=UpperCAmelCase__ , )[0] # post-processing snake_case : List[Any] = self.movq.decode(UpperCAmelCase__ , force_not_quantize=UpperCAmelCase__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: snake_case : Optional[Any] = image * 0.5 + 0.5 snake_case : int = image.clamp(0 , 1 ) snake_case : List[str] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": snake_case : str = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
84
0
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _a : List[str] = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _a : List[Any] = 'main' # Default branch name _a : Dict = 'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2' # One particular commit (not the top of `main`) _a : Any = 'aaaaaaa' # This commit does not exist, so we should 404. _a : str = 'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684' # Sha-1 of config.json on the top of `main`, for checking purposes _a : Tuple = '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3' @contextlib.contextmanager def a_ ( ) -> str: """simple docstring""" print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def a_ ( ) -> List[str]: """simple docstring""" print('''Bonjour!''' ) yield print('''Au revoir!''' ) class a_ ( unittest.TestCase ): def lowerCAmelCase( self : Tuple ): """simple docstring""" assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class a_ ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def lowerCAmelCase( self : str , UpperCAmelCase__ : str ): """simple docstring""" with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : str ): """simple docstring""" with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : Tuple ): """simple docstring""" with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def lowerCAmelCase( self : Optional[int] ): """simple docstring""" self.assertEqual(find_labels(UpperCAmelCase__ ) , ['''labels'''] ) self.assertEqual(find_labels(UpperCAmelCase__ ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(UpperCAmelCase__ ) , ['''start_positions''', '''end_positions'''] ) class a_ ( a ): pass self.assertEqual(find_labels(UpperCAmelCase__ ) , ['''labels'''] ) @require_tf def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" self.assertEqual(find_labels(UpperCAmelCase__ ) , ['''labels'''] ) self.assertEqual(find_labels(UpperCAmelCase__ ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(UpperCAmelCase__ ) , ['''start_positions''', '''end_positions'''] ) class a_ ( a ): pass self.assertEqual(find_labels(UpperCAmelCase__ ) , ['''labels'''] ) @require_flax def lowerCAmelCase( self : int ): """simple docstring""" self.assertEqual(find_labels(UpperCAmelCase__ ) , [] ) self.assertEqual(find_labels(UpperCAmelCase__ ) , [] ) self.assertEqual(find_labels(UpperCAmelCase__ ) , [] ) class a_ ( a ): pass self.assertEqual(find_labels(UpperCAmelCase__ ) , [] )
720
import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _a : List[Any] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class a_ ( a , unittest.TestCase ): A__ : Dict = ReformerTokenizer A__ : Optional[int] = ReformerTokenizerFast A__ : str = True A__ : Tuple = False A__ : str = True def lowerCAmelCase( self : List[Any] ): """simple docstring""" super().setUp() snake_case : str = ReformerTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : int = '''<s>''' snake_case : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase__ ) , UpperCAmelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase__ ) , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''j''' ) self.assertEqual(len(UpperCAmelCase__ ) , 1_000 ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def lowerCAmelCase( self : Dict ): """simple docstring""" if not self.test_rust_tokenizer: return snake_case : Any = self.get_tokenizer() snake_case : str = self.get_rust_tokenizer() snake_case : Tuple = '''I was born in 92000, and this is falsé.''' snake_case : str = tokenizer.tokenize(UpperCAmelCase__ ) snake_case : int = rust_tokenizer.tokenize(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : Union[str, Any] = tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) snake_case : List[str] = rust_tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : List[str] = self.get_rust_tokenizer() snake_case : Optional[int] = tokenizer.encode(UpperCAmelCase__ ) snake_case : Optional[Any] = rust_tokenizer.encode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : List[Any]=15 ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case : str = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) # Simple input snake_case : Union[str, Any] = '''This is a simple input''' snake_case : List[str] = ['''This is a simple input 1''', '''This is a simple input 2'''] snake_case : int = ('''This is a simple input''', '''This is a pair''') snake_case : int = [ ('''This is a simple input 1''', '''This is a simple input 2'''), ('''This is a simple pair 1''', '''This is a simple pair 2'''), ] # Simple input tests self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Simple input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Simple input self.assertRaises( UpperCAmelCase__ , tokenizer_r.batch_encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' , ) # Pair input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Pair input self.assertRaises(UpperCAmelCase__ , tokenizer_r.encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' ) # Pair input self.assertRaises( UpperCAmelCase__ , tokenizer_r.batch_encode_plus , UpperCAmelCase__ , max_length=UpperCAmelCase__ , padding='''max_length''' , ) def lowerCAmelCase( self : str ): """simple docstring""" pass def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : Union[str, Any] = ReformerTokenizer(UpperCAmelCase__ , keep_accents=UpperCAmelCase__ ) snake_case : List[str] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [285, 46, 10, 170, 382] , ) snake_case : int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) snake_case : int = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) snake_case : List[Any] = tokenizer.convert_ids_to_tokens(UpperCAmelCase__ ) self.assertListEqual( UpperCAmelCase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def lowerCAmelCase( self : Tuple ): """simple docstring""" return ReformerTokenizer.from_pretrained('''google/reformer-crime-and-punishment''' ) @slow def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Any = '''Hello World!''' snake_case : Optional[Any] = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @slow def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[Any] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) snake_case : Dict = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(UpperCAmelCase__ , self.big_tokenizer.encode(UpperCAmelCase__ ) ) @require_torch @slow def lowerCAmelCase( self : List[Any] ): """simple docstring""" import torch from transformers import ReformerConfig, ReformerModel # Build sequence snake_case : Any = list(self.big_tokenizer.get_vocab().keys() )[:10] snake_case : Union[str, Any] = ''' '''.join(UpperCAmelCase__ ) snake_case : Optional[int] = self.big_tokenizer.encode_plus(UpperCAmelCase__ , return_tensors='''pt''' ) snake_case : List[str] = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors='''pt''' ) snake_case : Optional[Any] = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) snake_case : Tuple = encoded_sequence['''input_ids'''].shape snake_case : List[Any] = ReformerModel(UpperCAmelCase__ ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**UpperCAmelCase__ ) model(**UpperCAmelCase__ ) @slow def lowerCAmelCase( self : Optional[int] ): """simple docstring""" # fmt: off snake_case : Tuple = {'''input_ids''': [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 snake_case : Tuple = [ '''This is a very simple sentence.''', '''The quick brown fox jumps over the lazy dog.''', ] self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''google/reformer-crime-and-punishment''' , revision='''0e6c3decb8211d49bf881013425dc8b0448b3f5a''' , padding=UpperCAmelCase__ , sequences=UpperCAmelCase__ , )
84
0
def a_ ( __magic_name__ , __magic_name__ ) -> Optional[int]: """simple docstring""" snake_case : Dict = len(__magic_name__ ) snake_case : int = len(__magic_name__ ) snake_case : Optional[int] = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] snake_case : Union[str, Any] = True for i in range(__magic_name__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: snake_case : Optional[Any] = True if a[i].islower(): snake_case : List[Any] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
721
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def a_ ( __magic_name__ ) -> Tuple: """simple docstring""" snake_case , snake_case : Any = image.size snake_case , snake_case : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 snake_case : List[str] = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) snake_case : Dict = np.array(__magic_name__ ).astype(np.floataa ) / 255.0 snake_case : Optional[Any] = image[None].transpose(0 , 3 , 1 , 2 ) snake_case : Tuple = torch.from_numpy(__magic_name__ ) return 2.0 * image - 1.0 class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : VQModel , UpperCAmelCase__ : UNetaDModel , UpperCAmelCase__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ): """simple docstring""" super().__init__() self.register_modules(vqvae=UpperCAmelCase__ , unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) @torch.no_grad() def __call__( self : Any , UpperCAmelCase__ : Union[torch.Tensor, PIL.Image.Image] = None , UpperCAmelCase__ : Optional[int] = 1 , UpperCAmelCase__ : Optional[int] = 100 , UpperCAmelCase__ : Optional[float] = 0.0 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" if isinstance(UpperCAmelCase__ , PIL.Image.Image ): snake_case : Optional[int] = 1 elif isinstance(UpperCAmelCase__ , torch.Tensor ): snake_case : Any = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(UpperCAmelCase__ )}" ) if isinstance(UpperCAmelCase__ , PIL.Image.Image ): snake_case : Optional[Any] = preprocess(UpperCAmelCase__ ) snake_case , snake_case : Union[str, Any] = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image snake_case : List[Any] = (batch_size, self.unet.config.in_channels // 2, height, width) snake_case : str = next(self.unet.parameters() ).dtype snake_case : Dict = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=self.device , dtype=UpperCAmelCase__ ) snake_case : Any = image.to(device=self.device , dtype=UpperCAmelCase__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(UpperCAmelCase__ , device=self.device ) snake_case : Optional[Any] = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler snake_case : Union[str, Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] snake_case : Any = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case : Optional[Any] = {} if accepts_eta: snake_case : Dict = eta for t in self.progress_bar(UpperCAmelCase__ ): # concat latents and low resolution image in the channel dimension. snake_case : Optional[int] = torch.cat([latents, image] , dim=1 ) snake_case : str = self.scheduler.scale_model_input(UpperCAmelCase__ , UpperCAmelCase__ ) # predict the noise residual snake_case : int = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case : Any = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample # decode the image latents with the VQVAE snake_case : Optional[int] = self.vqvae.decode(UpperCAmelCase__ ).sample snake_case : int = torch.clamp(UpperCAmelCase__ , -1.0 , 1.0 ) snake_case : Dict = image / 2 + 0.5 snake_case : int = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case : Any = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
84
0
import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() _a : Any = logging.get_logger(__name__) def a_ ( __magic_name__ ) -> Union[str, Any]: """simple docstring""" snake_case : int = torch.load(__magic_name__ , map_location='''cpu''' ) if "model" in sd.keys(): snake_case : Union[str, Any] = torch.load(__magic_name__ , map_location='''cpu''' )['''model'''] # pop unnecessary weights snake_case : List[str] = [ '''decoder.version''', '''decoder.output_projection.weight''', ] for key in keys_to_delete: if key in sd: sd.pop(__magic_name__ ) snake_case : Any = { '''decoder.project_in_dim.weight''': '''decoder.project_in.weight''', '''decoder.project_out_dim.weight''': '''decoder.project_out.weight''', '''decoder.layer_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.layer_norm.bias''': '''decoder.final_layer_norm.bias''', } for old_key, new_key in keys_to_rename.items(): if old_key in sd: snake_case : Dict = sd.pop(__magic_name__ ) snake_case : Optional[Any] = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: snake_case : Tuple = sd[key] # We split QKV in separate Q,K,V snake_case : Optional[Any] = key.replace('''.qkv_proj.''' , '''.q_proj.''' ) snake_case : Optional[Any] = key.replace('''.qkv_proj.''' , '''.k_proj.''' ) snake_case : Any = key.replace('''.qkv_proj.''' , '''.v_proj.''' ) snake_case : Dict = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 snake_case : Union[str, Any] = torch.split(__magic_name__ , depth // 3 , dim=0 ) snake_case : Optional[int] = q snake_case : str = k snake_case : List[str] = v del sd[key] return sd @torch.no_grad() def a_ ( __magic_name__ , __magic_name__ , __magic_name__=None ) -> Dict: """simple docstring""" snake_case : Any = load_checkpoint(__magic_name__ ) if config is not None: snake_case : str = OPTConfig.from_pretrained(__magic_name__ ) else: snake_case : Optional[int] = OPTConfig() snake_case : Dict = OPTModel(__magic_name__ ).half().eval() model.load_state_dict(__magic_name__ ) # Check results Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) model.save_pretrained(__magic_name__ ) if __name__ == "__main__": _a : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--fairseq_path', type=str, help=( 'path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:' ' https://huggingface.co/models?other=opt_metasq' ), ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--hf_config', default=None, type=str, help='Define HF config.') _a : List[Any] = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
700
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class a_ ( a ): def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = tempfile.mkdtemp() snake_case : Dict = 5 # Realm tok snake_case : str = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] snake_case : Tuple = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) snake_case : Any = os.path.join(UpperCAmelCase__ , 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 : Tuple = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def lowerCAmelCase( self : Any ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Any = RealmConfig(num_block_records=self.num_block_records ) return config def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[int] = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Dict = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=UpperCAmelCase__ , ) return block_records def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Tuple = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[str] = self.get_config() snake_case : Optional[Any] = self.get_dummy_retriever() snake_case : Optional[int] = retriever.tokenizer snake_case : Dict = np.array([0, 3] , dtype='''long''' ) snake_case : Optional[int] = tokenizer(['''Test question'''] ).input_ids snake_case : Union[str, Any] = tokenizer( ['''the fourth'''] , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ).input_ids snake_case : Optional[Any] = config.reader_seq_len snake_case , snake_case , snake_case , snake_case : List[str] = retriever( UpperCAmelCase__ , UpperCAmelCase__ , answer_ids=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors='''np''' ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(len(UpperCAmelCase__ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = self.get_config() snake_case : Optional[int] = self.get_dummy_retriever() snake_case : List[str] = retriever.tokenizer snake_case : Optional[Any] = np.array([0, 3, 5] , dtype='''long''' ) snake_case : Optional[int] = tokenizer(['''Test question'''] ).input_ids snake_case : Any = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ).input_ids snake_case : List[Any] = config.reader_seq_len snake_case , snake_case , snake_case , snake_case : Union[str, Any] = retriever( UpperCAmelCase__ , UpperCAmelCase__ , answer_ids=UpperCAmelCase__ , max_length=UpperCAmelCase__ , return_tensors='''np''' ) self.assertEqual([False, True, True] , UpperCAmelCase__ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , UpperCAmelCase__ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : int = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path snake_case : Optional[Any] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: snake_case : Any = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) snake_case : Any = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
84
0
import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class a_ ( unittest.TestCase ): def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Tuple = 1 snake_case : int = 3 snake_case : Dict = (32, 32) snake_case : Dict = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(UpperCAmelCase__ ) return image @property def lowerCAmelCase( self : int ): """simple docstring""" torch.manual_seed(0 ) snake_case : int = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) return model @property def lowerCAmelCase( self : List[Any] ): """simple docstring""" torch.manual_seed(0 ) snake_case : int = 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 , ) return model @property def lowerCAmelCase( self : Tuple ): """simple docstring""" torch.manual_seed(0 ) snake_case : Union[str, Any] = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_006 , ) return RobertaSeriesModelWithTransformation(UpperCAmelCase__ ) @property def lowerCAmelCase( self : List[str] ): """simple docstring""" def extract(*UpperCAmelCase__ : str , **UpperCAmelCase__ : Tuple ): class a_ : def __init__( self : Optional[Any] ): """simple docstring""" snake_case : Tuple = torch.ones([0] ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : List[Any] ): """simple docstring""" self.pixel_values.to(UpperCAmelCase__ ) return self return Out() return extract def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case : Any = self.dummy_cond_unet snake_case : Tuple = PNDMScheduler(skip_prk_steps=UpperCAmelCase__ ) snake_case : List[str] = self.dummy_vae snake_case : Optional[int] = self.dummy_text_encoder snake_case : Dict = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) snake_case : Any = 77 snake_case : Union[str, Any] = self.dummy_image.to(UpperCAmelCase__ ) snake_case : Union[str, Any] = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk snake_case : Dict = AltDiffusionImgaImgPipeline( unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , vae=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , safety_checker=UpperCAmelCase__ , feature_extractor=self.dummy_extractor , ) snake_case : Tuple = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=UpperCAmelCase__ ) snake_case : Optional[Any] = alt_pipe.to(UpperCAmelCase__ ) alt_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) snake_case : Optional[int] = '''A painting of a squirrel eating a burger''' snake_case : str = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) snake_case : List[str] = alt_pipe( [prompt] , generator=UpperCAmelCase__ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=UpperCAmelCase__ , ) snake_case : Any = output.images snake_case : Dict = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) snake_case : Optional[Any] = alt_pipe( [prompt] , generator=UpperCAmelCase__ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , )[0] snake_case : Dict = image[0, -3:, -3:, -1] snake_case : Union[str, Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) snake_case : Any = np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Optional[Any] = self.dummy_cond_unet snake_case : Union[str, Any] = PNDMScheduler(skip_prk_steps=UpperCAmelCase__ ) snake_case : Optional[int] = self.dummy_vae snake_case : Any = self.dummy_text_encoder snake_case : Optional[Any] = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' ) snake_case : List[str] = 77 snake_case : str = self.dummy_image.to(UpperCAmelCase__ ) # put models in fp16 snake_case : List[Any] = unet.half() snake_case : Union[str, Any] = vae.half() snake_case : Tuple = bert.half() # make sure here that pndm scheduler skips prk snake_case : List[Any] = AltDiffusionImgaImgPipeline( unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , vae=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , safety_checker=UpperCAmelCase__ , feature_extractor=self.dummy_extractor , ) snake_case : Optional[Any] = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=UpperCAmelCase__ ) snake_case : List[Any] = alt_pipe.to(UpperCAmelCase__ ) alt_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) snake_case : Any = '''A painting of a squirrel eating a burger''' snake_case : Any = torch.manual_seed(0 ) snake_case : int = alt_pipe( [prompt] , generator=UpperCAmelCase__ , num_inference_steps=2 , output_type='''np''' , image=UpperCAmelCase__ , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[int] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) # resize to resolution that is divisible by 8 but not 16 or 32 snake_case : Optional[int] = init_image.resize((760, 504) ) snake_case : int = '''BAAI/AltDiffusion''' snake_case : Optional[int] = AltDiffusionImgaImgPipeline.from_pretrained( UpperCAmelCase__ , safety_checker=UpperCAmelCase__ , ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) pipe.enable_attention_slicing() snake_case : Optional[int] = '''A fantasy landscape, trending on artstation''' snake_case : int = torch.manual_seed(0 ) snake_case : Dict = pipe( prompt=UpperCAmelCase__ , image=UpperCAmelCase__ , strength=0.75 , guidance_scale=7.5 , generator=UpperCAmelCase__ , output_type='''np''' , ) snake_case : int = output.images[0] snake_case : str = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) snake_case : int = np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class a_ ( unittest.TestCase ): def lowerCAmelCase( self : List[str] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Union[str, Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) snake_case : Tuple = init_image.resize((768, 512) ) snake_case : List[Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy''' ) snake_case : Union[str, Any] = '''BAAI/AltDiffusion''' snake_case : List[Any] = AltDiffusionImgaImgPipeline.from_pretrained( UpperCAmelCase__ , safety_checker=UpperCAmelCase__ , ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) pipe.enable_attention_slicing() snake_case : Union[str, Any] = '''A fantasy landscape, trending on artstation''' snake_case : int = torch.manual_seed(0 ) snake_case : Dict = pipe( prompt=UpperCAmelCase__ , image=UpperCAmelCase__ , strength=0.75 , guidance_scale=7.5 , generator=UpperCAmelCase__ , output_type='''np''' , ) snake_case : Optional[Any] = output.images[0] assert image.shape == (512, 768, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1e-2
701
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _a : str = {'configuration_encoder_decoder': ['EncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = ['EncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Dict = ['TFEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int = ['FlaxEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys _a : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
84
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _a : Optional[Any] = logging.get_logger(__name__) _a : Optional[int] = { 'facebook/nllb-moe-54B': 'https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json', } class a_ ( a ): A__ : str = 'nllb-moe' A__ : Any = ['past_key_values'] A__ : Optional[int] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : List[str] , UpperCAmelCase__ : Dict=128_112 , UpperCAmelCase__ : Any=1_024 , UpperCAmelCase__ : str=12 , UpperCAmelCase__ : Union[str, Any]=4_096 , UpperCAmelCase__ : Tuple=16 , UpperCAmelCase__ : Union[str, Any]=12 , UpperCAmelCase__ : int=4_096 , UpperCAmelCase__ : Optional[Any]=16 , UpperCAmelCase__ : List[Any]=0.05 , UpperCAmelCase__ : Dict=0.05 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]="relu" , UpperCAmelCase__ : Union[str, Any]=1_024 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : Union[str, Any]="float32" , UpperCAmelCase__ : int=False , UpperCAmelCase__ : List[Any]=128 , UpperCAmelCase__ : Optional[int]=64 , UpperCAmelCase__ : Optional[Any]=4 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Optional[Any]=0.001 , UpperCAmelCase__ : Tuple=0.001 , UpperCAmelCase__ : Tuple="all" , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : int=False , UpperCAmelCase__ : List[Any]=1.0 , UpperCAmelCase__ : List[str]=0.2 , UpperCAmelCase__ : List[str]=1 , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : List[str]=2 , UpperCAmelCase__ : Tuple=False , **UpperCAmelCase__ : Dict , ): """simple docstring""" snake_case : int = vocab_size snake_case : List[str] = max_position_embeddings snake_case : List[Any] = d_model snake_case : List[Any] = encoder_ffn_dim snake_case : Optional[Any] = encoder_layers snake_case : List[Any] = encoder_attention_heads snake_case : Union[str, Any] = decoder_ffn_dim snake_case : str = decoder_layers snake_case : Optional[int] = decoder_attention_heads snake_case : str = dropout snake_case : Any = attention_dropout snake_case : Any = activation_dropout snake_case : List[Any] = activation_function snake_case : Any = init_std snake_case : Optional[Any] = encoder_layerdrop snake_case : Dict = decoder_layerdrop snake_case : Any = use_cache snake_case : Optional[int] = encoder_layers snake_case : Union[str, Any] = scale_embedding # scale factor will be sqrt(d_model) if True snake_case : List[str] = router_z_loss_coef snake_case : str = router_aux_loss_coef snake_case : Union[str, Any] = decoder_sparse_step snake_case : Optional[int] = encoder_sparse_step snake_case : int = num_experts snake_case : int = expert_capacity snake_case : int = router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(F"`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}" ) snake_case : Union[str, Any] = router_dtype snake_case : Optional[Any] = router_ignore_padding_tokens snake_case : str = batch_prioritized_routing snake_case : Optional[Any] = second_expert_policy snake_case : Dict = normalize_router_prob_before_dropping snake_case : Optional[int] = moe_eval_capacity_token_fraction snake_case : Tuple = moe_token_dropout snake_case : List[Any] = output_router_logits super().__init__( pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , is_encoder_decoder=UpperCAmelCase__ , decoder_start_token_id=UpperCAmelCase__ , **UpperCAmelCase__ , )
702
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer _a : str = logging.get_logger(__name__) _a : Optional[int] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _a : Optional[Any] = { 'vocab_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json' ), }, } _a : Union[str, Any] = { 'yjernite/retribert-base-uncased': 512, } _a : Tuple = { 'yjernite/retribert-base-uncased': {'do_lower_case': True}, } class a_ ( a ): A__ : List[str] = VOCAB_FILES_NAMES A__ : Any = PRETRAINED_VOCAB_FILES_MAP A__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Any = PRETRAINED_INIT_CONFIGURATION A__ : Optional[Any] = RetriBertTokenizer A__ : Any = ['input_ids', 'attention_mask'] def __init__( self : Optional[int] , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Dict="[UNK]" , UpperCAmelCase__ : str="[SEP]" , UpperCAmelCase__ : Union[str, Any]="[PAD]" , UpperCAmelCase__ : Dict="[CLS]" , UpperCAmelCase__ : Optional[Any]="[MASK]" , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=None , **UpperCAmelCase__ : Dict , ): """simple docstring""" super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , do_lower_case=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , tokenize_chinese_chars=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ , **UpperCAmelCase__ , ) snake_case : List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCAmelCase__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCAmelCase__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCAmelCase__ ) != tokenize_chinese_chars ): snake_case : int = getattr(UpperCAmelCase__ , normalizer_state.pop('''type''' ) ) snake_case : List[Any] = do_lower_case snake_case : Union[str, Any] = strip_accents snake_case : int = tokenize_chinese_chars snake_case : int = normalizer_class(**UpperCAmelCase__ ) snake_case : Union[str, Any] = do_lower_case def lowerCAmelCase( self : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=None ): """simple docstring""" snake_case : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ): """simple docstring""" snake_case : List[Any] = [self.sep_token_id] snake_case : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ): """simple docstring""" snake_case : Tuple = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ )
84
0
import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device 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 EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class a_ : def __init__( self : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int]=13 , UpperCAmelCase__ : str=7 , UpperCAmelCase__ : str=False , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : List[str]=33 , UpperCAmelCase__ : List[Any]=32 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : int=4 , UpperCAmelCase__ : Tuple=37 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Union[str, Any]=512 , UpperCAmelCase__ : Dict=16 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : Optional[Any]=4 , UpperCAmelCase__ : List[str]=None , ): """simple docstring""" snake_case : Tuple = parent snake_case : Optional[int] = batch_size snake_case : int = seq_length snake_case : str = is_training snake_case : Any = use_input_mask snake_case : List[str] = use_token_type_ids snake_case : Tuple = use_labels snake_case : List[str] = vocab_size snake_case : List[Any] = hidden_size snake_case : str = num_hidden_layers snake_case : Optional[Any] = num_attention_heads snake_case : Dict = intermediate_size snake_case : Optional[int] = hidden_act snake_case : int = hidden_dropout_prob snake_case : Tuple = attention_probs_dropout_prob snake_case : Dict = max_position_embeddings snake_case : Optional[Any] = type_vocab_size snake_case : Union[str, Any] = type_sequence_label_size snake_case : List[str] = initializer_range snake_case : str = num_labels snake_case : str = num_choices snake_case : List[Any] = scope def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case : Union[str, Any] = None if self.use_input_mask: snake_case : Any = random_attention_mask([self.batch_size, self.seq_length] ) snake_case : Optional[int] = None snake_case : Tuple = None snake_case : Optional[int] = None if self.use_labels: snake_case : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case : str = ids_tensor([self.batch_size] , self.num_choices ) snake_case : Any = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def lowerCAmelCase( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any] ): """simple docstring""" snake_case : Union[str, Any] = EsmModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : int = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) snake_case : Optional[Any] = model(UpperCAmelCase__ ) snake_case : Any = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] ): """simple docstring""" snake_case : int = EsmForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : int = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] ): """simple docstring""" snake_case : int = self.num_labels snake_case : Optional[Any] = EsmForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : Optional[int] = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase( self : int ): """simple docstring""" snake_case : List[str] = self.prepare_config_and_inputs() ( snake_case ) : str = config_and_inputs snake_case : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class a_ ( a , a , unittest.TestCase ): A__ : List[Any] = False A__ : int = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) A__ : Optional[int] = () A__ : Optional[int] = ( { 'feature-extraction': EsmModel, 'fill-mask': EsmForMaskedLM, 'text-classification': EsmForSequenceClassification, 'token-classification': EsmForTokenClassification, 'zero-shot': EsmForSequenceClassification, } if is_torch_available() else {} ) A__ : Union[str, Any] = True def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : Tuple = EsmModelTester(self ) snake_case : Union[str, Any] = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=37 ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case : Tuple = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : Dict = EsmModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : str = self.model_tester.prepare_config_and_inputs()[0] snake_case : Union[str, Any] = EsmEmbeddings(config=UpperCAmelCase__ ) snake_case : Optional[int] = torch.as_tensor([[12, 31, 13, model.padding_idx]] ) snake_case : Any = torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) snake_case : Optional[int] = create_position_ids_from_input_ids(UpperCAmelCase__ , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(UpperCAmelCase__ , UpperCAmelCase__ ) ) ) def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Any = self.model_tester.prepare_config_and_inputs()[0] snake_case : str = EsmEmbeddings(config=UpperCAmelCase__ ) snake_case : List[str] = torch.empty(2 , 4 , 30 ) snake_case : Any = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] snake_case : Any = torch.as_tensor([expected_single_positions, expected_single_positions] ) snake_case : str = embeddings.create_position_ids_from_inputs_embeds(UpperCAmelCase__ ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(UpperCAmelCase__ , UpperCAmelCase__ ) ) ) @unittest.skip('''Esm does not support embedding resizing''' ) def lowerCAmelCase( self : int ): """simple docstring""" pass @unittest.skip('''Esm does not support embedding resizing''' ) def lowerCAmelCase( self : str ): """simple docstring""" pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" pass @require_torch class a_ ( a ): @slow def lowerCAmelCase( self : Optional[int] ): """simple docstring""" with torch.no_grad(): snake_case : str = EsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) model.eval() snake_case : Dict = torch.tensor([[0, 1, 2, 3, 4, 5]] ) snake_case : Union[str, Any] = model(UpperCAmelCase__ )[0] snake_case : Tuple = 33 snake_case : Any = torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) snake_case : List[Any] = torch.tensor( [[[8.9215, -10.5898, -6.4671], [-6.3967, -13.9114, -1.1212], [-7.7812, -13.9516, -3.7406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4 ) ) @slow def lowerCAmelCase( self : int ): """simple docstring""" with torch.no_grad(): snake_case : Optional[int] = EsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) model.eval() snake_case : Union[str, Any] = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) snake_case : int = model(UpperCAmelCase__ )[0] # compare the actual values for a slice. snake_case : List[str] = torch.tensor( [[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1e-4 ) )
703
import string import numpy def a_ ( __magic_name__ , __magic_name__ ) -> int: """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , __magic_name__ ) class a_ : A__ : List[Any] = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) A__ : List[str] = numpy.vectorize(lambda a : x % 36 ) A__ : Dict = numpy.vectorize(a ) def __init__( self : List[str] , UpperCAmelCase__ : numpy.ndarray ): """simple docstring""" snake_case : int = self.modulus(UpperCAmelCase__ ) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key snake_case : List[str] = encrypt_key.shape[0] def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : str ): """simple docstring""" return self.key_string.index(UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] , UpperCAmelCase__ : int ): """simple docstring""" return self.key_string[round(UpperCAmelCase__ )] def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[Any] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: snake_case : Tuple = det % len(self.key_string ) snake_case : Tuple = len(self.key_string ) if greatest_common_divisor(UpperCAmelCase__ , len(self.key_string ) ) != 1: snake_case : List[Any] = ( F"determinant modular {req_l} of encryption key({det}) " F"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[int] = [char for char in text.upper() if char in self.key_string] snake_case : Optional[int] = chars[-1] while len(UpperCAmelCase__ ) % self.break_key != 0: chars.append(UpperCAmelCase__ ) return "".join(UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[int] = self.process_text(text.upper() ) snake_case : Optional[int] = '''''' for i in range(0 , len(UpperCAmelCase__ ) - self.break_key + 1 , self.break_key ): snake_case : int = text[i : i + self.break_key] snake_case : int = [self.replace_letters(UpperCAmelCase__ ) for char in batch] snake_case : Tuple = numpy.array([vec] ).T snake_case : Optional[Any] = self.modulus(self.encrypt_key.dot(UpperCAmelCase__ ) ).T.tolist()[ 0 ] snake_case : Dict = ''''''.join( self.replace_digits(UpperCAmelCase__ ) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Optional[int] = round(numpy.linalg.det(self.encrypt_key ) ) if det < 0: snake_case : int = det % len(self.key_string ) snake_case : Dict = None for i in range(len(self.key_string ) ): if (det * i) % len(self.key_string ) == 1: snake_case : Any = i break snake_case : Any = ( det_inv * numpy.linalg.det(self.encrypt_key ) * numpy.linalg.inv(self.encrypt_key ) ) return self.to_int(self.modulus(UpperCAmelCase__ ) ) def lowerCAmelCase( self : Dict , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Any = self.make_decrypt_key() snake_case : Optional[Any] = self.process_text(text.upper() ) snake_case : int = '''''' for i in range(0 , len(UpperCAmelCase__ ) - self.break_key + 1 , self.break_key ): snake_case : Any = text[i : i + self.break_key] snake_case : int = [self.replace_letters(UpperCAmelCase__ ) for char in batch] snake_case : List[str] = numpy.array([vec] ).T snake_case : Optional[Any] = self.modulus(decrypt_key.dot(UpperCAmelCase__ ) ).T.tolist()[0] snake_case : int = ''''''.join( self.replace_digits(UpperCAmelCase__ ) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def a_ ( ) -> None: """simple docstring""" snake_case : Any = int(input('''Enter the order of the encryption key: ''' ) ) snake_case : List[Any] = [] print('''Enter each row of the encryption key with space separated integers''' ) for _ in range(__magic_name__ ): snake_case : Optional[Any] = [int(__magic_name__ ) for x in input().split()] hill_matrix.append(__magic_name__ ) snake_case : List[str] = HillCipher(numpy.array(__magic_name__ ) ) print('''Would you like to encrypt or decrypt some text? (1 or 2)''' ) snake_case : int = input('''\n1. Encrypt\n2. Decrypt\n''' ) if option == "1": snake_case : List[Any] = input('''What text would you like to encrypt?: ''' ) print('''Your encrypted text is:''' ) print(hc.encrypt(__magic_name__ ) ) elif option == "2": snake_case : int = input('''What text would you like to decrypt?: ''' ) print('''Your decrypted text is:''' ) print(hc.decrypt(__magic_name__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
84
0
import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device 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 ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : Union[str, Any]=7 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : int=99 , UpperCAmelCase__ : List[Any]=32 , UpperCAmelCase__ : Any=5 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : Union[str, Any]=37 , UpperCAmelCase__ : str="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : Dict=512 , UpperCAmelCase__ : List[Any]=16 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Tuple=3 , UpperCAmelCase__ : int=4 , UpperCAmelCase__ : List[Any]=None , ): """simple docstring""" snake_case : Optional[int] = parent snake_case : Union[str, Any] = batch_size snake_case : Dict = seq_length snake_case : int = is_training snake_case : List[str] = use_input_mask snake_case : Optional[int] = use_token_type_ids snake_case : Optional[Any] = use_labels snake_case : List[Any] = vocab_size snake_case : Dict = hidden_size snake_case : Dict = num_hidden_layers snake_case : List[Any] = num_attention_heads snake_case : str = intermediate_size snake_case : Optional[int] = hidden_act snake_case : str = hidden_dropout_prob snake_case : Optional[Any] = attention_probs_dropout_prob snake_case : Optional[int] = max_position_embeddings snake_case : List[Any] = type_vocab_size snake_case : List[str] = type_sequence_label_size snake_case : Any = initializer_range snake_case : int = num_labels snake_case : str = num_choices snake_case : List[Any] = scope def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case : List[Any] = None if self.use_input_mask: snake_case : Dict = random_attention_mask([self.batch_size, self.seq_length] ) snake_case : Dict = None snake_case : str = None snake_case : List[str] = None if self.use_labels: snake_case : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) snake_case : List[str] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase( self : Any ): """simple docstring""" return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): """simple docstring""" snake_case : List[Any] = DistilBertModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : int = model(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : Any = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[Any] ): """simple docstring""" snake_case : List[Any] = DistilBertForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : int = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ): """simple docstring""" snake_case : Tuple = DistilBertForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : Any = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ): """simple docstring""" snake_case : Dict = self.num_labels snake_case : Optional[Any] = DistilBertForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : Optional[int] = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Tuple = self.num_labels snake_case : Any = DistilBertForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : int = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase( self : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : str ): """simple docstring""" snake_case : Optional[Any] = self.num_choices snake_case : int = DistilBertForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case : Any = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Optional[int] = self.prepare_config_and_inputs() (snake_case) : Union[str, Any] = config_and_inputs snake_case : Dict = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class a_ ( a , a , unittest.TestCase ): A__ : Tuple = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) A__ : Union[str, Any] = ( { 'feature-extraction': DistilBertModel, 'fill-mask': DistilBertForMaskedLM, 'question-answering': DistilBertForQuestionAnswering, 'text-classification': DistilBertForSequenceClassification, 'token-classification': DistilBertForTokenClassification, 'zero-shot': DistilBertForSequenceClassification, } if is_torch_available() else {} ) A__ : str = True A__ : str = True A__ : Union[str, Any] = True A__ : List[Any] = True def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : int = DistilBertModelTester(self ) snake_case : str = ConfigTester(self , config_class=UpperCAmelCase__ , dim=37 ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] ): """simple docstring""" snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCAmelCase__ ) def lowerCAmelCase( self : str ): """simple docstring""" snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCAmelCase__ ) def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCAmelCase__ ) def lowerCAmelCase( self : str ): """simple docstring""" snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCAmelCase__ ) @slow def lowerCAmelCase( self : str ): """simple docstring""" for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case : Dict = DistilBertModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return snake_case : List[str] = True snake_case : Optional[Any] = model_class(config=UpperCAmelCase__ ) snake_case : str = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : Union[str, Any] = torch.jit.trace( UpperCAmelCase__ , (inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , '''traced_model.pt''' ) ) snake_case : List[Any] = torch.jit.load(os.path.join(UpperCAmelCase__ , '''traced_model.pt''' ) , map_location=UpperCAmelCase__ ) loaded(inputs_dict['''input_ids'''].to(UpperCAmelCase__ ) , inputs_dict['''attention_mask'''].to(UpperCAmelCase__ ) ) @require_torch class a_ ( unittest.TestCase ): @slow def lowerCAmelCase( self : Any ): """simple docstring""" snake_case : Dict = DistilBertModel.from_pretrained('''distilbert-base-uncased''' ) snake_case : Tuple = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) snake_case : Optional[int] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): snake_case : Tuple = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] snake_case : Dict = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , UpperCAmelCase__ ) snake_case : Any = torch.tensor( [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1e-4 ) )
704
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class a_ ( a ): A__ : List[Any] = 'Salesforce/blip-image-captioning-base' A__ : Dict = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) A__ : str = 'image_captioner' A__ : Dict = AutoModelForVisionaSeq A__ : Optional[Any] = ['image'] A__ : List[str] = ['text'] def __init__( self : List[str] , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , UpperCAmelCase__ : "Image" ): """simple docstring""" return self.pre_processor(images=UpperCAmelCase__ , return_tensors='''pt''' ) def lowerCAmelCase( self : Any , UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" return self.model.generate(**UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : List[Any] ): """simple docstring""" return self.pre_processor.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ )[0].strip()
84
0
'''simple docstring''' def a_ ( __magic_name__ = 1_000 ) -> int: """simple docstring""" snake_case : Dict = -1 snake_case : Tuple = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c snake_case : Union[str, Any] = (n * n - 2 * a * n) // (2 * n - 2 * a) snake_case : str = n - a - b if c * c == (a * a + b * b): snake_case : Tuple = a * b * c if candidate >= product: snake_case : Optional[int] = candidate return product if __name__ == "__main__": print(f"{solution() = }")
705
def a_ ( __magic_name__ ) -> bool: """simple docstring""" if p < 2: raise ValueError('''p should not be less than 2!''' ) elif p == 2: return True snake_case : int = 4 snake_case : Optional[Any] = (1 << p) - 1 for _ in range(p - 2 ): snake_case : Optional[Any] = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
84
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _a : Tuple = logging.get_logger(__name__) _a : int = { 'weiweishi/roc-bert-base-zh': 'https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json', } class a_ ( a ): A__ : List[str] = 'roc_bert' def __init__( self : int , UpperCAmelCase__ : List[Any]=30_522 , UpperCAmelCase__ : List[str]=768 , UpperCAmelCase__ : List[Any]=12 , UpperCAmelCase__ : Optional[int]=12 , UpperCAmelCase__ : int=3_072 , UpperCAmelCase__ : List[str]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=512 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : Dict=0.02 , UpperCAmelCase__ : int=1e-1_2 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : Optional[Any]="absolute" , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Union[str, Any]=768 , UpperCAmelCase__ : Any=910 , UpperCAmelCase__ : str=512 , UpperCAmelCase__ : Optional[Any]=24_858 , UpperCAmelCase__ : List[str]=True , **UpperCAmelCase__ : Any , ): """simple docstring""" snake_case : str = vocab_size snake_case : Tuple = max_position_embeddings snake_case : List[Any] = hidden_size snake_case : Tuple = num_hidden_layers snake_case : str = num_attention_heads snake_case : int = intermediate_size snake_case : Union[str, Any] = hidden_act snake_case : List[str] = hidden_dropout_prob snake_case : str = attention_probs_dropout_prob snake_case : Dict = initializer_range snake_case : Optional[Any] = type_vocab_size snake_case : Optional[int] = layer_norm_eps snake_case : Dict = use_cache snake_case : str = enable_pronunciation snake_case : Union[str, Any] = enable_shape snake_case : List[str] = pronunciation_embed_dim snake_case : Union[str, Any] = pronunciation_vocab_size snake_case : Union[str, Any] = shape_embed_dim snake_case : str = shape_vocab_size snake_case : List[Any] = concat_input snake_case : Any = position_embedding_type snake_case : Dict = classifier_dropout super().__init__(pad_token_id=UpperCAmelCase__ , **UpperCAmelCase__ )
706
from sklearn.metrics import fa_score import datasets _a : List[str] = '\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n' _a : Dict = '\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {\'f1\': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results[\'f1\'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results[\'f1\'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")\n >>> print(round(results[\'f1\'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {\'f1\': array([0.8, 0. , 0. ])}\n' _a : List[Any] = '\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' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def lowerCAmelCase( self : Any ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ), '''references''': datasets.Sequence(datasets.Value('''int32''' ) ), } if self.config_name == '''multilabel''' else { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'''] , ) def lowerCAmelCase( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : List[str]="binary" , UpperCAmelCase__ : str=None ): """simple docstring""" snake_case : List[Any] = fa_score( UpperCAmelCase__ , UpperCAmelCase__ , labels=UpperCAmelCase__ , pos_label=UpperCAmelCase__ , average=UpperCAmelCase__ , sample_weight=UpperCAmelCase__ ) return {"f1": float(UpperCAmelCase__ ) if score.size == 1 else score}
84
0
import argparse from collections import OrderedDict from pathlib import Path import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision.transforms import functional as F from transformers import DetrImageProcessor, TableTransformerConfig, TableTransformerForObjectDetection from transformers.utils import logging logging.set_verbosity_info() _a : Optional[Any] = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) _a : int = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f"transformer.encoder.layers.{i}.self_attn.out_proj.weight", f"encoder.layers.{i}.self_attn.out_proj.weight") ) rename_keys.append( (f"transformer.encoder.layers.{i}.self_attn.out_proj.bias", f"encoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"encoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"encoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"encoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"encoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.weight", f"encoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm1.bias", f"encoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.weight", f"encoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias")) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"decoder.layers.{i}.self_attn.out_proj.weight") ) rename_keys.append( (f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"decoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight", f"decoder.layers.{i}.encoder_attn.out_proj.weight", ) ) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias", f"decoder.layers.{i}.encoder_attn.out_proj.bias", ) ) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"decoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"decoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"decoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"decoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.weight", f"decoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm1.bias", f"decoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.weight", f"decoder.layers.{i}.encoder_attn_layer_norm.weight") ) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.bias", f"decoder.layers.{i}.encoder_attn_layer_norm.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.weight", f"decoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"decoder.layers.{i}.final_layer_norm.bias")) # convolutional projection + query embeddings + layernorm of encoder + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ('input_proj.weight', 'input_projection.weight'), ('input_proj.bias', 'input_projection.bias'), ('query_embed.weight', 'query_position_embeddings.weight'), ('transformer.encoder.norm.weight', 'encoder.layernorm.weight'), ('transformer.encoder.norm.bias', 'encoder.layernorm.bias'), ('transformer.decoder.norm.weight', 'decoder.layernorm.weight'), ('transformer.decoder.norm.bias', 'decoder.layernorm.bias'), ('class_embed.weight', 'class_labels_classifier.weight'), ('class_embed.bias', 'class_labels_classifier.bias'), ('bbox_embed.layers.0.weight', 'bbox_predictor.layers.0.weight'), ('bbox_embed.layers.0.bias', 'bbox_predictor.layers.0.bias'), ('bbox_embed.layers.1.weight', 'bbox_predictor.layers.1.weight'), ('bbox_embed.layers.1.bias', 'bbox_predictor.layers.1.bias'), ('bbox_embed.layers.2.weight', 'bbox_predictor.layers.2.weight'), ('bbox_embed.layers.2.bias', 'bbox_predictor.layers.2.bias'), ] ) def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> Any: """simple docstring""" snake_case : List[str] = state_dict.pop(__magic_name__ ) snake_case : List[Any] = val def a_ ( __magic_name__ ) -> str: """simple docstring""" snake_case : int = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: snake_case : Dict = key.replace('''backbone.0.body''' , '''backbone.conv_encoder.model''' ) snake_case : Dict = value else: snake_case : Tuple = value return new_state_dict def a_ ( __magic_name__ ) -> Dict: """simple docstring""" snake_case : int = '''''' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) snake_case : List[str] = state_dict.pop(F"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight" ) snake_case : Optional[Any] = state_dict.pop(F"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict snake_case : Union[str, Any] = in_proj_weight[:256, :] snake_case : int = in_proj_bias[:256] snake_case : int = in_proj_weight[256:512, :] snake_case : int = in_proj_bias[256:512] snake_case : Tuple = in_proj_weight[-256:, :] snake_case : Any = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention snake_case : int = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight" ) snake_case : Tuple = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict snake_case : Optional[int] = in_proj_weight[:256, :] snake_case : Dict = in_proj_bias[:256] snake_case : Any = in_proj_weight[256:512, :] snake_case : List[str] = in_proj_bias[256:512] snake_case : int = in_proj_weight[-256:, :] snake_case : str = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention snake_case : Optional[Any] = state_dict.pop( F"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight" ) snake_case : int = state_dict.pop(F"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias" ) # next, add query, keys and values (in that order) of cross-attention to the state dict snake_case : Tuple = in_proj_weight_cross_attn[:256, :] snake_case : int = in_proj_bias_cross_attn[:256] snake_case : Any = in_proj_weight_cross_attn[256:512, :] snake_case : List[Any] = in_proj_bias_cross_attn[256:512] snake_case : List[Any] = in_proj_weight_cross_attn[-256:, :] snake_case : int = in_proj_bias_cross_attn[-256:] def a_ ( __magic_name__ , __magic_name__ ) -> Dict: """simple docstring""" snake_case : List[str] = image.size snake_case : str = max(__magic_name__ , __magic_name__ ) snake_case : str = 800 if '''detection''' in checkpoint_url else 1_000 snake_case : int = target_max_size / current_max_size snake_case : Dict = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) ) return resized_image def a_ ( __magic_name__ ) -> Optional[int]: """simple docstring""" snake_case : Optional[int] = F.to_tensor(__magic_name__ ) snake_case : Any = F.normalize(__magic_name__ , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ) return image @torch.no_grad() def a_ ( __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: """simple docstring""" logger.info('''Converting model...''' ) # load original state dict snake_case : Any = torch.hub.load_state_dict_from_url(__magic_name__ , map_location='''cpu''' ) # rename keys for src, dest in rename_keys: rename_key(__magic_name__ , __magic_name__ , __magic_name__ ) snake_case : Union[str, Any] = rename_backbone_keys(__magic_name__ ) # query, key and value matrices need special treatment read_in_q_k_v(__magic_name__ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them snake_case : List[str] = '''model.''' for key in state_dict.copy().keys(): if not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ): snake_case : Union[str, Any] = state_dict.pop(__magic_name__ ) snake_case : List[Any] = val # create HuggingFace model and load state dict snake_case : Union[str, Any] = TableTransformerConfig( backbone='''resnet18''' , mask_loss_coefficient=1 , dice_loss_coefficient=1 , ce_loss_coefficient=1 , bbox_loss_coefficient=5 , giou_loss_coefficient=2 , eos_coefficient=0.4 , class_cost=1 , bbox_cost=5 , giou_cost=2 , ) if "detection" in checkpoint_url: snake_case : Optional[Any] = 15 snake_case : str = 2 snake_case : Dict = {0: '''table''', 1: '''table rotated'''} snake_case : Dict = idalabel snake_case : str = {v: k for k, v in idalabel.items()} else: snake_case : Union[str, Any] = 125 snake_case : Union[str, Any] = 6 snake_case : Union[str, Any] = { 0: '''table''', 1: '''table column''', 2: '''table row''', 3: '''table column header''', 4: '''table projected row header''', 5: '''table spanning cell''', } snake_case : Optional[Any] = idalabel snake_case : List[str] = {v: k for k, v in idalabel.items()} snake_case : Any = DetrImageProcessor( format='''coco_detection''' , max_size=800 if '''detection''' in checkpoint_url else 1_000 ) snake_case : Any = TableTransformerForObjectDetection(__magic_name__ ) model.load_state_dict(__magic_name__ ) model.eval() # verify our conversion snake_case : Any = '''example_pdf.png''' if '''detection''' in checkpoint_url else '''example_table.png''' snake_case : Union[str, Any] = hf_hub_download(repo_id='''nielsr/example-pdf''' , repo_type='''dataset''' , filename=__magic_name__ ) snake_case : Any = Image.open(__magic_name__ ).convert('''RGB''' ) snake_case : Dict = normalize(resize(__magic_name__ , __magic_name__ ) ).unsqueeze(0 ) snake_case : Dict = model(__magic_name__ ) if "detection" in checkpoint_url: snake_case : int = (1, 15, 3) snake_case : Tuple = torch.tensor( [[-6.7897, -16.9985, 6.7937], [-8.0186, -22.2192, 6.9677], [-7.3117, -21.0708, 7.4055]] ) snake_case : List[str] = torch.tensor([[0.4867, 0.1767, 0.6732], [0.6718, 0.4479, 0.3830], [0.4716, 0.1760, 0.6364]] ) else: snake_case : Dict = (1, 125, 7) snake_case : Optional[int] = torch.tensor( [[-18.1430, -8.3214, 4.8274], [-18.4685, -7.1361, -4.2667], [-26.3693, -9.3429, -4.9962]] ) snake_case : int = torch.tensor([[0.4983, 0.5595, 0.9440], [0.4916, 0.6315, 0.5954], [0.6108, 0.8637, 0.1135]] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, :3, :3] , __magic_name__ , atol=1e-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __magic_name__ , atol=1e-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F"Saving PyTorch model and image processor to {pytorch_dump_folder_path}..." ) Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) model.save_pretrained(__magic_name__ ) image_processor.save_pretrained(__magic_name__ ) if push_to_hub: # Push model to HF hub logger.info('''Pushing model to the hub...''' ) snake_case : Tuple = ( '''microsoft/table-transformer-detection''' if '''detection''' in checkpoint_url else '''microsoft/table-transformer-structure-recognition''' ) model.push_to_hub(__magic_name__ ) image_processor.push_to_hub(__magic_name__ ) if __name__ == "__main__": _a : str = argparse.ArgumentParser() parser.add_argument( '--checkpoint_url', default='https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth', type=str, choices=[ 'https://pubtables1m.blob.core.windows.net/model/pubtables1m_detection_detr_r18.pth', 'https://pubtables1m.blob.core.windows.net/model/pubtables1m_structure_detr_r18.pth', ], help='URL of the Table Transformer checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) _a : Dict = parser.parse_args() convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
707
def a_ ( __magic_name__ ) -> int: """simple docstring""" if not isinstance(__magic_name__ , __magic_name__ ): raise TypeError('''only integers accepted as input''' ) else: snake_case : str = str(abs(__magic_name__ ) ) snake_case : Optional[Any] = [list(__magic_name__ ) for char in range(len(__magic_name__ ) )] for index in range(len(__magic_name__ ) ): num_transpositions[index].pop(__magic_name__ ) return max( int(''''''.join(list(__magic_name__ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
84
0
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _a : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name _a : Dict = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n >>> pipe_prior.to("cuda")\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> zero_image_emb = out.negative_image_embeds\n >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n >>> pipe.to("cuda")\n >>> image = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=50,\n ... ).images\n >>> image[0].save("cat.png")\n ```\n' def a_ ( __magic_name__ , __magic_name__ , __magic_name__=8 ) -> Union[str, Any]: """simple docstring""" snake_case : Optional[int] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 snake_case : Optional[int] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : UNetaDConditionModel , UpperCAmelCase__ : DDPMScheduler , UpperCAmelCase__ : VQModel , ): """simple docstring""" super().__init__() self.register_modules( unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , movq=UpperCAmelCase__ , ) snake_case : int = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCAmelCase( self : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): """simple docstring""" if latents is None: snake_case : str = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) else: if latents.shape != shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}" ) snake_case : Union[str, Any] = latents.to(UpperCAmelCase__ ) snake_case : Optional[Any] = latents * scheduler.init_noise_sigma return latents def lowerCAmelCase( self : int , UpperCAmelCase__ : List[str]=0 ): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) snake_case : Tuple = torch.device(F"cuda:{gpu_id}" ) snake_case : Any = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCAmelCase__ , UpperCAmelCase__ ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : int=0 ): """simple docstring""" if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) snake_case : List[Any] = torch.device(F"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=UpperCAmelCase__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) snake_case : Tuple = None for cpu_offloaded_model in [self.unet, self.movq]: snake_case : Tuple = cpu_offload_with_hook(UpperCAmelCase__ , UpperCAmelCase__ , prev_module_hook=UpperCAmelCase__ ) # We'll offload the last model manually. snake_case : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCAmelCase( self : List[Any] ): """simple docstring""" if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(UpperCAmelCase__ , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(UpperCAmelCase__ ) def __call__( self : Any , UpperCAmelCase__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 512 , UpperCAmelCase__ : int = 100 , UpperCAmelCase__ : float = 4.0 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[torch.FloatTensor] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , ): """simple docstring""" snake_case : Optional[int] = self._execution_device snake_case : int = guidance_scale > 1.0 if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : Tuple = torch.cat(UpperCAmelCase__ , dim=0 ) snake_case : List[str] = image_embeds.shape[0] * num_images_per_prompt if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): snake_case : str = torch.cat(UpperCAmelCase__ , dim=0 ) if do_classifier_free_guidance: snake_case : str = image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : str = negative_image_embeds.repeat_interleave(UpperCAmelCase__ , dim=0 ) snake_case : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase__ ) self.scheduler.set_timesteps(UpperCAmelCase__ , device=UpperCAmelCase__ ) snake_case : List[Any] = self.scheduler.timesteps snake_case : Optional[int] = self.unet.config.in_channels snake_case : Dict = downscale_height_and_width(UpperCAmelCase__ , UpperCAmelCase__ , self.movq_scale_factor ) # create initial latent snake_case : str = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(UpperCAmelCase__ ) ): # expand the latents if we are doing classifier free guidance snake_case : str = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case : Optional[Any] = {'''image_embeds''': image_embeds} snake_case : Any = self.unet( sample=UpperCAmelCase__ , timestep=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , added_cond_kwargs=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , )[0] if do_classifier_free_guidance: snake_case : Any = noise_pred.split(latents.shape[1] , dim=1 ) snake_case : Tuple = noise_pred.chunk(2 ) snake_case : str = variance_pred.chunk(2 ) snake_case : List[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) snake_case : Dict = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): snake_case : List[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 snake_case : Optional[int] = self.scheduler.step( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , generator=UpperCAmelCase__ , )[0] # post-processing snake_case : List[str] = self.movq.decode(UpperCAmelCase__ , force_not_quantize=UpperCAmelCase__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: snake_case : List[Any] = image * 0.5 + 0.5 snake_case : Optional[int] = image.clamp(0 , 1 ) snake_case : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": snake_case : Union[str, Any] = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase__ )
708
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class a_ : def __init__( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any]=99 , UpperCAmelCase__ : Dict=13 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Any=9 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : Tuple=32 , UpperCAmelCase__ : Dict=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=37 , UpperCAmelCase__ : Union[str, Any]=8 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : str=0.002 , UpperCAmelCase__ : str=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : Union[str, Any]=0 , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=None , ): """simple docstring""" snake_case : Union[str, Any] = parent snake_case : Union[str, Any] = batch_size snake_case : Any = encoder_seq_length snake_case : str = decoder_seq_length # For common tests snake_case : Optional[int] = self.decoder_seq_length snake_case : Optional[Any] = is_training snake_case : List[Any] = use_attention_mask snake_case : Union[str, Any] = use_labels snake_case : Any = vocab_size snake_case : Optional[int] = hidden_size snake_case : List[str] = num_hidden_layers snake_case : Union[str, Any] = num_attention_heads snake_case : Any = d_ff snake_case : Any = relative_attention_num_buckets snake_case : Optional[Any] = dropout_rate snake_case : int = initializer_factor snake_case : Optional[Any] = eos_token_id snake_case : Dict = pad_token_id snake_case : Optional[Any] = decoder_start_token_id snake_case : Union[str, Any] = None snake_case : List[str] = decoder_layers def lowerCAmelCase( self : Union[str, Any] ): """simple docstring""" return TaConfig.from_pretrained('''google/umt5-base''' ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=None , ): """simple docstring""" if attention_mask is None: snake_case : Union[str, Any] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: snake_case : Any = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: snake_case : List[Any] = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=UpperCAmelCase__ ) if decoder_head_mask is None: snake_case : Tuple = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=UpperCAmelCase__ ) if cross_attn_head_mask is None: snake_case : Union[str, Any] = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=UpperCAmelCase__ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input snake_case : List[str] = input_ids.clamp(self.pad_token_id + 1 ) snake_case : List[str] = decoder_input_ids.clamp(self.pad_token_id + 1 ) snake_case : str = self.get_config() snake_case : Tuple = config.num_attention_heads snake_case : List[Any] = self.prepare_inputs_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return config, input_dict def lowerCAmelCase( self : Dict ): """simple docstring""" snake_case , snake_case : List[str] = self.prepare_config_and_inputs() return config, inputs_dict def lowerCAmelCase( self : Dict ): """simple docstring""" return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def lowerCAmelCase( self : Tuple ): """simple docstring""" return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , ): """simple docstring""" snake_case : str = UMTaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() snake_case : str = model( input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , decoder_attention_mask=UpperCAmelCase__ , ) snake_case : int = model(input_ids=UpperCAmelCase__ , decoder_input_ids=UpperCAmelCase__ ) snake_case : int = result.last_hidden_state snake_case : Dict = result.past_key_values snake_case : Dict = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(UpperCAmelCase__ ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def lowerCAmelCase( self : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , ): """simple docstring""" snake_case : int = UMTaModel(config=UpperCAmelCase__ ).get_decoder().to(UpperCAmelCase__ ).eval() # first forward pass snake_case : List[Any] = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) snake_case : List[Any] = model(UpperCAmelCase__ ) snake_case : Any = model(UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) self.parent.assertTrue(len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) ) self.parent.assertTrue(len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) + 1 ) snake_case , snake_case : List[str] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids snake_case : Any = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and snake_case : Union[str, Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case : Any = model(UpperCAmelCase__ )['''last_hidden_state'''] snake_case : Optional[Any] = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )['''last_hidden_state'''] # select random slice snake_case : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() snake_case : Tuple = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1e-3 ) ) def lowerCAmelCase( self : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , ): """simple docstring""" snake_case : int = UMTaModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).half().eval() snake_case : str = model(**UpperCAmelCase__ )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(UpperCAmelCase__ ).any().item() ) @require_torch class a_ ( a , a , a , unittest.TestCase ): A__ : str = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) A__ : str = (UMTaForConditionalGeneration,) if is_torch_available() else () A__ : Any = ( { 'conversational': UMTaForConditionalGeneration, 'feature-extraction': UMTaModel, 'summarization': UMTaForConditionalGeneration, 'text2text-generation': UMTaForConditionalGeneration, 'translation': UMTaForConditionalGeneration, 'question-answering': UMTaForQuestionAnswering, } if is_torch_available() else {} ) A__ : Dict = True A__ : List[str] = False A__ : Optional[int] = False A__ : Optional[int] = True A__ : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests A__ : int = [0.8, 0.9] def lowerCAmelCase( self : Optional[Any] ): """simple docstring""" snake_case : Union[str, Any] = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def lowerCAmelCase( self : Optional[int] ): """simple docstring""" snake_case : Tuple = self.model_tester.prepare_config_and_inputs() snake_case : Optional[Any] = UMTaModel(config_and_inputs[0] ).to(UpperCAmelCase__ ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( UpperCAmelCase__ , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=UpperCAmelCase__ , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def lowerCAmelCase( self : List[Any] ): """simple docstring""" snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*UpperCAmelCase__ ) def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : Optional[int] = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() snake_case : int = config_and_inputs[0] snake_case : Union[str, Any] = UMTaForConditionalGeneration(UpperCAmelCase__ ).eval() model.to(UpperCAmelCase__ ) snake_case : str = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=UpperCAmelCase__ ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ), } for attn_name, (name, mask) in zip(UpperCAmelCase__ , head_masking.items() ): snake_case : int = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": snake_case : List[str] = torch.ones( config.num_decoder_layers , config.num_heads , device=UpperCAmelCase__ ) snake_case : Union[str, Any] = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=UpperCAmelCase__ , return_dict_in_generate=UpperCAmelCase__ , **UpperCAmelCase__ , ) # We check the state of decoder_attentions and cross_attentions just from the last step snake_case : List[str] = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def lowerCAmelCase( self : Any ): """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class a_ ( unittest.TestCase ): @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def lowerCAmelCase( self : int ): """simple docstring""" snake_case : Optional[Any] = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=UpperCAmelCase__ ).to(UpperCAmelCase__ ) snake_case : int = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=UpperCAmelCase__ , legacy=UpperCAmelCase__ ) snake_case : List[str] = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] snake_case : Dict = tokenizer(UpperCAmelCase__ , return_tensors='''pt''' , padding=UpperCAmelCase__ ).input_ids # fmt: off snake_case : Optional[Any] = torch.tensor( [ [ 38_530, 210_703, 256_299, 1_410, 256_298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25_922, 256_299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_460, 339, 312, 19_014, 10_620, 758, 256_299, 2_355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256_299, 14_869, 281, 301, 256_298, 275, 119_983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256_299, 14_869, 281, 2_234, 289, 2_275, 333,61_391, 289, 256_298, 543, 256_297, 168_714, 329, 256_296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(UpperCAmelCase__ , UpperCAmelCase__ ) snake_case : List[Any] = model.generate(input_ids.to(UpperCAmelCase__ ) ) snake_case : int = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] snake_case : Tuple = tokenizer.batch_decode(UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
84
0
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger _a : Union[str, Any] = get_logger(__name__) class a_ ( enum.Enum ): A__ : List[Any] = 'all_checks' A__ : List[Any] = 'basic_checks' A__ : Union[str, Any] = 'no_checks' class a_ ( a ): pass class a_ ( a ): pass class a_ ( a ): pass class a_ ( a ): pass def a_ ( __magic_name__ , __magic_name__ , __magic_name__=None ) -> List[Any]: """simple docstring""" if expected_checksums is None: logger.info('''Unable to verify checksums.''' ) return if len(set(__magic_name__ ) - set(__magic_name__ ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(__magic_name__ ) - set(__magic_name__ ) ) ) if len(set(__magic_name__ ) - set(__magic_name__ ) ) > 0: raise UnexpectedDownloadedFile(str(set(__magic_name__ ) - set(__magic_name__ ) ) ) snake_case : Tuple = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] snake_case : Dict = ''' for ''' + verification_name if verification_name is not None else '''''' if len(__magic_name__ ) > 0: raise NonMatchingChecksumError( F"Checksums didn't match{for_verification_name}:\n" F"{bad_urls}\n" '''Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error''' ) logger.info('''All the checksums matched successfully''' + for_verification_name ) class a_ ( a ): pass class a_ ( a ): pass class a_ ( a ): pass class a_ ( a ): pass def a_ ( __magic_name__ , __magic_name__ ) -> Optional[int]: """simple docstring""" if expected_splits is None: logger.info('''Unable to verify splits sizes.''' ) return if len(set(__magic_name__ ) - set(__magic_name__ ) ) > 0: raise ExpectedMoreSplits(str(set(__magic_name__ ) - set(__magic_name__ ) ) ) if len(set(__magic_name__ ) - set(__magic_name__ ) ) > 0: raise UnexpectedSplits(str(set(__magic_name__ ) - set(__magic_name__ ) ) ) snake_case : List[Any] = [ {'''expected''': expected_splits[name], '''recorded''': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(__magic_name__ ) > 0: raise NonMatchingSplitsSizesError(str(__magic_name__ ) ) logger.info('''All the splits matched successfully.''' ) def a_ ( __magic_name__ , __magic_name__ = True ) -> dict: """simple docstring""" if record_checksum: snake_case : List[Any] = shaaaa() with open(__magic_name__ , '''rb''' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , b'''''' ): m.update(__magic_name__ ) snake_case : Optional[Any] = m.hexdigest() else: snake_case : Any = None return {"num_bytes": os.path.getsize(__magic_name__ ), "checksum": checksum} def a_ ( __magic_name__ ) -> Union[str, Any]: """simple docstring""" if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
709
import torch from diffusers import DiffusionPipeline class a_ ( a ): def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ): """simple docstring""" super().__init__() self.register_modules(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) def __call__( self : Optional[int] ): """simple docstring""" snake_case : Any = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) snake_case : Dict = 1 snake_case : Optional[Any] = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample snake_case : List[Any] = self.scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ).prev_sample snake_case : List[Any] = scheduler_output - scheduler_output + torch.ones_like(UpperCAmelCase__ ) return result
84
0
from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class a_ ( a ): A__ : Optional[torch.FloatTensor] = None A__ : torch.FloatTensor = None A__ : Optional[Tuple[torch.FloatTensor]] = None A__ : Optional[Tuple[torch.FloatTensor]] = None class a_ ( a ): def __init__( self : Tuple , UpperCAmelCase__ : Tuple=1 , UpperCAmelCase__ : str=0 , UpperCAmelCase__ : Tuple=2 , UpperCAmelCase__ : Optional[Any]=512 , UpperCAmelCase__ : Optional[int]="cls" , UpperCAmelCase__ : int=False , UpperCAmelCase__ : Optional[int]=True , **UpperCAmelCase__ : Any , ): """simple docstring""" super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) snake_case : Any = project_dim snake_case : Tuple = pooler_fn snake_case : Tuple = learn_encoder snake_case : List[Any] = use_attention_mask class a_ ( a ): A__ : Dict = [r'pooler', r'logit_scale'] A__ : Any = [r'position_ids', r'predictions.decoder.bias'] A__ : Optional[Any] = 'roberta' A__ : Optional[Any] = RobertaSeriesConfig def __init__( self : Tuple , UpperCAmelCase__ : Any ): """simple docstring""" super().__init__(UpperCAmelCase__ ) snake_case : int = XLMRobertaModel(UpperCAmelCase__ ) snake_case : List[Any] = nn.Linear(config.hidden_size , config.project_dim ) snake_case : Dict = getattr(UpperCAmelCase__ , '''has_pre_transformation''' , UpperCAmelCase__ ) if self.has_pre_transformation: snake_case : Dict = nn.Linear(config.hidden_size , config.project_dim ) snake_case : Optional[Any] = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def lowerCAmelCase( self : Optional[Any] , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[torch.Tensor] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , ): """simple docstring""" snake_case : List[str] = return_dict if return_dict is not None else self.config.use_return_dict snake_case : Optional[int] = self.base_model( input_ids=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , position_ids=UpperCAmelCase__ , head_mask=UpperCAmelCase__ , inputs_embeds=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , output_attentions=UpperCAmelCase__ , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=UpperCAmelCase__ , ) if self.has_pre_transformation: snake_case : Dict = outputs['''hidden_states'''][-2] snake_case : str = self.pre_LN(UpperCAmelCase__ ) snake_case : List[Any] = self.transformation_pre(UpperCAmelCase__ ) return TransformationModelOutput( projection_state=UpperCAmelCase__ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: snake_case : List[str] = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=UpperCAmelCase__ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
710
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a_ ( a ): A__ : List[str] = ['image_processor', 'tokenizer'] A__ : Any = 'CLIPImageProcessor' A__ : Optional[int] = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : Union[str, Any] , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Optional[int] ): """simple docstring""" snake_case : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , UpperCAmelCase__ , ) snake_case : List[Any] = kwargs.pop('''feature_extractor''' ) snake_case : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(UpperCAmelCase__ , UpperCAmelCase__ ) def __call__( self : Any , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : Union[str, Any] ): """simple docstring""" if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: snake_case : int = self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if images is not None: snake_case : Dict = self.image_processor(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) if text is not None and images is not None: snake_case : Tuple = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase__ ) , tensor_type=UpperCAmelCase__ ) def lowerCAmelCase( self : List[str] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : int ): """simple docstring""" return self.tokenizer.batch_decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) def lowerCAmelCase( self : Optional[int] , *UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : str ): """simple docstring""" return self.tokenizer.decode(*UpperCAmelCase__ , **UpperCAmelCase__ ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" snake_case : int = self.tokenizer.model_input_names snake_case : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def lowerCAmelCase( self : Tuple ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , UpperCAmelCase__ , ) return self.image_processor_class @property def lowerCAmelCase( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , UpperCAmelCase__ , ) return self.image_processor
84
0