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 argparse from collections import defaultdict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] , UpperCamelCase__: Dict , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''{file}_{class_name}_{test_name}''' done_test[_id] += 1 with open(UpperCamelCase__ , """r""" ) as f: SCREAMING_SNAKE_CASE__ = f.readlines() SCREAMING_SNAKE_CASE__ = f'''class {class_name}(''' SCREAMING_SNAKE_CASE__ = f'''{4 * ' '}def {test_name}(''' SCREAMING_SNAKE_CASE__ = f'''{8 * ' '}{correct_line.split()[0]}''' SCREAMING_SNAKE_CASE__ = f'''{16 * ' '}{correct_line.split()[0]}''' SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = [] for line in lines: if line.startswith(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = True elif in_class and line.startswith(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = True elif in_class and in_func and (line.startswith(UpperCamelCase__ ) or line.startswith(UpperCamelCase__ )): SCREAMING_SNAKE_CASE__ = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: SCREAMING_SNAKE_CASE__ = True if in_class and in_func and in_line: if ")" not in line: continue else: SCREAMING_SNAKE_CASE__ = True if in_class and in_func and in_line and insert_line: new_lines.append(f'''{spaces * ' '}{correct_line}''' ) SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = False else: new_lines.append(UpperCamelCase__ ) with open(UpperCamelCase__ , """w""" ) as f: for line in new_lines: f.write(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Union[str, Any]=None ): if fail is not None: with open(UpperCamelCase__ , """r""" ) as f: SCREAMING_SNAKE_CASE__ = {l.strip() for l in f.readlines()} else: SCREAMING_SNAKE_CASE__ = None with open(UpperCamelCase__ , """r""" ) as f: SCREAMING_SNAKE_CASE__ = f.readlines() SCREAMING_SNAKE_CASE__ = defaultdict(UpperCamelCase__ ) for line in correct_lines: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = line.split(""";""" ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument('--correct_filename', help='filename of tests with expected result') parser.add_argument('--fail_filename', help='filename of test failures', type=str, default=None) _lowerCamelCase = parser.parse_args() main(args.correct_filename, args.fail_filename)
711
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RoCBertTokenizer lowerCamelCase_ = None lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = filter_non_english def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(__A , __A , ensure_ascii=__A ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(__A , __A , ensure_ascii=__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(__A , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__A ) , [5, 6, 2, 5, 7, 8] ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=__A , 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 _snake_case ( self :Any ) -> str: """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 _snake_case ( self :int ) -> str: """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 _snake_case ( self :List[str] ) -> List[str]: """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 _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def _snake_case ( self :int ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(__A , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE__ = ( [ ((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 _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你好""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你是谁""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( __A , __A , __A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(__A , add_special_tokens=__A ) self.assertEqual(__A , __A )
59
0
import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ = 8 # DPR tok SCREAMING_SNAKE_CASE__ = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """dpr_tokenizer""" ) os.makedirs(__A , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , DPR_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] ) ) # BART tok SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] SCREAMING_SNAKE_CASE__ = {"""unk_token""": """<unk>"""} SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """bart_tokenizer""" ) os.makedirs(__A , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , BART_VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , BART_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 _snake_case ( self :Union[str, Any] ) -> DPRQuestionEncoderTokenizer: """simple docstring""" return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def _snake_case ( self :List[Any] ) -> DPRContextEncoderTokenizer: """simple docstring""" return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def _snake_case ( self :Union[str, Any] ) -> BartTokenizer: """simple docstring""" return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , """bart_tokenizer""" ) ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = Dataset.from_dict( { """id""": ["""0""", """1"""], """text""": ["""foo""", """bar"""], """title""": ["""Foo""", """Bar"""], """embeddings""": [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index("""embeddings""" , string_factory="""Flat""" , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_dummy_dataset() SCREAMING_SNAKE_CASE__ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch("""transformers.models.rag.retrieval_rag.load_dataset""" ) as mock_load_dataset: SCREAMING_SNAKE_CASE__ = dataset SCREAMING_SNAKE_CASE__ = RagRetriever( __A , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def _snake_case ( self :Union[str, Any] , __A :bool ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_dummy_dataset() SCREAMING_SNAKE_CASE__ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="""custom""" , ) if from_disk: SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """dataset""" ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """index.faiss""" ) dataset.get_index("""embeddings""" ).save(os.path.join(self.tmpdirname , """index.faiss""" ) ) dataset.drop_index("""embeddings""" ) dataset.save_to_disk(os.path.join(self.tmpdirname , """dataset""" ) ) del dataset SCREAMING_SNAKE_CASE__ = RagRetriever( __A , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: SCREAMING_SNAKE_CASE__ = RagRetriever( __A , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , __A ) , ) return retriever def _snake_case ( self :Tuple ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = Dataset.from_dict( { """id""": ["""0""", """1"""], """text""": ["""foo""", """bar"""], """title""": ["""Foo""", """Bar"""], """embeddings""": [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index("""embeddings""" , string_factory="""Flat""" , metric_type=faiss.METRIC_INNER_PRODUCT ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """hf_bert_base.hnswSQ8_correct_phi_128.c_index""" ) dataset.save_faiss_index("""embeddings""" , index_file_name + """.index.dpr""" ) pickle.dump(dataset["""id"""] , open(index_file_name + """.index_meta.dpr""" , """wb""" ) ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """psgs_w100.tsv.pkl""" ) SCREAMING_SNAKE_CASE__ = {sample["""id"""]: [sample["""text"""], sample["""title"""]] for sample in dataset} pickle.dump(__A , open(__A , """wb""" ) ) SCREAMING_SNAKE_CASE__ = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name="""legacy""" , index_path=self.tmpdirname , ) SCREAMING_SNAKE_CASE__ = RagRetriever( __A , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = retriever.retrieve(__A , n_docs=__A ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__A ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""embeddings""", """id""", """text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""id"""] ) , __A ) self.assertEqual(doc_dicts[0]["""id"""][0] , """1""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""id"""][0] , """0""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _snake_case ( self :Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch("""transformers.models.rag.retrieval_rag.load_dataset""" ) as mock_load_dataset: SCREAMING_SNAKE_CASE__ = self.get_dummy_dataset() retriever.save_pretrained(__A ) SCREAMING_SNAKE_CASE__ = RagRetriever.from_pretrained(__A ) self.assertIsInstance(__A , __A ) SCREAMING_SNAKE_CASE__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = retriever.retrieve(__A , n_docs=1 ) self.assertTrue(out is not None ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = self.get_dummy_custom_hf_index_retriever(from_disk=__A ) SCREAMING_SNAKE_CASE__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = retriever.retrieve(__A , n_docs=__A ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__A ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""embeddings""", """id""", """text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""id"""] ) , __A ) self.assertEqual(doc_dicts[0]["""id"""][0] , """1""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""id"""][0] , """0""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_dummy_custom_hf_index_retriever(from_disk=__A ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(__A ) SCREAMING_SNAKE_CASE__ = RagRetriever.from_pretrained(__A ) self.assertIsInstance(__A , __A ) SCREAMING_SNAKE_CASE__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = retriever.retrieve(__A , n_docs=1 ) self.assertTrue(out is not None ) def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = self.get_dummy_custom_hf_index_retriever(from_disk=__A ) SCREAMING_SNAKE_CASE__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = retriever.retrieve(__A , n_docs=__A ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__A ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""embeddings""", """id""", """text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""id"""] ) , __A ) self.assertEqual(doc_dicts[0]["""id"""][0] , """1""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""id"""][0] , """0""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_dummy_custom_hf_index_retriever(from_disk=__A ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(__A ) SCREAMING_SNAKE_CASE__ = RagRetriever.from_pretrained(__A ) self.assertIsInstance(__A , __A ) SCREAMING_SNAKE_CASE__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = retriever.retrieve(__A , n_docs=1 ) self.assertTrue(out is not None ) def _snake_case ( self :Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = self.get_dummy_legacy_index_retriever() SCREAMING_SNAKE_CASE__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = retriever.retrieve(__A , n_docs=__A ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(__A ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ["""text""", """title"""] ) self.assertEqual(len(doc_dicts[0]["""text"""] ) , __A ) self.assertEqual(doc_dicts[0]["""text"""][0] , """bar""" ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]["""text"""][0] , """foo""" ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def _snake_case ( self :int ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(__A ) SCREAMING_SNAKE_CASE__ = RagRetriever.from_pretrained(__A ) self.assertIsInstance(__A , __A ) SCREAMING_SNAKE_CASE__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = retriever.retrieve(__A , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def _snake_case ( self :Dict ) -> Tuple: """simple docstring""" import torch SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE__ = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = retriever(__A , __A , prefix=retriever.config.generator.prefix , n_docs=__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = ( out["""context_input_ids"""], out["""context_attention_mask"""], out["""retrieved_doc_embeds"""], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(__A , __A ) self.assertIsInstance(__A , __A ) self.assertIsInstance(__A , np.ndarray ) SCREAMING_SNAKE_CASE__ = retriever( __A , __A , prefix=retriever.config.generator.prefix , n_docs=__A , return_tensors="""pt""" , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = ( # noqa: F841 out["""context_input_ids"""], out["""context_attention_mask"""], out["""retrieved_doc_embeds"""], out["""doc_ids"""], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(__A , torch.Tensor ) self.assertIsInstance(__A , torch.Tensor ) self.assertIsInstance(__A , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_dpr_ctx_encoder_tokenizer() SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = self.get_dummy_custom_hf_index_retriever(from_disk=__A ) retriever.set_ctx_encoder_tokenizer(__A ) SCREAMING_SNAKE_CASE__ = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE__ = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = retriever(__A , __A , prefix=retriever.config.generator.prefix , n_docs=__A ) self.assertEqual( len(__A ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ("""tokenized_doc_ids""", """tokenized_doc_attention_mask""") ) , __A ) # check for doc token related keys in dictionary.
712
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = original_name.split(""".""" )[0] SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 2] ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 1] ) SCREAMING_SNAKE_CASE__ = orig_block_num - offset SCREAMING_SNAKE_CASE__ = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = OrderedDict() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): SCREAMING_SNAKE_CASE__ = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 SCREAMING_SNAKE_CASE__ = key[: key.find("""proj""" )] SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , f'''patch_embeddings.{total_embed_found}.''' ) SCREAMING_SNAKE_CASE__ = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: SCREAMING_SNAKE_CASE__ = """poolformer.encoder.""" + key if "mlp.fc1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm1""" , """before_norm""" ) if "norm2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: SCREAMING_SNAKE_CASE__ = key.replace("""head""" , """classifier""" ) SCREAMING_SNAKE_CASE__ = value return new_state_dict def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = PoolFormerConfig() # set attributes based on model_name SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = model_name[-3:] SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = (1, 1_000) # set config attributes SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if size == "s12": SCREAMING_SNAKE_CASE__ = [2, 2, 6, 2] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s24": SCREAMING_SNAKE_CASE__ = [4, 4, 12, 4] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "m36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 elif size == "m48": SCREAMING_SNAKE_CASE__ = [8, 8, 24, 8] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) # Prepare image SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location=torch.device("""cpu""" ) ) # rename keys SCREAMING_SNAKE_CASE__ = rename_keys(UpperCamelCase__ ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ = PoolFormerForImageClassification(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Define image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.logits # define expected logit slices for different models if size == "s12": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": SCREAMING_SNAKE_CASE__ = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": SCREAMING_SNAKE_CASE__ = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": SCREAMING_SNAKE_CASE__ = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , UpperCamelCase__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ShapEPipeline lowerCamelCase_ = ["prompt"] lowerCamelCase_ = ["prompt"] lowerCamelCase_ = [ "num_images_per_prompt", "num_inference_steps", "generator", "latents", "guidance_scale", "frame_size", "output_type", "return_dict", ] lowerCamelCase_ = False @property def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" return 32 @property def _snake_case ( self :Dict ) -> str: """simple docstring""" return 32 @property def _snake_case ( self :str ) -> Tuple: """simple docstring""" return self.time_input_dim * 4 @property def _snake_case ( self :Optional[int] ) -> Any: """simple docstring""" return 8 @property def _snake_case ( self :Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def _snake_case ( self :Tuple ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__A ) @property def _snake_case ( self :str ) -> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } SCREAMING_SNAKE_CASE__ = PriorTransformer(**__A ) return model @property def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } SCREAMING_SNAKE_CASE__ = ShapERenderer(**__A ) return model def _snake_case ( self :int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dummy_prior SCREAMING_SNAKE_CASE__ = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ = self.dummy_tokenizer SCREAMING_SNAKE_CASE__ = self.dummy_renderer SCREAMING_SNAKE_CASE__ = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1024 , prediction_type="""sample""" , use_karras_sigmas=__A , clip_sample=__A , clip_sample_range=1.0 , ) SCREAMING_SNAKE_CASE__ = { """prior""": prior, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """renderer""": renderer, """scheduler""": scheduler, } return components def _snake_case ( self :List[Any] , __A :Tuple , __A :List[str]=0 ) -> Optional[int]: """simple docstring""" if str(__A ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ = torch.manual_seed(__A ) else: SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(__A ) SCREAMING_SNAKE_CASE__ = { """prompt""": """horse""", """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = """cpu""" SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**__A ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = pipe(**self.get_dummy_inputs(__A ) ) SCREAMING_SNAKE_CASE__ = output.images[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) SCREAMING_SNAKE_CASE__ = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :Dict ) -> Any: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def _snake_case ( self :Union[str, Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch_device == """cpu""" SCREAMING_SNAKE_CASE__ = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__A , relax_max_difference=__A , ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**__A ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 2 SCREAMING_SNAKE_CASE__ = self.get_dummy_inputs(__A ) for key in inputs.keys(): if key in self.batch_params: SCREAMING_SNAKE_CASE__ = batch_size * [inputs[key]] SCREAMING_SNAKE_CASE__ = pipe(**__A , num_images_per_prompt=__A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_np_out.npy""" ) SCREAMING_SNAKE_CASE__ = ShapEPipeline.from_pretrained("""openai/shap-e""" ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ = pipe( """a shark""" , generator=__A , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__A , __A )
713
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_text_model" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :Union[str, Any] , __A :Any=5_0244 , __A :Optional[Any]=768 , __A :Tuple=64 , __A :List[str]=2048 , __A :int=12 , __A :str=12 , __A :Any=32 , __A :Tuple=128 , __A :int=0.1 , __A :str=1E-6 , __A :Optional[Any]=1.0 , __A :Union[str, Any]="gelu_new" , __A :Any=0 , __A :List[str]=False , __A :Optional[Any]=0 , __A :int=1 , __A :Optional[int]=False , __A :Optional[Any]=True , **__A :List[Any] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = d_kv SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = num_layers SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = decoder_start_token_id # for backwards compatibility SCREAMING_SNAKE_CASE__ = dense_act_fn super().__init__( pad_token_id=__A , eos_token_id=__A , decoder_start_token_id=__A , tie_word_embeddings=__A , is_decoder=__A , **__A , ) @classmethod def _snake_case ( cls :Optional[int] , __A :Union[str, os.PathLike] , **__A :Optional[int] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = 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(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_vision_model" def __init__( self :Optional[int] , __A :int=768 , __A :Optional[Any]=768 , __A :Union[str, Any]=2048 , __A :int=64 , __A :Union[str, Any]=12 , __A :str=12 , __A :Any="gelu_new" , __A :List[Any]=1E-6 , __A :Dict=0.0 , __A :int=0.0 , __A :int=1E-10 , __A :Dict=1.0 , __A :int=4096 , __A :int=32 , __A :int=128 , **__A :Tuple , ) -> str: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = patch_embed_hidden_size SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = dense_act_fn SCREAMING_SNAKE_CASE__ = seq_len SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = d_kv @classmethod def _snake_case ( cls :str , __A :Union[str, os.PathLike] , **__A :str ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = 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(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct" lowerCamelCase_ = True def __init__( self :str , __A :Optional[Any]=None , __A :List[str]=None , __A :Optional[Any]=1.0 , __A :Optional[Any]=0.0_2 , __A :Any=False , __A :Tuple=False , __A :Any=True , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__(tie_word_embeddings=__A , is_encoder_decoder=__A , **__A ) if text_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE__ = PixaStructTextConfig(**__A ) SCREAMING_SNAKE_CASE__ = PixaStructVisionConfig(**__A ) SCREAMING_SNAKE_CASE__ = self.text_config.decoder_start_token_id SCREAMING_SNAKE_CASE__ = self.text_config.pad_token_id SCREAMING_SNAKE_CASE__ = self.text_config.eos_token_id SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = is_vqa @classmethod def _snake_case ( cls :Union[str, Any] , __A :PixaStructTextConfig , __A :PixaStructVisionConfig , **__A :Optional[int] ) -> Optional[Any]: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__A ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
0
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RobertaTokenizer lowerCamelCase_ = RobertaTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = {"cls_token": "<s>"} def _snake_case ( self :List[str] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] SCREAMING_SNAKE_CASE__ = {"""unk_token""": """<unk>"""} SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__A ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :List[str] , **__A :List[Any] ) -> List[str]: """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__A ) def _snake_case ( self :Union[str, Any] , **__A :int ) -> List[Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **__A ) def _snake_case ( self :str , __A :Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = """lower newer""" SCREAMING_SNAKE_CASE__ = """lower newer""" return input_text, output_text def _snake_case ( self :List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ = """lower newer""" SCREAMING_SNAKE_CASE__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) # , add_prefix_space=True) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=__A ) , [0, 3_1414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=__A ) , [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2] , ) @slow def _snake_case ( self :List[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained("""roberta-base""" ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""sequence builders""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode( """sequence builders""" , add_special_tokens=__A , add_prefix_space=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=__A , add_prefix_space=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = """Encode this sequence.""" SCREAMING_SNAKE_CASE__ = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A , add_special_tokens=__A , add_prefix_space=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A , add_special_tokens=__A , add_prefix_space=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(__A , __A ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(__A , __A ) # Testing spaces after special tokens SCREAMING_SNAKE_CASE__ = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(__A , lstrip=__A , rstrip=__A )} ) # mask token has a left space SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = """Encode <mask> sequence""" SCREAMING_SNAKE_CASE__ = """Encode <mask>sequence""" SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A ) SCREAMING_SNAKE_CASE__ = encoded.index(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A ) SCREAMING_SNAKE_CASE__ = encoded.index(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(__A , __A ) def _snake_case ( self :List[Any] ) -> List[str]: """simple docstring""" pass def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = """A, <mask> AllenNLP sentence.""" SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus(__A , add_special_tokens=__A , return_token_type_ids=__A ) SCREAMING_SNAKE_CASE__ = 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"""] ) , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = 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, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( __A , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( __A , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def _snake_case ( self :List[str] ) -> List[Any]: """simple docstring""" for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) SCREAMING_SNAKE_CASE__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , __A ) self.assertEqual(post_processor_state["""add_prefix_space"""] , __A ) self.assertEqual(post_processor_state["""trim_offsets"""] , __A ) def _snake_case ( self :Optional[int] ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` SCREAMING_SNAKE_CASE__ = f'''{text_of_1_token} {text_of_1_token}''' SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__A ) + 1, len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__A ) + 1, len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__A ), len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__A ), len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = f''' {text}''' # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__A ) + 1, 1 + len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__A ), 1 + len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__A ), 1 + len(__A ) + 1 + len(__A )) , )
714
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[int] ) -> str: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__A , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = Accelerator() _lowerCamelCase = (accelerator.state.process_index + 2, 10) _lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device) _lowerCamelCase = '' _lowerCamelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." _lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." _lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
0
import random def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: str , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = a[left_index] SCREAMING_SNAKE_CASE__ = left_index + 1 for j in range(left_index + 1 , UpperCamelCase__ ): if a[j] < pivot: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = a[i], a[j] i += 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = a[i - 1], a[left_index] return i - 1 def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] , UpperCamelCase__: List[Any] , UpperCamelCase__: str ): if left < right: SCREAMING_SNAKE_CASE__ = random.randint(UpperCamelCase__ , right - 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound SCREAMING_SNAKE_CASE__ = partition(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) quick_sort_random( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # recursive quicksort to the left of the pivot point quick_sort_random( UpperCamelCase__ , pivot_index + 1 , UpperCamelCase__ ) # recursive quicksort to the right of the pivot point def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = input("""Enter numbers separated by a comma:\n""" ).strip() SCREAMING_SNAKE_CASE__ = [int(UpperCamelCase__ ) for item in user_input.split(""",""" )] quick_sort_random(UpperCamelCase__ , 0 , len(UpperCamelCase__ ) ) print(UpperCamelCase__ ) if __name__ == "__main__": main()
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCamelCase = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3FeatureExtractor'] _lowerCamelCase = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
0
import itertools import string from collections.abc import Generator, Iterable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Iterable[str] , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = iter(UpperCamelCase__ ) while True: SCREAMING_SNAKE_CASE__ = tuple(itertools.islice(UpperCamelCase__ , UpperCamelCase__ ) ) if not chunk: return yield chunk def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = """""".join([c.upper() for c in dirty if c in string.ascii_letters] ) SCREAMING_SNAKE_CASE__ = """""" if len(UpperCamelCase__ ) < 2: return dirty for i in range(len(UpperCamelCase__ ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(UpperCamelCase__ ) & 1: clean += "X" return clean def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): # I and J are used interchangeably to allow # us to use a 5x5 table (25 letters) SCREAMING_SNAKE_CASE__ = """ABCDEFGHIKLMNOPQRSTUVWXYZ""" # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler SCREAMING_SNAKE_CASE__ = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(UpperCamelCase__ ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(UpperCamelCase__ ) return table def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = generate_table(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = prepare_input(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = """""" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(UpperCamelCase__ , 2 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = divmod(table.index(UpperCamelCase__ ) , 5 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = divmod(table.index(UpperCamelCase__ ) , 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = generate_table(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = """""" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(UpperCamelCase__ , 2 ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = divmod(table.index(UpperCamelCase__ ) , 5 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = divmod(table.index(UpperCamelCase__ ) , 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
716
import inspect import unittest class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self :Any ) -> Any: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ = inspect.getmembers(__A , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ = """k-diffusion""" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ = """invisible-watermark""" assert backend in deps, f'''{backend} is not in the deps table!'''
59
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_lxmert import LxmertTokenizer _lowerCamelCase = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _lowerCamelCase = { 'vocab_file': { 'unc-nlp/lxmert-base-uncased': 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt', }, 'tokenizer_file': { 'unc-nlp/lxmert-base-uncased': ( 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json' ), }, } _lowerCamelCase = { 'unc-nlp/lxmert-base-uncased': 512, } _lowerCamelCase = { 'unc-nlp/lxmert-base-uncased': {'do_lower_case': True}, } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = PRETRAINED_INIT_CONFIGURATION lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = LxmertTokenizer def __init__( self :List[str] , __A :Tuple=None , __A :Dict=None , __A :str=True , __A :Optional[Any]="[UNK]" , __A :Union[str, Any]="[SEP]" , __A :str="[PAD]" , __A :Optional[Any]="[CLS]" , __A :Tuple="[MASK]" , __A :Tuple=True , __A :Dict=None , **__A :Optional[Any] , ) -> Optional[int]: """simple docstring""" super().__init__( __A , tokenizer_file=__A , do_lower_case=__A , unk_token=__A , sep_token=__A , pad_token=__A , cls_token=__A , mask_token=__A , tokenize_chinese_chars=__A , strip_accents=__A , **__A , ) SCREAMING_SNAKE_CASE__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __A ) != do_lower_case or normalizer_state.get("""strip_accents""" , __A ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __A ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE__ = getattr(__A , normalizer_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ = do_lower_case SCREAMING_SNAKE_CASE__ = strip_accents SCREAMING_SNAKE_CASE__ = tokenize_chinese_chars SCREAMING_SNAKE_CASE__ = normalizer_class(**__A ) SCREAMING_SNAKE_CASE__ = do_lower_case def _snake_case ( self :str , __A :Dict , __A :str=None ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [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 _snake_case ( self :str , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self :List[str] , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._tokenizer.model.save(__A , name=__A ) return tuple(__A )
717
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 _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
59
0
'''simple docstring''' import qiskit def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register SCREAMING_SNAKE_CASE__ = qiskit.QuantumCircuit(UpperCamelCase__ , UpperCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator SCREAMING_SNAKE_CASE__ = qiskit.execute(UpperCamelCase__ , UpperCamelCase__ , shots=1_000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(UpperCamelCase__ ) if __name__ == "__main__": print(F'''Total count for various states are: {single_qubit_measure(1, 1)}''')
718
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = OpenAIGPTTokenizer lowerCamelCase_ = OpenAIGPTTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Union[str, Any] , __A :str ) -> List[Any]: """simple docstring""" return "lower newer", "lower newer" def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE__ = """lower""" SCREAMING_SNAKE_CASE__ = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] , __A :Optional[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) # Simple input SCREAMING_SNAKE_CASE__ = """This is a simple input""" SCREAMING_SNAKE_CASE__ = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE__ = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) # Pair input self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ ): pass
59
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
719
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
0
def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] SCREAMING_SNAKE_CASE__ = 6 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 1_901 SCREAMING_SNAKE_CASE__ = 0 while year < 2_001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 SCREAMING_SNAKE_CASE__ = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 SCREAMING_SNAKE_CASE__ = day - 29 else: if day > days_per_month[month - 1]: month += 1 SCREAMING_SNAKE_CASE__ = day - days_per_month[month - 2] if month > 12: year += 1 SCREAMING_SNAKE_CASE__ = 1 if year < 2_001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
720
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
0
_lowerCamelCase = [ 'Audio', 'Array2D', 'Array3D', 'Array4D', 'Array5D', 'ClassLabel', 'Features', 'Sequence', 'Value', 'Image', 'Translation', 'TranslationVariableLanguages', ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
721
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
59
0
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 UpperCamelCase_ : def __init__( self :str , __A :List[str] , __A :Union[str, Any]=99 , __A :Optional[int]=13 , __A :List[Any]=7 , __A :List[Any]=9 , __A :List[str]=True , __A :List[Any]=True , __A :List[Any]=False , __A :Tuple=32 , __A :int=5 , __A :Optional[int]=4 , __A :Dict=37 , __A :Union[str, Any]=8 , __A :Dict=0.1 , __A :Dict=0.0_0_2 , __A :Dict=1 , __A :Union[str, Any]=0 , __A :int=0 , __A :List[str]=None , __A :Optional[Any]=None , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = encoder_seq_length SCREAMING_SNAKE_CASE__ = decoder_seq_length # For common tests SCREAMING_SNAKE_CASE__ = self.decoder_seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_attention_mask SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = pad_token_id SCREAMING_SNAKE_CASE__ = decoder_start_token_id SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = decoder_layers def _snake_case ( self :Any ) -> str: """simple docstring""" return TaConfig.from_pretrained("""google/umt5-base""" ) def _snake_case ( self :Tuple , __A :int , __A :str , __A :List[str] , __A :Optional[Any]=None , __A :str=None , __A :int=None , __A :Optional[int]=None , __A :Dict=None , ) -> Any: """simple docstring""" if attention_mask is None: SCREAMING_SNAKE_CASE__ = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: SCREAMING_SNAKE_CASE__ = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=__A ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=__A ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=__A ) 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 _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ = input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ = decoder_input_ids.clamp(self.pad_token_id + 1 ) SCREAMING_SNAKE_CASE__ = self.get_config() SCREAMING_SNAKE_CASE__ = config.num_attention_heads SCREAMING_SNAKE_CASE__ = self.prepare_inputs_dict(__A , __A , __A ) return config, input_dict def _snake_case ( self :str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() return config, inputs_dict def _snake_case ( self :Any ) -> Optional[Any]: """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 _snake_case ( self :Dict ) -> Optional[Any]: """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 _snake_case ( self :Tuple , __A :List[str] , __A :Optional[Any] , __A :Tuple , __A :Any , __A :Optional[Any] , __A :int , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = UMTaModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model( input_ids=__A , decoder_input_ids=__A , attention_mask=__A , decoder_attention_mask=__A , ) SCREAMING_SNAKE_CASE__ = model(input_ids=__A , decoder_input_ids=__A ) SCREAMING_SNAKE_CASE__ = result.last_hidden_state SCREAMING_SNAKE_CASE__ = result.past_key_values SCREAMING_SNAKE_CASE__ = 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(__A ) , 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 _snake_case ( self :Optional[int] , __A :List[Any] , __A :str , __A :str , __A :Dict , __A :Optional[int] , __A :Any , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = UMTaModel(config=__A ).get_decoder().to(__A ).eval() # first forward pass SCREAMING_SNAKE_CASE__ = model(__A , use_cache=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = model(__A , use_cache=__A ) self.parent.assertTrue(len(__A ) == len(__A ) ) self.parent.assertTrue(len(__A ) == len(__A ) + 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and SCREAMING_SNAKE_CASE__ = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ = model(__A )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ = model(__A , past_key_values=__A )["""last_hidden_state"""] # select random slice SCREAMING_SNAKE_CASE__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__A , __A , atol=1E-3 ) ) def _snake_case ( self :str , __A :Union[str, Any] , __A :Optional[int] , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = UMTaModel(config=__A ).to(__A ).half().eval() SCREAMING_SNAKE_CASE__ = model(**__A )["""last_hidden_state"""] self.parent.assertFalse(torch.isnan(__A ).any().item() ) @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) lowerCamelCase_ = (UMTaForConditionalGeneration,) if is_torch_available() else () lowerCamelCase_ = ( { "conversational": UMTaForConditionalGeneration, "feature-extraction": UMTaModel, "summarization": UMTaForConditionalGeneration, "text2text-generation": UMTaForConditionalGeneration, "translation": UMTaForConditionalGeneration, "question-answering": UMTaForQuestionAnswering, } if is_torch_available() else {} ) lowerCamelCase_ = True lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = True # The small UMT5 model needs higher percentages for CPU/MP tests lowerCamelCase_ = [0.8, 0.9] def _snake_case ( self :List[str] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = UMTaModelTester(self ) @unittest.skip("""Test has a segmentation fault on torch 1.8.0""" ) def _snake_case ( self :Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ = UMTaModel(config_and_inputs[0] ).to(__A ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( __A , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f'''{tmpdirname}/t5_test.onnx''' , export_params=__A , opset_version=9 , input_names=["""input_ids""", """decoder_input_ids"""] , ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*__A ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""encoder_attentions""", """decoder_attentions""", """cross_attentions"""] SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ = config_and_inputs[0] SCREAMING_SNAKE_CASE__ = UMTaForConditionalGeneration(__A ).eval() model.to(__A ) SCREAMING_SNAKE_CASE__ = { """head_mask""": torch.zeros(config.num_layers , config.num_heads , device=__A ), """decoder_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=__A ), """cross_attn_head_mask""": torch.zeros(config.num_decoder_layers , config.num_heads , device=__A ), } for attn_name, (name, mask) in zip(__A , head_masking.items() ): SCREAMING_SNAKE_CASE__ = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": SCREAMING_SNAKE_CASE__ = torch.ones( config.num_decoder_layers , config.num_heads , device=__A ) SCREAMING_SNAKE_CASE__ = model.generate( config_and_inputs[1]["""input_ids"""] , num_beams=1 , max_length=3 , output_attentions=__A , return_dict_in_generate=__A , **__A , ) # We check the state of decoder_attentions and cross_attentions just from the last step SCREAMING_SNAKE_CASE__ = 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 _snake_case ( self :List[Any] ) -> int: """simple docstring""" pass @require_torch @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( 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 _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = UMTaForConditionalGeneration.from_pretrained("""google/umt5-small""" , return_dict=__A ).to(__A ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained("""google/umt5-small""" , use_fast=__A , legacy=__A ) SCREAMING_SNAKE_CASE__ = [ """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>.""", ] SCREAMING_SNAKE_CASE__ = tokenizer(__A , return_tensors="""pt""" , padding=__A ).input_ids # fmt: off SCREAMING_SNAKE_CASE__ = torch.tensor( [ [ 3_8530, 21_0703, 25_6299, 1410, 25_6298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 2_5922, 25_6299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 1_9014, 1_0620, 758, 25_6299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 25_6299, 1_4869, 281, 301, 25_6298, 275, 11_9983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 25_6299, 1_4869, 281, 2234, 289, 2275, 333,6_1391, 289, 25_6298, 543, 25_6297, 16_8714, 329, 25_6296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(__A , __A ) SCREAMING_SNAKE_CASE__ = model.generate(input_ids.to(__A ) ) SCREAMING_SNAKE_CASE__ = [ """<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>""", ] SCREAMING_SNAKE_CASE__ = tokenizer.batch_decode(__A ) self.assertEqual(__A , __A )
700
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__: float ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
59
0
'''simple docstring''' import random from typing import Any def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list ): for _ in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = random.randint(0 , len(UpperCamelCase__ ) - 1 ) SCREAMING_SNAKE_CASE__ = random.randint(0 , len(UpperCamelCase__ ) - 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = data[b], data[a] return data if __name__ == "__main__": _lowerCamelCase = [0, 1, 2, 3, 4, 5, 6, 7] _lowerCamelCase = ['python', 'says', 'hello', '!'] print('Fisher-Yates Shuffle:') print('List', integers, strings) print('FY Shuffle', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
701
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
0
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = [R"h\.\d+\.attn\.bias", R"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self :Any , __A :int , __A :int , __A :Optional[int] = None , __A :int = 5_0257 , __A :int = 1024 , __A :int = 768 , __A :int = 12 , __A :int = 12 , __A :Optional[int] = None , __A :str = "gelu_new" , __A :float = 0.1 , __A :float = 0.1 , __A :float = 0.1 , __A :float = 1E-5 , __A :float = 0.0_2 , __A :bool = True , __A :bool = True , __A :bool = False , __A :bool = False , ) -> List[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'''`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and''' f''' `n_embd`: {n_embd} are not equal.''' ) SCREAMING_SNAKE_CASE__ = prefix_inner_dim SCREAMING_SNAKE_CASE__ = prefix_hidden_dim SCREAMING_SNAKE_CASE__ = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) SCREAMING_SNAKE_CASE__ = ( nn.Linear(self.prefix_hidden_dim , __A ) if self.prefix_hidden_dim is not None else nn.Identity() ) SCREAMING_SNAKE_CASE__ = GPTaConfig( vocab_size=__A , n_positions=__A , n_embd=__A , n_layer=__A , n_head=__A , n_inner=__A , activation_function=__A , resid_pdrop=__A , embd_pdrop=__A , attn_pdrop=__A , layer_norm_epsilon=__A , initializer_range=__A , scale_attn_weights=__A , use_cache=__A , scale_attn_by_inverse_layer_idx=__A , reorder_and_upcast_attn=__A , ) SCREAMING_SNAKE_CASE__ = GPTaLMHeadModel(__A ) def _snake_case ( self :Optional[Any] , __A :torch.Tensor , __A :torch.Tensor , __A :Optional[torch.Tensor] = None , __A :Optional[torch.Tensor] = None , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.transformer.transformer.wte(__A ) SCREAMING_SNAKE_CASE__ = self.encode_prefix(__A ) SCREAMING_SNAKE_CASE__ = self.decode_prefix(__A ) SCREAMING_SNAKE_CASE__ = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: SCREAMING_SNAKE_CASE__ = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) SCREAMING_SNAKE_CASE__ = torch.cat((dummy_token, input_ids) , dim=1 ) SCREAMING_SNAKE_CASE__ = self.transformer(inputs_embeds=__A , labels=__A , attention_mask=__A ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def _snake_case ( self :Optional[int] , __A :int , __A :torch.device ) -> torch.Tensor: """simple docstring""" return torch.zeros(__A , self.prefix_length , dtype=torch.intaa , device=__A ) def _snake_case ( self :Optional[Any] , __A :Dict ) -> Optional[int]: """simple docstring""" return self.encode_prefix(__A ) @torch.no_grad() def _snake_case ( self :str , __A :List[str] , __A :List[Any] , __A :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch.split(__A , 1 , dim=0 ) SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] for feature in features: SCREAMING_SNAKE_CASE__ = self.decode_prefix(feature.to(__A ) ) # back to the clip feature # Only support beam search for now SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.generate_beam( input_embeds=__A , device=__A , eos_token_id=__A ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) SCREAMING_SNAKE_CASE__ = torch.stack(__A ) SCREAMING_SNAKE_CASE__ = torch.stack(__A ) return generated_tokens, generated_seq_lengths @torch.no_grad() def _snake_case ( self :List[str] , __A :Union[str, Any]=None , __A :Optional[int]=None , __A :List[Any]=None , __A :int = 5 , __A :int = 67 , __A :float = 1.0 , __A :Optional[int] = None , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = torch.ones(__A , device=__A , dtype=torch.int ) SCREAMING_SNAKE_CASE__ = torch.zeros(__A , device=__A , dtype=torch.bool ) if input_embeds is not None: SCREAMING_SNAKE_CASE__ = input_embeds else: SCREAMING_SNAKE_CASE__ = self.transformer.transformer.wte(__A ) for i in range(__A ): SCREAMING_SNAKE_CASE__ = self.transformer(inputs_embeds=__A ) SCREAMING_SNAKE_CASE__ = outputs.logits SCREAMING_SNAKE_CASE__ = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) SCREAMING_SNAKE_CASE__ = logits.softmax(-1 ).log() if scores is None: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = logits.topk(__A , -1 ) SCREAMING_SNAKE_CASE__ = generated.expand(__A , *generated.shape[1:] ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: SCREAMING_SNAKE_CASE__ = next_tokens else: SCREAMING_SNAKE_CASE__ = tokens.expand(__A , *tokens.shape[1:] ) SCREAMING_SNAKE_CASE__ = torch.cat((tokens, next_tokens) , dim=1 ) else: SCREAMING_SNAKE_CASE__ = -float(np.inf ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = scores[:, None] + logits seq_lengths[~is_stopped] += 1 SCREAMING_SNAKE_CASE__ = scores_sum / seq_lengths[:, None] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = scores_sum_average.view(-1 ).topk(__A , -1 ) SCREAMING_SNAKE_CASE__ = next_tokens // scores_sum.shape[1] SCREAMING_SNAKE_CASE__ = seq_lengths[next_tokens_source] SCREAMING_SNAKE_CASE__ = next_tokens % scores_sum.shape[1] SCREAMING_SNAKE_CASE__ = next_tokens.unsqueeze(1 ) SCREAMING_SNAKE_CASE__ = tokens[next_tokens_source] SCREAMING_SNAKE_CASE__ = torch.cat((tokens, next_tokens) , dim=1 ) SCREAMING_SNAKE_CASE__ = generated[next_tokens_source] SCREAMING_SNAKE_CASE__ = scores_sum_average * seq_lengths SCREAMING_SNAKE_CASE__ = is_stopped[next_tokens_source] SCREAMING_SNAKE_CASE__ = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) SCREAMING_SNAKE_CASE__ = torch.cat((generated, next_token_embed) , dim=1 ) SCREAMING_SNAKE_CASE__ = is_stopped + next_tokens.eq(__A ).squeeze() if is_stopped.all(): break SCREAMING_SNAKE_CASE__ = scores / seq_lengths SCREAMING_SNAKE_CASE__ = scores.argsort(descending=__A ) # tokens tensors are already padded to max_seq_length SCREAMING_SNAKE_CASE__ = [tokens[i] for i in order] SCREAMING_SNAKE_CASE__ = torch.stack(__A , dim=0 ) SCREAMING_SNAKE_CASE__ = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
702
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCamelCase__ ) EnvironmentCommand.register_subcommand(UpperCamelCase__ ) TestCommand.register_subcommand(UpperCamelCase__ ) RunBeamCommand.register_subcommand(UpperCamelCase__ ) DummyDataCommand.register_subcommand(UpperCamelCase__ ) # Parse args SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_known_args() if not hasattr(UpperCamelCase__ , """func""" ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE__ = parse_unknown_args(UpperCamelCase__ ) # Run SCREAMING_SNAKE_CASE__ = args.func(UpperCamelCase__ , **UpperCamelCase__ ) service.run() if __name__ == "__main__": main()
59
0
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 class UpperCamelCase_ ( nn.Module ): def __init__( self :int , __A :str=3 , __A :Optional[Any]=3 , __A :str=("DownEncoderBlock2D",) , __A :Tuple=(64,) , __A :List[Any]=2 , __A :List[str]=32 , __A :str="silu" , __A :Optional[int]=True , ) -> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = layers_per_block SCREAMING_SNAKE_CASE__ = torch.nn.Convad( __A , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = nn.ModuleList([] ) # down SCREAMING_SNAKE_CASE__ = block_out_channels[0] for i, down_block_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = output_channel SCREAMING_SNAKE_CASE__ = block_out_channels[i] SCREAMING_SNAKE_CASE__ = i == len(__A ) - 1 SCREAMING_SNAKE_CASE__ = get_down_block( __A , num_layers=self.layers_per_block , in_channels=__A , out_channels=__A , add_downsample=not is_final_block , resnet_eps=1E-6 , downsample_padding=0 , resnet_act_fn=__A , resnet_groups=__A , attention_head_dim=__A , temb_channels=__A , ) self.down_blocks.append(__A ) # mid SCREAMING_SNAKE_CASE__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=__A , output_scale_factor=1 , resnet_time_scale_shift="""default""" , attention_head_dim=block_out_channels[-1] , resnet_groups=__A , temb_channels=__A , ) # out SCREAMING_SNAKE_CASE__ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__A , eps=1E-6 ) SCREAMING_SNAKE_CASE__ = nn.SiLU() SCREAMING_SNAKE_CASE__ = 2 * out_channels if double_z else out_channels SCREAMING_SNAKE_CASE__ = nn.Convad(block_out_channels[-1] , __A , 3 , padding=1 ) SCREAMING_SNAKE_CASE__ = False def _snake_case ( self :str , __A :int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = x SCREAMING_SNAKE_CASE__ = self.conv_in(__A ) if self.training and self.gradient_checkpointing: def create_custom_forward(__A :str ): def custom_forward(*__A :str ): return module(*__A ) return custom_forward # down if is_torch_version(""">=""" , """1.11.0""" ): for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(__A ) , __A , use_reentrant=__A ) # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , use_reentrant=__A ) else: for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(__A ) , __A ) # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __A ) else: # down for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = down_block(__A ) # middle SCREAMING_SNAKE_CASE__ = self.mid_block(__A ) # post-process SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A ) SCREAMING_SNAKE_CASE__ = self.conv_act(__A ) SCREAMING_SNAKE_CASE__ = self.conv_out(__A ) return sample class UpperCamelCase_ ( nn.Module ): def __init__( self :Dict , __A :Optional[Any]=3 , __A :Tuple=3 , __A :Optional[int]=("UpDecoderBlock2D",) , __A :int=(64,) , __A :int=2 , __A :Dict=32 , __A :Dict="silu" , __A :str="group" , ) -> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = layers_per_block SCREAMING_SNAKE_CASE__ = nn.Convad( __A , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = nn.ModuleList([] ) SCREAMING_SNAKE_CASE__ = in_channels if norm_type == """spatial""" else None # mid SCREAMING_SNAKE_CASE__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=__A , output_scale_factor=1 , resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__A , temb_channels=__A , ) # up SCREAMING_SNAKE_CASE__ = list(reversed(__A ) ) SCREAMING_SNAKE_CASE__ = reversed_block_out_channels[0] for i, up_block_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = output_channel SCREAMING_SNAKE_CASE__ = reversed_block_out_channels[i] SCREAMING_SNAKE_CASE__ = i == len(__A ) - 1 SCREAMING_SNAKE_CASE__ = get_up_block( __A , num_layers=self.layers_per_block + 1 , in_channels=__A , out_channels=__A , prev_output_channel=__A , add_upsample=not is_final_block , resnet_eps=1E-6 , resnet_act_fn=__A , resnet_groups=__A , attention_head_dim=__A , temb_channels=__A , resnet_time_scale_shift=__A , ) self.up_blocks.append(__A ) SCREAMING_SNAKE_CASE__ = output_channel # out if norm_type == "spatial": SCREAMING_SNAKE_CASE__ = SpatialNorm(block_out_channels[0] , __A ) else: SCREAMING_SNAKE_CASE__ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__A , eps=1E-6 ) SCREAMING_SNAKE_CASE__ = nn.SiLU() SCREAMING_SNAKE_CASE__ = nn.Convad(block_out_channels[0] , __A , 3 , padding=1 ) SCREAMING_SNAKE_CASE__ = False def _snake_case ( self :List[str] , __A :Any , __A :Dict=None ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = z SCREAMING_SNAKE_CASE__ = self.conv_in(__A ) SCREAMING_SNAKE_CASE__ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__A :str ): def custom_forward(*__A :Dict ): return module(*__A ) return custom_forward if is_torch_version(""">=""" , """1.11.0""" ): # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , __A , use_reentrant=__A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(__A ) , __A , __A , use_reentrant=__A ) else: # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , __A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(__A ) , __A , __A ) else: # middle SCREAMING_SNAKE_CASE__ = self.mid_block(__A , __A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = up_block(__A , __A ) # post-process if latent_embeds is None: SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A ) else: SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A , __A ) SCREAMING_SNAKE_CASE__ = self.conv_act(__A ) SCREAMING_SNAKE_CASE__ = self.conv_out(__A ) return sample class UpperCamelCase_ ( nn.Module ): def __init__( self :List[str] , __A :Optional[Any] , __A :Tuple , __A :Optional[int] , __A :int=None , __A :Optional[Any]="random" , __A :int=False , __A :Any=True ) -> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = n_e SCREAMING_SNAKE_CASE__ = vq_embed_dim SCREAMING_SNAKE_CASE__ = beta SCREAMING_SNAKE_CASE__ = legacy SCREAMING_SNAKE_CASE__ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) SCREAMING_SNAKE_CASE__ = remap if self.remap is not None: self.register_buffer("""used""" , torch.tensor(np.load(self.remap ) ) ) SCREAMING_SNAKE_CASE__ = self.used.shape[0] SCREAMING_SNAKE_CASE__ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": SCREAMING_SNAKE_CASE__ = self.re_embed SCREAMING_SNAKE_CASE__ = self.re_embed + 1 print( f'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' f'''Using {self.unknown_index} for unknown indices.''' ) else: SCREAMING_SNAKE_CASE__ = n_e SCREAMING_SNAKE_CASE__ = sane_index_shape def _snake_case ( self :str , __A :List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = inds.shape assert len(__A ) > 1 SCREAMING_SNAKE_CASE__ = inds.reshape(ishape[0] , -1 ) SCREAMING_SNAKE_CASE__ = self.used.to(__A ) SCREAMING_SNAKE_CASE__ = (inds[:, :, None] == used[None, None, ...]).long() SCREAMING_SNAKE_CASE__ = match.argmax(-1 ) SCREAMING_SNAKE_CASE__ = match.sum(2 ) < 1 if self.unknown_index == "random": SCREAMING_SNAKE_CASE__ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: SCREAMING_SNAKE_CASE__ = self.unknown_index return new.reshape(__A ) def _snake_case ( self :Dict , __A :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = inds.shape assert len(__A ) > 1 SCREAMING_SNAKE_CASE__ = inds.reshape(ishape[0] , -1 ) SCREAMING_SNAKE_CASE__ = self.used.to(__A ) if self.re_embed > self.used.shape[0]: # extra token SCREAMING_SNAKE_CASE__ = 0 # simply set to zero SCREAMING_SNAKE_CASE__ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __A ) return back.reshape(__A ) def _snake_case ( self :Tuple , __A :Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = z.permute(0 , 2 , 3 , 1 ).contiguous() SCREAMING_SNAKE_CASE__ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z SCREAMING_SNAKE_CASE__ = torch.argmin(torch.cdist(__A , self.embedding.weight ) , dim=1 ) SCREAMING_SNAKE_CASE__ = self.embedding(__A ).view(z.shape ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # compute loss for embedding if not self.legacy: SCREAMING_SNAKE_CASE__ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: SCREAMING_SNAKE_CASE__ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients SCREAMING_SNAKE_CASE__ = z + (z_q - z).detach() # reshape back to match original input shape SCREAMING_SNAKE_CASE__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis SCREAMING_SNAKE_CASE__ = self.remap_to_used(__A ) SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _snake_case ( self :List[Any] , __A :Tuple , __A :List[str] ) -> List[Any]: """simple docstring""" if self.remap is not None: SCREAMING_SNAKE_CASE__ = indices.reshape(shape[0] , -1 ) # add batch axis SCREAMING_SNAKE_CASE__ = self.unmap_to_all(__A ) SCREAMING_SNAKE_CASE__ = indices.reshape(-1 ) # flatten again # get quantized latent vectors SCREAMING_SNAKE_CASE__ = self.embedding(__A ) if shape is not None: SCREAMING_SNAKE_CASE__ = z_q.view(__A ) # reshape back to match original input shape SCREAMING_SNAKE_CASE__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , __A :List[Any] , __A :int=False ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = parameters SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = torch.chunk(__A , 2 , dim=1 ) SCREAMING_SNAKE_CASE__ = torch.clamp(self.logvar , -30.0 , 20.0 ) SCREAMING_SNAKE_CASE__ = deterministic SCREAMING_SNAKE_CASE__ = torch.exp(0.5 * self.logvar ) SCREAMING_SNAKE_CASE__ = torch.exp(self.logvar ) if self.deterministic: SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def _snake_case ( self :Any , __A :Optional[torch.Generator] = None ) -> torch.FloatTensor: """simple docstring""" SCREAMING_SNAKE_CASE__ = randn_tensor( self.mean.shape , generator=__A , device=self.parameters.device , dtype=self.parameters.dtype ) SCREAMING_SNAKE_CASE__ = self.mean + self.std * sample return x def _snake_case ( self :Union[str, Any] , __A :int=None ) -> int: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def _snake_case ( self :str , __A :Tuple , __A :int=[1, 2, 3] ) -> int: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) SCREAMING_SNAKE_CASE__ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__A ) def _snake_case ( self :Tuple ) -> Optional[int]: """simple docstring""" return self.mean
703
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , *__A :Tuple , **__A :Dict ) -> None: """simple docstring""" warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __A , ) super().__init__(*__A , **__A )
59
0
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :int , __A :str ) -> Optional[Any]: """simple docstring""" with open(__A , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ = re.compile(r"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)""" ) SCREAMING_SNAKE_CASE__ = input_file.read() SCREAMING_SNAKE_CASE__ = regexp.search(__A ) return match def _snake_case ( self :Optional[int] , __A :str ) -> Dict: """simple docstring""" with open(__A , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ = re.compile(r"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()""" , re.DOTALL ) SCREAMING_SNAKE_CASE__ = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` SCREAMING_SNAKE_CASE__ = regexp.finditer(__A ) SCREAMING_SNAKE_CASE__ = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(__A ) ): raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}''' ) def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_print_statements(str(__A ) ): raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.''' )
704
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
59
0
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = AutoencoderKL lowerCamelCase_ = "sample" lowerCamelCase_ = 1e-2 @property def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = (32, 32) SCREAMING_SNAKE_CASE__ = floats_tensor((batch_size, num_channels) + sizes ).to(__A ) return {"sample": image} @property def _snake_case ( self :Any ) -> List[Any]: """simple docstring""" return (3, 32, 32) @property def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" return (3, 32, 32) def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } SCREAMING_SNAKE_CASE__ = self.dummy_input return init_dict, inputs_dict def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" pass def _snake_case ( self :Optional[Any] ) -> List[Any]: """simple docstring""" pass @unittest.skipIf(torch_device == """mps""" , """Gradient checkpointing skipped on MPS""" ) def _snake_case ( self :Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.prepare_init_args_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = self.model_class(**__A ) model.to(__A ) assert not model.is_gradient_checkpointing and model.training SCREAMING_SNAKE_CASE__ = model(**__A ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() SCREAMING_SNAKE_CASE__ = torch.randn_like(__A ) SCREAMING_SNAKE_CASE__ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing SCREAMING_SNAKE_CASE__ = self.model_class(**__A ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__A ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training SCREAMING_SNAKE_CASE__ = model_a(**__A ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() SCREAMING_SNAKE_CASE__ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) SCREAMING_SNAKE_CASE__ = dict(model.named_parameters() ) SCREAMING_SNAKE_CASE__ = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def _snake_case ( self :Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = AutoencoderKL.from_pretrained("""fusing/autoencoder-kl-dummy""" , output_loading_info=__A ) self.assertIsNotNone(__A ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(__A ) SCREAMING_SNAKE_CASE__ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoencoderKL.from_pretrained("""fusing/autoencoder-kl-dummy""" ) SCREAMING_SNAKE_CASE__ = model.to(__A ) model.eval() if torch_device == "mps": SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) else: SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) SCREAMING_SNAKE_CASE__ = image.to(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A , sample_posterior=__A , generator=__A ).sample SCREAMING_SNAKE_CASE__ = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": SCREAMING_SNAKE_CASE__ = torch.tensor( [ -4.0_078E-01, -3.8_323E-04, -1.2_681E-01, -1.1_462E-01, 2.0_095E-01, 1.0_893E-01, -8.8_247E-02, -3.0_361E-01, -9.8_644E-03, ] ) elif torch_device == "cpu": SCREAMING_SNAKE_CASE__ = torch.tensor( [-0.1_3_5_2, 0.0_8_7_8, 0.0_4_1_9, -0.0_8_1_8, -0.1_0_6_9, 0.0_6_8_8, -0.1_4_5_8, -0.4_4_4_6, -0.0_0_2_6] ) else: SCREAMING_SNAKE_CASE__ = torch.tensor( [-0.2_4_2_1, 0.4_6_4_2, 0.2_5_0_7, -0.0_4_3_8, 0.0_6_8_2, 0.3_1_6_0, -0.2_0_1_8, -0.0_7_2_7, 0.2_4_8_5] ) self.assertTrue(torch_all_close(__A , __A , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Optional[int] , __A :int , __A :Optional[Any] ) -> Tuple: """simple docstring""" return f'''gaussian_noise_s={seed}_shape={'_'.join([str(__A ) for s in shape] )}.npy''' def _snake_case ( self :List[str] ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :int , __A :Any=0 , __A :List[str]=(4, 3, 512, 512) , __A :int=False ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch.floataa if fpaa else torch.floataa SCREAMING_SNAKE_CASE__ = torch.from_numpy(load_hf_numpy(self.get_file_format(__A , __A ) ) ).to(__A ).to(__A ) return image def _snake_case ( self :Tuple , __A :int="CompVis/stable-diffusion-v1-4" , __A :Any=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """fp16""" if fpaa else None SCREAMING_SNAKE_CASE__ = torch.floataa if fpaa else torch.floataa SCREAMING_SNAKE_CASE__ = AutoencoderKL.from_pretrained( __A , subfolder="""vae""" , torch_dtype=__A , revision=__A , ) model.to(__A ).eval() return model def _snake_case ( self :Optional[int] , __A :Optional[Any]=0 ) -> Optional[int]: """simple docstring""" if torch_device == "mps": return torch.manual_seed(__A ) return torch.Generator(device=__A ).manual_seed(__A ) @parameterized.expand( [ # fmt: off [33, [-0.1_6_0_3, 0.9_8_7_8, -0.0_4_9_5, -0.0_7_9_0, -0.2_7_0_9, 0.8_3_7_5, -0.2_0_6_0, -0.0_8_2_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]], [47, [-0.2_3_7_6, 0.1_1_6_8, 0.1_3_3_2, -0.4_8_4_0, -0.2_5_0_8, -0.0_7_9_1, -0.0_4_9_3, -0.4_0_8_9], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]], # fmt: on ] ) def _snake_case ( self :List[Any] , __A :int , __A :str , __A :Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model() SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A ) SCREAMING_SNAKE_CASE__ = self.get_generator(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A , generator=__A , sample_posterior=__A ).sample assert sample.shape == image.shape SCREAMING_SNAKE_CASE__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(expected_slice_mps if torch_device == """mps""" else expected_slice ) assert torch_all_close(__A , __A , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0_5_1_3, 0.0_2_8_9, 1.3_7_9_9, 0.2_1_6_6, -0.2_5_7_3, -0.0_8_7_1, 0.5_1_0_3, -0.0_9_9_9]], [47, [-0.4_1_2_8, -0.1_3_2_0, -0.3_7_0_4, 0.1_9_6_5, -0.4_1_1_6, -0.2_3_3_2, -0.3_3_4_0, 0.2_2_4_7]], # fmt: on ] ) @require_torch_gpu def _snake_case ( self :str , __A :Optional[Any] , __A :Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model(fpaa=__A ) SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A , fpaa=__A ) SCREAMING_SNAKE_CASE__ = self.get_generator(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A , generator=__A , sample_posterior=__A ).sample assert sample.shape == image.shape SCREAMING_SNAKE_CASE__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(__A ) assert torch_all_close(__A , __A , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1_6_0_9, 0.9_8_6_6, -0.0_4_8_7, -0.0_7_7_7, -0.2_7_1_6, 0.8_3_6_8, -0.2_0_5_5, -0.0_8_1_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]], [47, [-0.2_3_7_7, 0.1_1_4_7, 0.1_3_3_3, -0.4_8_4_1, -0.2_5_0_6, -0.0_8_0_5, -0.0_4_9_1, -0.4_0_8_5], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]], # fmt: on ] ) def _snake_case ( self :Any , __A :Tuple , __A :List[str] , __A :str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model() SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A ).sample assert sample.shape == image.shape SCREAMING_SNAKE_CASE__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(expected_slice_mps if torch_device == """mps""" else expected_slice ) assert torch_all_close(__A , __A , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2_0_5_1, -0.1_8_0_3, -0.2_3_1_1, -0.2_1_1_4, -0.3_2_9_2, -0.3_5_7_4, -0.2_9_5_3, -0.3_3_2_3]], [37, [-0.2_6_3_2, -0.2_6_2_5, -0.2_1_9_9, -0.2_7_4_1, -0.4_5_3_9, -0.4_9_9_0, -0.3_7_2_0, -0.4_9_2_5]], # fmt: on ] ) @require_torch_gpu def _snake_case ( self :Dict , __A :Any , __A :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model() SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A , shape=(3, 4, 64, 64) ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample assert list(sample.shape ) == [3, 3, 512, 512] SCREAMING_SNAKE_CASE__ = sample[-1, -2:, :2, -2:].flatten().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(__A ) assert torch_all_close(__A , __A , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0_3_6_9, 0.0_2_0_7, -0.0_7_7_6, -0.0_6_8_2, -0.1_7_4_7, -0.1_9_3_0, -0.1_4_6_5, -0.2_0_3_9]], [16, [-0.1_6_2_8, -0.2_1_3_4, -0.2_7_4_7, -0.2_6_4_2, -0.3_7_7_4, -0.4_4_0_4, -0.3_6_8_7, -0.4_2_7_7]], # fmt: on ] ) @require_torch_gpu def _snake_case ( self :int , __A :Any , __A :Optional[int] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model(fpaa=__A ) SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A , shape=(3, 4, 64, 64) , fpaa=__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample assert list(sample.shape ) == [3, 3, 512, 512] SCREAMING_SNAKE_CASE__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(__A ) assert torch_all_close(__A , __A , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="""xformers is not required when using PyTorch 2.0.""" ) def _snake_case ( self :Optional[int] , __A :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model(fpaa=__A ) SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A , shape=(3, 4, 64, 64) , fpaa=__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__A , __A , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="""xformers is not required when using PyTorch 2.0.""" ) def _snake_case ( self :str , __A :int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model() SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A , shape=(3, 4, 64, 64) ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__A , __A , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3_0_0_1, 0.0_9_1_8, -2.6_9_8_4, -3.9_7_2_0, -3.2_0_9_9, -5.0_3_5_3, 1.7_3_3_8, -0.2_0_6_5, 3.4_2_6_7]], [47, [-1.5_0_3_0, -4.3_8_7_1, -6.0_3_5_5, -9.1_1_5_7, -1.6_6_6_1, -2.7_8_5_3, 2.1_6_0_7, -5.0_8_2_3, 2.5_6_3_3]], # fmt: on ] ) def _snake_case ( self :Tuple , __A :Union[str, Any] , __A :Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model() SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A ) SCREAMING_SNAKE_CASE__ = self.get_generator(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.encode(__A ).latent_dist SCREAMING_SNAKE_CASE__ = dist.sample(generator=__A ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] SCREAMING_SNAKE_CASE__ = sample[0, -1, -3:, -3:].flatten().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(__A ) SCREAMING_SNAKE_CASE__ = 3E-3 if torch_device != """mps""" else 1E-2 assert torch_all_close(__A , __A , atol=__A )
705
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__ )}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
0
import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors from ..processors.utils import InputFeatures _lowerCamelCase = logging.get_logger(__name__) @dataclass class UpperCamelCase_ : lowerCamelCase_ = field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys() )} ) lowerCamelCase_ = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) lowerCamelCase_ = field( default=1_28 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _snake_case ( self :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.task_name.lower() class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "train" lowerCamelCase_ = "dev" lowerCamelCase_ = "test" class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :GlueDataTrainingArguments , __A :PreTrainedTokenizerBase , __A :Optional[int] = None , __A :Union[str, Split] = Split.train , __A :Optional[str] = None , ) -> List[Any]: """simple docstring""" warnings.warn( """This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """ """library. You can have a look at this example script for pointers: """ """https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py""" , __A , ) SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = glue_processors[args.task_name]() SCREAMING_SNAKE_CASE__ = glue_output_modes[args.task_name] if isinstance(__A , __A ): try: SCREAMING_SNAKE_CASE__ = Split[mode] except KeyError: raise KeyError("""mode is not a valid split name""" ) # Load data features from cache or dataset file SCREAMING_SNAKE_CASE__ = os.path.join( cache_dir if cache_dir is not None else args.data_dir , f'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}''' , ) SCREAMING_SNAKE_CASE__ = self.processor.get_labels() if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in ( "RobertaTokenizer", "RobertaTokenizerFast", "XLMRobertaTokenizer", "BartTokenizer", "BartTokenizerFast", ): # HACK(label indices are swapped in RoBERTa pretrained model) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = label_list[2], label_list[1] SCREAMING_SNAKE_CASE__ = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. SCREAMING_SNAKE_CASE__ = cached_features_file + """.lock""" with FileLock(__A ): if os.path.exists(__A ) and not args.overwrite_cache: SCREAMING_SNAKE_CASE__ = time.time() SCREAMING_SNAKE_CASE__ = torch.load(__A ) logger.info( f'''Loading features from cached file {cached_features_file} [took %.3f s]''' , time.time() - start ) else: logger.info(f'''Creating features from dataset file at {args.data_dir}''' ) if mode == Split.dev: SCREAMING_SNAKE_CASE__ = self.processor.get_dev_examples(args.data_dir ) elif mode == Split.test: SCREAMING_SNAKE_CASE__ = self.processor.get_test_examples(args.data_dir ) else: SCREAMING_SNAKE_CASE__ = self.processor.get_train_examples(args.data_dir ) if limit_length is not None: SCREAMING_SNAKE_CASE__ = examples[:limit_length] SCREAMING_SNAKE_CASE__ = glue_convert_examples_to_features( __A , __A , max_length=args.max_seq_length , label_list=__A , output_mode=self.output_mode , ) SCREAMING_SNAKE_CASE__ = time.time() torch.save(self.features , __A ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]''' ) def __len__( self :List[Any] ) -> str: """simple docstring""" return len(self.features ) def __getitem__( self :Union[str, Any] , __A :Union[str, Any] ) -> InputFeatures: """simple docstring""" return self.features[i] def _snake_case ( self :int ) -> Union[str, Any]: """simple docstring""" return self.label_list
706
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
59
0
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = generate_pascal_triangle(UpperCamelCase__ ) for row_idx in range(UpperCamelCase__ ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=""" """ ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=""" """ ) else: print(triangle[row_idx][col_idx] , end="""""" ) print() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise TypeError("""The input value of 'num_rows' should be 'int'""" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( """The input value of 'num_rows' should be greater than or equal to 0""" ) SCREAMING_SNAKE_CASE__ = [] for current_row_idx in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = populate_current_row(UpperCamelCase__ , UpperCamelCase__ ) triangle.append(UpperCamelCase__ ) return triangle def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 1, 1 for current_col_idx in range(1 , UpperCamelCase__ ): calculate_current_element( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return current_row def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] , UpperCamelCase__: list[int] , UpperCamelCase__: int , UpperCamelCase__: int , ): SCREAMING_SNAKE_CASE__ = triangle[current_row_idx - 1][current_col_idx - 1] SCREAMING_SNAKE_CASE__ = triangle[current_row_idx - 1][current_col_idx] SCREAMING_SNAKE_CASE__ = above_to_left_elt + above_to_right_elt def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise TypeError("""The input value of 'num_rows' should be 'int'""" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( """The input value of 'num_rows' should be greater than or equal to 0""" ) SCREAMING_SNAKE_CASE__ = [[1]] for row_index in range(1 , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = [0] + result[-1] + [0] SCREAMING_SNAKE_CASE__ = row_index + 1 # Calculate the number of distinct elements in a row SCREAMING_SNAKE_CASE__ = sum(divmod(UpperCamelCase__ , 2 ) ) SCREAMING_SNAKE_CASE__ = [ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] SCREAMING_SNAKE_CASE__ = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() SCREAMING_SNAKE_CASE__ = row_first_half + row_second_half result.append(UpperCamelCase__ ) return result def SCREAMING_SNAKE_CASE__ ( ): from collections.abc import Callable from timeit import timeit def benchmark_a_function(UpperCamelCase__: Callable , UpperCamelCase__: int ) -> None: SCREAMING_SNAKE_CASE__ = f'''{func.__name__}({value})''' SCREAMING_SNAKE_CASE__ = timeit(f'''__main__.{call}''' , setup="""import __main__""" ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f'''{call:38} -- {timing:.4f} seconds''' ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(UpperCamelCase__ , UpperCamelCase__ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
707
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
59
0
'''simple docstring''' import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = CpmAntTokenizer lowerCamelCase_ = False def _snake_case ( self :Any ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = [ """<d>""", """</d>""", """<s>""", """</s>""", """</_>""", """<unk>""", """<pad>""", """</n>""", """我""", """是""", """C""", """P""", """M""", """A""", """n""", """t""", ] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) @tooslow def _snake_case ( self :Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = CpmAntTokenizer.from_pretrained("""openbmb/cpm-ant-10b""" ) SCREAMING_SNAKE_CASE__ = """今天天气真好!""" SCREAMING_SNAKE_CASE__ = ["""今天""", """天气""", """真""", """好""", """!"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = """今天天气真好!""" SCREAMING_SNAKE_CASE__ = [tokenizer.bos_token] + tokens SCREAMING_SNAKE_CASE__ = [6, 9802, 1_4962, 2082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) SCREAMING_SNAKE_CASE__ = tokenizer.decode(__A ) self.assertEqual(__A , __A )
708
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , default=512 , help="""Maximum sequence length. For training on TPUs, it helps to have a maximum""" """ sequence length that is a multiple of 8.""" , ) parser.add_argument( """--output_dir""" , default="""tf-tpu""" , type=UpperCamelCase__ , help="""Output directory where the TFRecord shards will be saved. If the""" """ path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord""" """ shards will be directly saved to a Google Cloud Storage bucket.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """input_ids""": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["""input_ids"""][i] ) ), """attention_mask""": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["""attention_mask"""][i] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , num_proc=4 , remove_columns=["""text"""] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) shard_count += 1 total_records += records_containing with open(f'''split-{args.split}-records-count.txt''' , """w""" ) as f: print(f'''Total {args.split} records: {total_records}''' , file=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
59
0
import numpy as np from transformers import Pipeline def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): SCREAMING_SNAKE_CASE__ = np.max(UpperCamelCase__ , axis=-1 , keepdims=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :List[Any] , **__A :Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = {} if "second_text" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""second_text"""] return preprocess_kwargs, {}, {} def _snake_case ( self :Union[str, Any] , __A :Any , __A :Optional[int]=None ) -> Optional[Any]: """simple docstring""" return self.tokenizer(__A , text_pair=__A , return_tensors=self.framework ) def _snake_case ( self :Any , __A :Optional[int] ) -> Any: """simple docstring""" return self.model(**__A ) def _snake_case ( self :int , __A :Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = model_outputs.logits[0].numpy() SCREAMING_SNAKE_CASE__ = softmax(__A ) SCREAMING_SNAKE_CASE__ = np.argmax(__A ) SCREAMING_SNAKE_CASE__ = self.model.config.idalabel[best_class] SCREAMING_SNAKE_CASE__ = probabilities[best_class].item() SCREAMING_SNAKE_CASE__ = logits.tolist() return {"label": label, "score": score, "logits": logits}
709
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [] for data in source_data: for i, el in enumerate(UpperCamelCase__ ): if len(UpperCamelCase__ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(UpperCamelCase__ ) ) return data_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = [] for dlist, weight in zip(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: SCREAMING_SNAKE_CASE__ = f'''Invalid weight of {weight:f} provided''' raise ValueError(UpperCamelCase__ ) score_lists.append(UpperCamelCase__ ) return score_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = get_data(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = calculate_each_score(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = generate_final_scores(UpperCamelCase__ ) # append scores to source data for i, ele in enumerate(UpperCamelCase__ ): source_data[i].append(UpperCamelCase__ ) return source_data
59
0
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 3 ): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise TypeError("""number of qubits must be a integer.""" ) if number_of_qubits <= 0: raise ValueError("""number of qubits must be > 0.""" ) if math.floor(UpperCamelCase__ ) != number_of_qubits: raise ValueError("""number of qubits must be exact integer.""" ) if number_of_qubits > 10: raise ValueError("""number of qubits too large to simulate(>10).""" ) SCREAMING_SNAKE_CASE__ = QuantumRegister(UpperCamelCase__ , """qr""" ) SCREAMING_SNAKE_CASE__ = ClassicalRegister(UpperCamelCase__ , """cr""" ) SCREAMING_SNAKE_CASE__ = QuantumCircuit(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = number_of_qubits for i in range(UpperCamelCase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(UpperCamelCase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , UpperCamelCase__ , UpperCamelCase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(UpperCamelCase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(UpperCamelCase__ , UpperCamelCase__ ) # simulate with 10000 shots SCREAMING_SNAKE_CASE__ = Aer.get_backend("""qasm_simulator""" ) SCREAMING_SNAKE_CASE__ = execute(UpperCamelCase__ , UpperCamelCase__ , shots=10_000 ) return job.result().get_counts(UpperCamelCase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
710
import warnings from functools import wraps from typing import Callable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Callable ): @wraps(UpperCamelCase__ ) def _inner_fn(*UpperCamelCase__: Dict , **UpperCamelCase__: Any ): warnings.warn( (f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , UpperCamelCase__ , ) return fn(*UpperCamelCase__ , **UpperCamelCase__ ) return _inner_fn
59
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
711
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RoCBertTokenizer lowerCamelCase_ = None lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = filter_non_english def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(__A , __A , ensure_ascii=__A ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(__A , __A , ensure_ascii=__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(__A , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__A ) , [5, 6, 2, 5, 7, 8] ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=__A , 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 _snake_case ( self :Any ) -> str: """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 _snake_case ( self :int ) -> str: """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 _snake_case ( self :List[str] ) -> List[str]: """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 _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def _snake_case ( self :int ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(__A , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE__ = ( [ ((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 _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你好""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你是谁""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( __A , __A , __A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(__A , add_special_tokens=__A ) self.assertEqual(__A , __A )
59
0
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0, 0 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 2 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 3 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 5 for _ in range(1 , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ugly_nums.append(UpperCamelCase__ ) if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F'''{ugly_numbers(200) = }''')
712
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = original_name.split(""".""" )[0] SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 2] ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 1] ) SCREAMING_SNAKE_CASE__ = orig_block_num - offset SCREAMING_SNAKE_CASE__ = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = OrderedDict() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): SCREAMING_SNAKE_CASE__ = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 SCREAMING_SNAKE_CASE__ = key[: key.find("""proj""" )] SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , f'''patch_embeddings.{total_embed_found}.''' ) SCREAMING_SNAKE_CASE__ = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: SCREAMING_SNAKE_CASE__ = """poolformer.encoder.""" + key if "mlp.fc1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm1""" , """before_norm""" ) if "norm2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: SCREAMING_SNAKE_CASE__ = key.replace("""head""" , """classifier""" ) SCREAMING_SNAKE_CASE__ = value return new_state_dict def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = PoolFormerConfig() # set attributes based on model_name SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = model_name[-3:] SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = (1, 1_000) # set config attributes SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if size == "s12": SCREAMING_SNAKE_CASE__ = [2, 2, 6, 2] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s24": SCREAMING_SNAKE_CASE__ = [4, 4, 12, 4] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "m36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 elif size == "m48": SCREAMING_SNAKE_CASE__ = [8, 8, 24, 8] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) # Prepare image SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location=torch.device("""cpu""" ) ) # rename keys SCREAMING_SNAKE_CASE__ = rename_keys(UpperCamelCase__ ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ = PoolFormerForImageClassification(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Define image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.logits # define expected logit slices for different models if size == "s12": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": SCREAMING_SNAKE_CASE__ = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": SCREAMING_SNAKE_CASE__ = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": SCREAMING_SNAKE_CASE__ = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , UpperCamelCase__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
0
'''simple docstring''' import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["input_features", "is_longer"] def __init__( self :str , __A :Tuple=64 , __A :List[str]=4_8000 , __A :Optional[Any]=480 , __A :Optional[int]=10 , __A :Dict=1024 , __A :Union[str, Any]=0.0 , __A :Optional[int]=False , __A :float = 0 , __A :float = 1_4000 , __A :int = None , __A :str = "fusion" , __A :str = "repeatpad" , **__A :Any , ) -> Optional[int]: """simple docstring""" super().__init__( feature_size=__A , sampling_rate=__A , padding_value=__A , return_attention_mask=__A , **__A , ) SCREAMING_SNAKE_CASE__ = top_db SCREAMING_SNAKE_CASE__ = truncation SCREAMING_SNAKE_CASE__ = padding SCREAMING_SNAKE_CASE__ = fft_window_size SCREAMING_SNAKE_CASE__ = (fft_window_size >> 1) + 1 SCREAMING_SNAKE_CASE__ = hop_length SCREAMING_SNAKE_CASE__ = max_length_s SCREAMING_SNAKE_CASE__ = max_length_s * sampling_rate SCREAMING_SNAKE_CASE__ = sampling_rate SCREAMING_SNAKE_CASE__ = frequency_min SCREAMING_SNAKE_CASE__ = frequency_max SCREAMING_SNAKE_CASE__ = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=__A , min_frequency=__A , max_frequency=__A , sampling_rate=__A , norm=__A , mel_scale="""htk""" , ) SCREAMING_SNAKE_CASE__ = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=__A , min_frequency=__A , max_frequency=__A , sampling_rate=__A , norm="""slaney""" , mel_scale="""slaney""" , ) def _snake_case ( self :List[Any] ) -> Dict[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def _snake_case ( self :Any , __A :np.array , __A :Optional[np.array] = None ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ = spectrogram( __A , window_function(self.fft_window_size , """hann""" ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=__A , log_mel="""dB""" , ) return log_mel_spectrogram.T def _snake_case ( self :Optional[Any] , __A :Any , __A :Optional[int] , __A :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE__ = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE__ = [0] # randomly choose index for each part SCREAMING_SNAKE_CASE__ = np.random.choice(ranges[0] ) SCREAMING_SNAKE_CASE__ = np.random.choice(ranges[1] ) SCREAMING_SNAKE_CASE__ = np.random.choice(ranges[2] ) SCREAMING_SNAKE_CASE__ = mel[idx_front : idx_front + chunk_frames, :] SCREAMING_SNAKE_CASE__ = mel[idx_middle : idx_middle + chunk_frames, :] SCREAMING_SNAKE_CASE__ = mel[idx_back : idx_back + chunk_frames, :] SCREAMING_SNAKE_CASE__ = torch.tensor(mel[None, None, :] ) SCREAMING_SNAKE_CASE__ = torch.nn.functional.interpolate( __A , size=[chunk_frames, 64] , mode="""bilinear""" , align_corners=__A ) SCREAMING_SNAKE_CASE__ = mel_shrink[0][0].numpy() SCREAMING_SNAKE_CASE__ = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def _snake_case ( self :Tuple , __A :np.array , __A :Tuple , __A :Tuple , __A :Tuple ) -> np.array: """simple docstring""" if waveform.shape[0] > max_length: if truncation == "rand_trunc": SCREAMING_SNAKE_CASE__ = True # random crop to max_length (for compatibility) -> this should be handled by self.pad SCREAMING_SNAKE_CASE__ = len(__A ) - max_length SCREAMING_SNAKE_CASE__ = np.random.randint(0 , overflow + 1 ) SCREAMING_SNAKE_CASE__ = waveform[idx : idx + max_length] SCREAMING_SNAKE_CASE__ = self._np_extract_fbank_features(__A , self.mel_filters_slaney )[None, :] elif truncation == "fusion": SCREAMING_SNAKE_CASE__ = self._np_extract_fbank_features(__A , self.mel_filters ) SCREAMING_SNAKE_CASE__ = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed SCREAMING_SNAKE_CASE__ = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. SCREAMING_SNAKE_CASE__ = np.stack([mel, mel, mel, mel] , axis=0 ) SCREAMING_SNAKE_CASE__ = False else: SCREAMING_SNAKE_CASE__ = self._random_mel_fusion(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = True else: raise NotImplementedError(f'''data_truncating {truncation} not implemented''' ) else: SCREAMING_SNAKE_CASE__ = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": SCREAMING_SNAKE_CASE__ = int(max_length / len(__A ) ) SCREAMING_SNAKE_CASE__ = np.stack(np.tile(__A , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": SCREAMING_SNAKE_CASE__ = int(max_length / len(__A ) ) SCREAMING_SNAKE_CASE__ = np.stack(np.tile(__A , __A ) ) SCREAMING_SNAKE_CASE__ = np.pad(__A , (0, max_length - waveform.shape[0]) , mode="""constant""" , constant_values=0 ) if truncation == "fusion": SCREAMING_SNAKE_CASE__ = self._np_extract_fbank_features(__A , self.mel_filters ) SCREAMING_SNAKE_CASE__ = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: SCREAMING_SNAKE_CASE__ = self._np_extract_fbank_features(__A , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self :Any , __A :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , __A :str = None , __A :Optional[str] = None , __A :Optional[int] = None , __A :Optional[int] = None , __A :Optional[Union[str, TensorType]] = None , **__A :List[Any] , ) -> BatchFeature: """simple docstring""" SCREAMING_SNAKE_CASE__ = truncation if truncation is not None else self.truncation SCREAMING_SNAKE_CASE__ = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a''' f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input''' f''' was sampled with {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) SCREAMING_SNAKE_CASE__ = isinstance(__A , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) SCREAMING_SNAKE_CASE__ = is_batched_numpy or ( isinstance(__A , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE__ = [np.asarray(__A , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(__A , np.ndarray ): SCREAMING_SNAKE_CASE__ = np.asarray(__A , dtype=np.floataa ) elif isinstance(__A , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE__ = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE__ = [np.asarray(__A )] # convert to mel spectrogram, truncate and pad if needed. SCREAMING_SNAKE_CASE__ = [ self._get_input_mel(__A , max_length if max_length else self.nb_max_samples , __A , __A ) for waveform in raw_speech ] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] for mel, longer in padded_inputs: input_mel.append(__A ) is_longer.append(__A ) if truncation == "fusion" and sum(__A ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer SCREAMING_SNAKE_CASE__ = np.random.randint(0 , len(__A ) ) SCREAMING_SNAKE_CASE__ = True if isinstance(input_mel[0] , __A ): SCREAMING_SNAKE_CASE__ = [np.asarray(__A , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool SCREAMING_SNAKE_CASE__ = [[longer] for longer in is_longer] SCREAMING_SNAKE_CASE__ = {"""input_features""": input_mel, """is_longer""": is_longer} SCREAMING_SNAKE_CASE__ = BatchFeature(__A ) if return_tensors is not None: SCREAMING_SNAKE_CASE__ = input_features.convert_to_tensors(__A ) return input_features
713
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_text_model" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :Union[str, Any] , __A :Any=5_0244 , __A :Optional[Any]=768 , __A :Tuple=64 , __A :List[str]=2048 , __A :int=12 , __A :str=12 , __A :Any=32 , __A :Tuple=128 , __A :int=0.1 , __A :str=1E-6 , __A :Optional[Any]=1.0 , __A :Union[str, Any]="gelu_new" , __A :Any=0 , __A :List[str]=False , __A :Optional[Any]=0 , __A :int=1 , __A :Optional[int]=False , __A :Optional[Any]=True , **__A :List[Any] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = d_kv SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = num_layers SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = decoder_start_token_id # for backwards compatibility SCREAMING_SNAKE_CASE__ = dense_act_fn super().__init__( pad_token_id=__A , eos_token_id=__A , decoder_start_token_id=__A , tie_word_embeddings=__A , is_decoder=__A , **__A , ) @classmethod def _snake_case ( cls :Optional[int] , __A :Union[str, os.PathLike] , **__A :Optional[int] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = 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(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_vision_model" def __init__( self :Optional[int] , __A :int=768 , __A :Optional[Any]=768 , __A :Union[str, Any]=2048 , __A :int=64 , __A :Union[str, Any]=12 , __A :str=12 , __A :Any="gelu_new" , __A :List[Any]=1E-6 , __A :Dict=0.0 , __A :int=0.0 , __A :int=1E-10 , __A :Dict=1.0 , __A :int=4096 , __A :int=32 , __A :int=128 , **__A :Tuple , ) -> str: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = patch_embed_hidden_size SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = dense_act_fn SCREAMING_SNAKE_CASE__ = seq_len SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = d_kv @classmethod def _snake_case ( cls :str , __A :Union[str, os.PathLike] , **__A :str ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = 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(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct" lowerCamelCase_ = True def __init__( self :str , __A :Optional[Any]=None , __A :List[str]=None , __A :Optional[Any]=1.0 , __A :Optional[Any]=0.0_2 , __A :Any=False , __A :Tuple=False , __A :Any=True , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__(tie_word_embeddings=__A , is_encoder_decoder=__A , **__A ) if text_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE__ = PixaStructTextConfig(**__A ) SCREAMING_SNAKE_CASE__ = PixaStructVisionConfig(**__A ) SCREAMING_SNAKE_CASE__ = self.text_config.decoder_start_token_id SCREAMING_SNAKE_CASE__ = self.text_config.pad_token_id SCREAMING_SNAKE_CASE__ = self.text_config.eos_token_id SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = is_vqa @classmethod def _snake_case ( cls :Union[str, Any] , __A :PixaStructTextConfig , __A :PixaStructVisionConfig , **__A :Optional[int] ) -> Optional[Any]: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__A ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
0
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): if upper_limit < 0: raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" ) SCREAMING_SNAKE_CASE__ = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 SCREAMING_SNAKE_CASE__ = 1 if upper_limit > 0: SCREAMING_SNAKE_CASE__ = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(UpperCamelCase__ ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('\n********* Catalan Numbers Using Dynamic Programming ************\n') print('\n*** Enter -1 at any time to quit ***') print('\nEnter the upper limit (≥ 0) for the Catalan number sequence: ', end='') try: while True: _lowerCamelCase = int(input().strip()) if N < 0: print('\n********* Goodbye!! ************') break else: print(F'''The Catalan numbers from 0 through {N} are:''') print(catalan_numbers(N)) print('Try another upper limit for the sequence: ', end='') except (NameError, ValueError): print('\n********* Invalid input, goodbye! ************\n') import doctest doctest.testmod()
714
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[int] ) -> str: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__A , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = Accelerator() _lowerCamelCase = (accelerator.state.process_index + 2, 10) _lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device) _lowerCamelCase = '' _lowerCamelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." _lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." _lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
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 UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__A , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(__A , """neck_hidden_sizes""" ) ) self.parent.assertTrue(hasattr(__A , """num_attention_heads""" ) ) class UpperCamelCase_ : def __init__( self :List[str] , __A :int , __A :List[Any]=13 , __A :Tuple=32 , __A :Optional[Any]=2 , __A :Optional[Any]=3 , __A :Tuple=640 , __A :Optional[int]=4 , __A :Optional[int]="silu" , __A :Any=3 , __A :List[str]=32 , __A :List[Any]=0.1 , __A :Any=0.1 , __A :Union[str, Any]=0.1 , __A :str=0.0_2 , __A :List[Any]=True , __A :Tuple=True , __A :Optional[int]=10 , __A :Dict=None , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = last_hidden_size SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = conv_kernel_size SCREAMING_SNAKE_CASE__ = output_stride SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = classifier_dropout_prob SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = scope def _snake_case ( self :str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ = self.get_config() return config, pixel_values, labels, pixel_labels def _snake_case ( self :Tuple ) -> int: """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 _snake_case ( self :int , __A :int , __A :List[Any] , __A :Optional[Any] , __A :Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = MobileViTModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _snake_case ( self :int , __A :str , __A :str , __A :List[str] , __A :Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = MobileViTForImageClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self :Any , __A :Any , __A :Union[str, Any] , __A :List[Any] , __A :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = MobileViTForSemanticSegmentation(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) SCREAMING_SNAKE_CASE__ = model(__A , labels=__A ) 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 _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) lowerCamelCase_ = ( { "feature-extraction": MobileViTModel, "image-classification": MobileViTForImageClassification, "image-segmentation": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = MobileViTModelTester(self ) SCREAMING_SNAKE_CASE__ = MobileViTConfigTester(self , config_class=__A , has_text_modality=__A ) def _snake_case ( self :List[str] ) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViT does not use inputs_embeds""" ) def _snake_case ( self :Tuple ) -> str: """simple docstring""" pass @unittest.skip(reason="""MobileViT does not support input and output embeddings""" ) def _snake_case ( self :Dict ) -> Dict: """simple docstring""" pass @unittest.skip(reason="""MobileViT does not output attentions""" ) def _snake_case ( self :Dict ) -> Optional[int]: """simple docstring""" pass def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = model_class(__A ) SCREAMING_SNAKE_CASE__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __A ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self :str ) -> Any: """simple docstring""" pass def _snake_case ( self :Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :Any ) -> str: """simple docstring""" def check_hidden_states_output(__A :Union[str, Any] , __A :Any , __A :Any ): SCREAMING_SNAKE_CASE__ = model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**self._prepare_for_class(__A , __A ) ) SCREAMING_SNAKE_CASE__ = outputs.hidden_states SCREAMING_SNAKE_CASE__ = 5 self.assertEqual(len(__A ) , __A ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. SCREAMING_SNAKE_CASE__ = 2 for i in range(len(__A ) ): 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 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) def _snake_case ( self :List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__A ) @slow def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = MobileViTModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class UpperCamelCase_ ( unittest.TestCase ): @cached_property def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small""" ) if is_vision_available() else None @slow def _snake_case ( self :int ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small""" ).to(__A ) SCREAMING_SNAKE_CASE__ = self.default_image_processor SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""pt""" ).to(__A ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**__A ) # verify the logits SCREAMING_SNAKE_CASE__ = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3] ).to(__A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __A , atol=1E-4 ) ) @slow def _snake_case ( self :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) SCREAMING_SNAKE_CASE__ = model.to(__A ) SCREAMING_SNAKE_CASE__ = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""pt""" ).to(__A ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**__A ) SCREAMING_SNAKE_CASE__ = outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor( [ [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]], [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9_8_6_8, -9.7_1_3_2], [-11.0405, -11.0221, -10.7318]], [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]], ] , device=__A , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __A , atol=1E-4 ) ) @slow def _snake_case ( self :List[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) SCREAMING_SNAKE_CASE__ = model.to(__A ) SCREAMING_SNAKE_CASE__ = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""pt""" ).to(__A ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**__A ) SCREAMING_SNAKE_CASE__ = outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE__ = image_processor.post_process_semantic_segmentation(outputs=__A , target_sizes=[(50, 60)] ) SCREAMING_SNAKE_CASE__ = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , __A ) SCREAMING_SNAKE_CASE__ = image_processor.post_process_semantic_segmentation(outputs=__A ) SCREAMING_SNAKE_CASE__ = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , __A )
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCamelCase = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3FeatureExtractor'] _lowerCamelCase = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "deta" lowerCamelCase_ = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self :Dict , __A :Tuple=None , __A :Union[str, Any]=900 , __A :str=2048 , __A :int=6 , __A :Tuple=2048 , __A :List[Any]=8 , __A :List[Any]=6 , __A :Optional[Any]=1024 , __A :List[Any]=8 , __A :List[str]=0.0 , __A :int=True , __A :Any="relu" , __A :str=256 , __A :int=0.1 , __A :Union[str, Any]=0.0 , __A :Union[str, Any]=0.0 , __A :List[str]=0.0_2 , __A :Dict=1.0 , __A :str=True , __A :Tuple=False , __A :int="sine" , __A :str=5 , __A :List[str]=4 , __A :Optional[int]=4 , __A :List[Any]=True , __A :Dict=300 , __A :Optional[int]=True , __A :List[Any]=True , __A :List[Any]=1 , __A :List[str]=5 , __A :Any=2 , __A :Tuple=1 , __A :List[Any]=1 , __A :Any=5 , __A :List[Any]=2 , __A :Union[str, Any]=0.1 , __A :Optional[Any]=0.2_5 , **__A :int , ) -> Any: """simple docstring""" if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) SCREAMING_SNAKE_CASE__ = CONFIG_MAPPING["""resnet"""](out_features=["""stage2""", """stage3""", """stage4"""] ) else: if isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = backbone_config.pop("""model_type""" ) SCREAMING_SNAKE_CASE__ = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE__ = config_class.from_dict(__A ) SCREAMING_SNAKE_CASE__ = backbone_config SCREAMING_SNAKE_CASE__ = num_queries SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = d_model SCREAMING_SNAKE_CASE__ = encoder_ffn_dim SCREAMING_SNAKE_CASE__ = encoder_layers SCREAMING_SNAKE_CASE__ = encoder_attention_heads SCREAMING_SNAKE_CASE__ = decoder_ffn_dim SCREAMING_SNAKE_CASE__ = decoder_layers SCREAMING_SNAKE_CASE__ = decoder_attention_heads SCREAMING_SNAKE_CASE__ = dropout SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = activation_dropout SCREAMING_SNAKE_CASE__ = activation_function SCREAMING_SNAKE_CASE__ = init_std SCREAMING_SNAKE_CASE__ = init_xavier_std SCREAMING_SNAKE_CASE__ = encoder_layerdrop SCREAMING_SNAKE_CASE__ = auxiliary_loss SCREAMING_SNAKE_CASE__ = position_embedding_type # deformable attributes SCREAMING_SNAKE_CASE__ = num_feature_levels SCREAMING_SNAKE_CASE__ = encoder_n_points SCREAMING_SNAKE_CASE__ = decoder_n_points SCREAMING_SNAKE_CASE__ = two_stage SCREAMING_SNAKE_CASE__ = two_stage_num_proposals SCREAMING_SNAKE_CASE__ = with_box_refine SCREAMING_SNAKE_CASE__ = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError("""If two_stage is True, with_box_refine must be True.""" ) # Hungarian matcher SCREAMING_SNAKE_CASE__ = class_cost SCREAMING_SNAKE_CASE__ = bbox_cost SCREAMING_SNAKE_CASE__ = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE__ = mask_loss_coefficient SCREAMING_SNAKE_CASE__ = dice_loss_coefficient SCREAMING_SNAKE_CASE__ = bbox_loss_coefficient SCREAMING_SNAKE_CASE__ = giou_loss_coefficient SCREAMING_SNAKE_CASE__ = eos_coefficient SCREAMING_SNAKE_CASE__ = focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def _snake_case ( self :List[str] ) -> int: """simple docstring""" return self.encoder_attention_heads @property def _snake_case ( self :List[Any] ) -> int: """simple docstring""" return self.d_model def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
716
import inspect import unittest class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self :Any ) -> Any: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ = inspect.getmembers(__A , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ = """k-diffusion""" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ = """invisible-watermark""" assert backend in deps, f'''{backend} is not in the deps table!'''
59
0
import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any]=32 , UpperCamelCase__: List[Any]=10 , UpperCamelCase__: str=100 , UpperCamelCase__: Any=1_026 , UpperCamelCase__: int=True , UpperCamelCase__: str="data/tokenized_stories_train_wikitext103.jbl" , UpperCamelCase__: str="igf_context_pairs.jbl" , ): set_seed(3 ) # generate train_data and objective_set SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = generate_datasets( UpperCamelCase__ , UpperCamelCase__ , number=UpperCamelCase__ , min_len=1_026 , trim=UpperCamelCase__ ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? SCREAMING_SNAKE_CASE__ = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # load pretrained model SCREAMING_SNAKE_CASE__ = load_gpta("""gpt2""" ).to(UpperCamelCase__ ) print("""computing perplexity on objective set""" ) SCREAMING_SNAKE_CASE__ = compute_perplexity(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).item() print("""perplexity on objective set:""" , UpperCamelCase__ ) # collect igf pairs and save to file demo.jbl collect_objective_set(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Optional[int]=15 , UpperCamelCase__: Union[str, Any]=128 , UpperCamelCase__: List[Any]=100 , UpperCamelCase__: Optional[int]="igf_model.pt" , ): set_seed(42 ) # Load pre-trained model SCREAMING_SNAKE_CASE__ = GPTaLMHeadModel.from_pretrained("""gpt2""" ) # Initialize secondary learner to use embedding weights of model SCREAMING_SNAKE_CASE__ = SecondaryLearner(UpperCamelCase__ ) # Train secondary learner SCREAMING_SNAKE_CASE__ = train_secondary_learner( UpperCamelCase__ , UpperCamelCase__ , max_epochs=UpperCamelCase__ , batch_size=UpperCamelCase__ , eval_freq=100 , igf_model_path=UpperCamelCase__ , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: int , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any=32 , UpperCamelCase__: Any=1_000 , UpperCamelCase__: Union[str, Any]=16 , UpperCamelCase__: Dict=1.0 , UpperCamelCase__: List[str]=recopy_gpta , UpperCamelCase__: List[str]=None , UpperCamelCase__: List[str]=10 , UpperCamelCase__: List[str]="gpt2_finetuned.pt" , ): SCREAMING_SNAKE_CASE__ = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) SCREAMING_SNAKE_CASE__ = RandomSampler(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , sampler=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = max_steps // (len(UpperCamelCase__ )) + 1 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = torch.zeros((1, context_len) , dtype=torch.long , device=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = recopy_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) model.train() if secondary_learner is not None: secondary_learner.to(UpperCamelCase__ ) secondary_learner.eval() SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] # Compute the performance of the transformer model at the beginning SCREAMING_SNAKE_CASE__ = compute_perplexity(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) test_perps.append(UpperCamelCase__ ) print("""Test perplexity, step""" , UpperCamelCase__ , """:""" , UpperCamelCase__ ) for epoch in range(int(UpperCamelCase__ ) ): for step, example in enumerate(UpperCamelCase__ ): torch.cuda.empty_cache() SCREAMING_SNAKE_CASE__ = random.randint(0 , example.size(2 ) - context_len - 1 ) SCREAMING_SNAKE_CASE__ = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ , labels=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = True if secondary_learner is not None: SCREAMING_SNAKE_CASE__ = secondary_learner.forward( torch.tensor(UpperCamelCase__ , dtype=torch.long , device=UpperCamelCase__ ).unsqueeze(0 ) )[0].item() observed_qs.append(float(UpperCamelCase__ ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: SCREAMING_SNAKE_CASE__ = -1 if predicted_q < threshold: SCREAMING_SNAKE_CASE__ = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) SCREAMING_SNAKE_CASE__ = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() SCREAMING_SNAKE_CASE__ = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: SCREAMING_SNAKE_CASE__ = compute_perplexity(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) test_perps.append(UpperCamelCase__ ) print("""Test perplexity, step""" , UpperCamelCase__ , """:""" , UpperCamelCase__ ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , UpperCamelCase__ ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser(description="""Fine-tune a transformer model with IGF on a language modeling task""" ) # Required parameters parser.add_argument( """--data_dir""" , default=UpperCamelCase__ , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""The input data dir. Should contain data files for WikiText.""" , ) parser.add_argument( """--model_name_or_path""" , default=UpperCamelCase__ , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""Path to pretrained model or model identifier from huggingface.co/models""" , ) parser.add_argument( """--data_file""" , type=UpperCamelCase__ , default=UpperCamelCase__ , help=( """A jbl file containing tokenized data which can be split as objective dataset, """ """train_dataset and test_dataset.""" ) , ) parser.add_argument( """--igf_data_file""" , type=UpperCamelCase__ , default=UpperCamelCase__ , help="""A jbl file containing the context and information gain pairs to train secondary learner.""" , ) parser.add_argument( """--output_dir""" , default=UpperCamelCase__ , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""The output directory where the final fine-tuned model is stored.""" , ) parser.add_argument( """--tokenizer_name""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Pretrained tokenizer name or path if not the same as model_name""" , ) parser.add_argument("""--seed""" , type=UpperCamelCase__ , default=UpperCamelCase__ , help="""A seed for reproducible training.""" ) parser.add_argument( """--context_len""" , default=32 , type=UpperCamelCase__ , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--size_objective_set""" , default=100 , type=UpperCamelCase__ , help="""number of articles that are long enough to be used as our objective set""" , ) parser.add_argument( """--eval_freq""" , default=100 , type=UpperCamelCase__ , help="""secondary model evaluation is triggered at eval_freq""" ) parser.add_argument("""--max_steps""" , default=1_000 , type=UpperCamelCase__ , help="""To calculate training epochs""" ) parser.add_argument( """--secondary_learner_batch_size""" , default=128 , type=UpperCamelCase__ , help="""batch size of training data for secondary learner""" , ) parser.add_argument( """--batch_size""" , default=16 , type=UpperCamelCase__ , help="""batch size of training data of language model(gpt2) """ ) parser.add_argument( """--eval_interval""" , default=10 , type=UpperCamelCase__ , help=( """decay the selectivity of our secondary learner filter from""" """1 standard deviation above average to 1 below average after 10 batches""" ) , ) parser.add_argument( """--number""" , default=100 , type=UpperCamelCase__ , help="""The number of examples split to be used as objective_set/test_data""" ) parser.add_argument( """--min_len""" , default=1_026 , type=UpperCamelCase__ , help="""The minimum length of the article to be used as objective set""" ) parser.add_argument( """--secondary_learner_max_epochs""" , default=15 , type=UpperCamelCase__ , help="""number of epochs to train secondary learner""" ) parser.add_argument("""--trim""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""truncate the example if it exceeds context length""" ) parser.add_argument( """--threshold""" , default=1.0 , type=UpperCamelCase__ , help=( """The threshold value used by secondary learner to filter the train_data and allow only""" """ informative data as input to the model""" ) , ) parser.add_argument("""--finetuned_model_name""" , default="""gpt2_finetuned.pt""" , type=UpperCamelCase__ , help="""finetuned_model_name""" ) parser.add_argument( """--recopy_model""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Reset the model to the original pretrained GPT-2 weights after each iteration""" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1_026 , trim=UpperCamelCase__ , data_file="""data/tokenized_stories_train_wikitext103.jbl""" , igf_data_file="""igf_context_pairs.jbl""" , ) # Load train data for secondary learner SCREAMING_SNAKE_CASE__ = joblib.load("""data/IGF_values.jbl""" ) # Train secondary learner SCREAMING_SNAKE_CASE__ = training_secondary_learner( UpperCamelCase__ , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="""igf_model.pt""" , ) # load pretrained gpt2 model SCREAMING_SNAKE_CASE__ = GPTaLMHeadModel.from_pretrained("""gpt2""" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = generate_datasets( context_len=32 , file="""data/tokenized_stories_train_wikitext103.jbl""" , number=100 , min_len=1_026 , trim=UpperCamelCase__ ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , context_len=32 , max_steps=1_000 , batch_size=16 , threshold=1.0 , recopy_model=UpperCamelCase__ , secondary_learner=UpperCamelCase__ , eval_interval=10 , finetuned_model_name="""gpt2_finetuned.pt""" , ) if __name__ == "__main__": main()
717
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 _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
59
0
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values _lowerCamelCase = argparse.ArgumentParser() parser.add_argument('--user', type=str, default='ubuntu') parser.add_argument('--host', type=str, default='localhost') parser.add_argument('--key_path', type=str, default=None) parser.add_argument('--instance', type=str, default='V100:1') parser.add_argument('--provider', type=str, default='cheapest') parser.add_argument('--use_spot', type=bool, default=False) parser.add_argument('--example', type=str, default='pytorch/text-generation/run_generation.py') _lowerCamelCase , _lowerCamelCase = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('Cannot specify both BYO and on-demand cluster args') _lowerCamelCase = rh.cluster( name='rh-cluster', ips=[args.host], ssh_creds={'ssh_user': args.user, 'ssh_private_key': args.key_path} ) else: _lowerCamelCase = rh.cluster( name='rh-cluster', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) _lowerCamelCase = args.example.rsplit('/', 1)[0] # Set up remote environment cluster.install_packages(['pip:./']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([F'''pip install -r transformers/examples/{example_dir}/requirements.txt''']) cluster.run(['pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([F'''python transformers/examples/{args.example} {' '.join(shlex.quote(arg) for arg in unknown)}''']) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
718
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = OpenAIGPTTokenizer lowerCamelCase_ = OpenAIGPTTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Union[str, Any] , __A :str ) -> List[Any]: """simple docstring""" return "lower newer", "lower newer" def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE__ = """lower""" SCREAMING_SNAKE_CASE__ = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] , __A :Optional[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) # Simple input SCREAMING_SNAKE_CASE__ = """This is a simple input""" SCREAMING_SNAKE_CASE__ = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE__ = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) # Pair input self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ ): pass
59
0
from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class UpperCamelCase_ : def __init__( self :Tuple , __A :Any , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = 13 SCREAMING_SNAKE_CASE__ = 7 SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = 99 SCREAMING_SNAKE_CASE__ = 32 SCREAMING_SNAKE_CASE__ = 2 SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = 37 SCREAMING_SNAKE_CASE__ = """gelu""" SCREAMING_SNAKE_CASE__ = 0.1 SCREAMING_SNAKE_CASE__ = 0.1 SCREAMING_SNAKE_CASE__ = 512 SCREAMING_SNAKE_CASE__ = 16 SCREAMING_SNAKE_CASE__ = 2 SCREAMING_SNAKE_CASE__ = 0.0_2 SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = None def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = 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 , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self :List[str] , __A :List[Any] , __A :Dict , __A :int , __A :Optional[Any] , __A :Any , __A :List[str] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFDistilBertModel(config=__A ) SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = [input_ids, input_mask] SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :Tuple , __A :Optional[int] , __A :List[str] , __A :Union[str, Any] , __A :Any , __A :List[Any] , __A :Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFDistilBertForMaskedLM(config=__A ) SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :Tuple , __A :int , __A :str , __A :Union[str, Any] , __A :Optional[Any] , __A :Any , __A :List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFDistilBertForQuestionAnswering(config=__A ) SCREAMING_SNAKE_CASE__ = { """input_ids""": input_ids, """attention_mask""": input_mask, } SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self :Dict , __A :Optional[Any] , __A :Optional[Any] , __A :Dict , __A :Optional[int] , __A :List[Any] , __A :Tuple ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = TFDistilBertForSequenceClassification(__A ) SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self :Union[str, Any] , __A :List[str] , __A :Any , __A :Optional[int] , __A :int , __A :str , __A :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_choices SCREAMING_SNAKE_CASE__ = TFDistilBertForMultipleChoice(__A ) SCREAMING_SNAKE_CASE__ = tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ = tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self :List[Any] , __A :Any , __A :Any , __A :int , __A :List[Any] , __A :str , __A :Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = TFDistilBertForTokenClassification(__A ) SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) lowerCamelCase_ = ( { "feature-extraction": TFDistilBertModel, "fill-mask": TFDistilBertForMaskedLM, "question-answering": TFDistilBertForQuestionAnswering, "text-classification": TFDistilBertForSequenceClassification, "token-classification": TFDistilBertForTokenClassification, "zero-shot": TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFDistilBertModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , dim=37 ) def _snake_case ( self :List[str] ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*__A ) def _snake_case ( self :List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*__A ) def _snake_case ( self :List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*__A ) def _snake_case ( self :Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*__A ) def _snake_case ( self :str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*__A ) @slow def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): SCREAMING_SNAKE_CASE__ = TFDistilBertModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @require_tf class UpperCamelCase_ ( unittest.TestCase ): @slow def _snake_case ( self :List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) SCREAMING_SNAKE_CASE__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE__ = model(__A )[0] SCREAMING_SNAKE_CASE__ = [1, 6, 768] self.assertEqual(output.shape , __A ) SCREAMING_SNAKE_CASE__ = tf.constant( [ [ [0.1_9_2_6_1_8_8_5, -0.1_3_7_3_2_9_5_5, 0.4_1_1_9_7_9_9], [0.2_2_1_5_0_1_5_6, -0.0_7_4_2_2_6_6_1, 0.3_9_0_3_7_2_0_4], [0.2_2_7_5_6_0_1_8, -0.0_8_9_6_4_1_4, 0.3_7_0_1_4_6_7], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __A , atol=1E-4 )
719
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
0
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Optional[int] , __A :Any , __A :Union[str, Any]=13 , __A :List[Any]=7 , __A :List[str]=True , __A :List[Any]=True , __A :str=False , __A :Union[str, Any]=True , __A :Any=99 , __A :List[Any]=32 , __A :int=5 , __A :Union[str, Any]=4 , __A :Tuple=64 , __A :Tuple="gelu" , __A :List[Any]=0.1 , __A :Optional[Any]=0.1 , __A :int=512 , __A :int=16 , __A :Optional[int]=2 , __A :Tuple=0.0_2 , __A :Union[str, Any]=3 , __A :Optional[int]=4 , __A :List[str]=None , __A :Any=2 , __A :Optional[Any]=2 , __A :Tuple=2 , __A :Optional[Any]=2 , __A :Optional[Any]=4 , __A :Dict=1 , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_mask SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = scope SCREAMING_SNAKE_CASE__ = q_groups SCREAMING_SNAKE_CASE__ = k_groups SCREAMING_SNAKE_CASE__ = v_groups SCREAMING_SNAKE_CASE__ = post_attention_groups SCREAMING_SNAKE_CASE__ = intermediate_groups SCREAMING_SNAKE_CASE__ = output_groups def _snake_case ( self :List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" return SqueezeBertConfig( embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def _snake_case ( self :Tuple , __A :Dict , __A :Union[str, Any] , __A :Any , __A :Union[str, Any] , __A :Optional[int] , __A :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = SqueezeBertModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , __A ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :int , __A :Dict , __A :Optional[Any] , __A :List[Any] , __A :str , __A :str , __A :int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = SqueezeBertForMaskedLM(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :int , __A :str , __A :Optional[Any] , __A :Tuple , __A :Optional[Any] , __A :Optional[Any] , __A :str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = SqueezeBertForQuestionAnswering(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , start_positions=__A , end_positions=__A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self :int , __A :Optional[Any] , __A :int , __A :str , __A :int , __A :List[Any] , __A :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = SqueezeBertForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self :Union[str, Any] , __A :Tuple , __A :List[Any] , __A :int , __A :List[str] , __A :Any , __A :Optional[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = SqueezeBertForTokenClassification(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self :Any , __A :Any , __A :List[str] , __A :List[Any] , __A :int , __A :str , __A :Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_choices SCREAMING_SNAKE_CASE__ = SqueezeBertForMultipleChoice(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowerCamelCase_ = ( { "feature-extraction": SqueezeBertModel, "fill-mask": SqueezeBertForMaskedLM, "question-answering": SqueezeBertForQuestionAnswering, "text-classification": SqueezeBertForSequenceClassification, "token-classification": SqueezeBertForTokenClassification, "zero-shot": SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :List[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , dim=37 ) def _snake_case ( self :List[Any] ) -> int: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*__A ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*__A ) def _snake_case ( self :List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*__A ) def _snake_case ( self :List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*__A ) def _snake_case ( self :Union[str, Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*__A ) def _snake_case ( self :Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*__A ) @slow def _snake_case ( self :Dict ) -> Union[str, Any]: """simple docstring""" for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = SqueezeBertModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @require_sentencepiece @require_tokenizers @require_torch class UpperCamelCase_ ( unittest.TestCase ): @slow def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) SCREAMING_SNAKE_CASE__ = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE__ = model(__A )[0] SCREAMING_SNAKE_CASE__ = torch.Size((1, 3) ) self.assertEqual(output.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor([[0.6_4_0_1, -0.0_3_4_9, -0.6_0_4_1]] ) self.assertTrue(torch.allclose(__A , __A , atol=1E-4 ) )
720
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
0
import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _lowerCamelCase = version.parse(importlib_metadata.version('nltk')) if NLTK_VERSION >= version.Version('3.6.4'): from nltk import word_tokenize _lowerCamelCase = '\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n' _lowerCamelCase = '\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n' _lowerCamelCase = '\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\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.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n \'meteor\': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric(\'meteor\')\n >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]\n >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results["meteor"], 4))\n 0.6944\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase_ ( datasets.Metric ): def _snake_case ( self :Union[str, Any] ) -> Dict: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"""] , reference_urls=[ """https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score""", """https://en.wikipedia.org/wiki/METEOR""", ] , ) def _snake_case ( self :Dict , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" import nltk nltk.download("""wordnet""" ) if NLTK_VERSION >= version.Version("""3.6.5""" ): nltk.download("""punkt""" ) if NLTK_VERSION >= version.Version("""3.6.6""" ): nltk.download("""omw-1.4""" ) def _snake_case ( self :int , __A :Any , __A :Optional[Any] , __A :Optional[int]=0.9 , __A :List[str]=3 , __A :Any=0.5 ) -> Optional[Any]: """simple docstring""" if NLTK_VERSION >= version.Version("""3.6.5""" ): SCREAMING_SNAKE_CASE__ = [ meteor_score.single_meteor_score( word_tokenize(__A ) , word_tokenize(__A ) , alpha=__A , beta=__A , gamma=__A ) for ref, pred in zip(__A , __A ) ] else: SCREAMING_SNAKE_CASE__ = [ meteor_score.single_meteor_score(__A , __A , alpha=__A , beta=__A , gamma=__A ) for ref, pred in zip(__A , __A ) ] return {"meteor": np.mean(__A )}
721
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
59
0
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase_ ( unittest.TestCase ): def __init__( self :Dict , __A :List[Any] , __A :List[str]=3 , __A :Any=32 , __A :Dict=3 , __A :Optional[int]=10 , __A :Dict=[10, 20, 30, 40] , __A :List[str]=[1, 1, 2, 1] , __A :int=True , __A :str=True , __A :List[str]="relu" , __A :Optional[int]=3 , __A :List[Any]=None , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embeddings_size SCREAMING_SNAKE_CASE__ = hidden_sizes SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = scope SCREAMING_SNAKE_CASE__ = len(__A ) def _snake_case ( self :Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ = self.get_config() return config, pixel_values def _snake_case ( self :Optional[int] ) -> Tuple: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _snake_case ( self :str , __A :int , __A :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaxRegNetModel(config=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _snake_case ( self :Optional[Any] , __A :Dict , __A :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = FlaxRegNetForImageClassification(config=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self :List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_flax class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :int ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaxRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , has_text_modality=__A ) def _snake_case ( self :List[str] ) -> str: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" return def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def _snake_case ( self :int ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" pass def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = model_class(__A ) SCREAMING_SNAKE_CASE__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __A ) def _snake_case ( self :Union[str, Any] ) -> str: """simple docstring""" def check_hidden_states_output(__A :Optional[int] , __A :str , __A :Optional[Any] ): SCREAMING_SNAKE_CASE__ = model_class(__A ) SCREAMING_SNAKE_CASE__ = model(**self._prepare_for_class(__A , __A ) ) SCREAMING_SNAKE_CASE__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ = self.model_tester.num_stages self.assertEqual(len(__A ) , expected_num_stages + 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE__ = self._prepare_for_class(__A , __A ) SCREAMING_SNAKE_CASE__ = model_class(__A ) @jax.jit def model_jitted(__A :Dict , **__A :Any ): return model(pixel_values=__A , **__A ) with self.subTest("""JIT Enabled""" ): SCREAMING_SNAKE_CASE__ = model_jitted(**__A ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): SCREAMING_SNAKE_CASE__ = model_jitted(**__A ).to_tuple() self.assertEqual(len(__A ) , len(__A ) ) for jitted_output, output in zip(__A , __A ): self.assertEqual(jitted_output.shape , output.shape ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_flax class UpperCamelCase_ ( unittest.TestCase ): @cached_property def _snake_case ( self :List[Any] ) -> Optional[Any]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/regnet-y-040""" ) if is_vision_available() else None @slow def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaxRegNetForImageClassification.from_pretrained("""facebook/regnet-y-040""" ) SCREAMING_SNAKE_CASE__ = self.default_image_processor SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ = model(**__A ) # verify the logits SCREAMING_SNAKE_CASE__ = (1, 1000) self.assertEqual(outputs.logits.shape , __A ) SCREAMING_SNAKE_CASE__ = jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , __A , atol=1E-4 ) )
700
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__: float ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
59
0
'''simple docstring''' from math import pow def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: int , ): if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count SCREAMING_SNAKE_CASE__ = int(pow(UpperCamelCase__ , UpperCamelCase__ ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = backtrack( UpperCamelCase__ , UpperCamelCase__ , current_number + 1 , UpperCamelCase__ , UpperCamelCase__ ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = backtrack( UpperCamelCase__ , UpperCamelCase__ , current_number + 1 , UpperCamelCase__ , UpperCamelCase__ ) return current_sum, solutions_count def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: int ): if not (1 <= needed_sum <= 1_000 and 2 <= power <= 10): raise ValueError( """Invalid input\n""" """needed_sum must be between 1 and 1000, power between 2 and 10.""" ) return backtrack(UpperCamelCase__ , UpperCamelCase__ , 1 , 0 , 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
701
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
0
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
702
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCamelCase__ ) EnvironmentCommand.register_subcommand(UpperCamelCase__ ) TestCommand.register_subcommand(UpperCamelCase__ ) RunBeamCommand.register_subcommand(UpperCamelCase__ ) DummyDataCommand.register_subcommand(UpperCamelCase__ ) # Parse args SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_known_args() if not hasattr(UpperCamelCase__ , """func""" ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE__ = parse_unknown_args(UpperCamelCase__ ) # Run SCREAMING_SNAKE_CASE__ = args.func(UpperCamelCase__ , **UpperCamelCase__ ) service.run() if __name__ == "__main__": main()
59
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "cvt" def __init__( self :Any , __A :List[str]=3 , __A :Any=[7, 3, 3] , __A :Optional[Any]=[4, 2, 2] , __A :Union[str, Any]=[2, 1, 1] , __A :List[str]=[64, 192, 384] , __A :int=[1, 3, 6] , __A :Any=[1, 2, 10] , __A :Optional[int]=[4.0, 4.0, 4.0] , __A :List[Any]=[0.0, 0.0, 0.0] , __A :Tuple=[0.0, 0.0, 0.0] , __A :Any=[0.0, 0.0, 0.1] , __A :Any=[True, True, True] , __A :Any=[False, False, True] , __A :Dict=["dw_bn", "dw_bn", "dw_bn"] , __A :Optional[Any]=[3, 3, 3] , __A :Dict=[1, 1, 1] , __A :List[str]=[2, 2, 2] , __A :Dict=[1, 1, 1] , __A :int=[1, 1, 1] , __A :Any=0.0_2 , __A :Optional[Any]=1E-12 , **__A :Union[str, Any] , ) -> str: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = patch_sizes SCREAMING_SNAKE_CASE__ = patch_stride SCREAMING_SNAKE_CASE__ = patch_padding SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = depth SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = attention_drop_rate SCREAMING_SNAKE_CASE__ = drop_rate SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = cls_token SCREAMING_SNAKE_CASE__ = qkv_projection_method SCREAMING_SNAKE_CASE__ = kernel_qkv SCREAMING_SNAKE_CASE__ = padding_kv SCREAMING_SNAKE_CASE__ = stride_kv SCREAMING_SNAKE_CASE__ = padding_q SCREAMING_SNAKE_CASE__ = stride_q SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = layer_norm_eps
703
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , *__A :Tuple , **__A :Dict ) -> None: """simple docstring""" warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __A , ) super().__init__(*__A , **__A )
59
0
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[int] ) -> str: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__A , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = Accelerator() _lowerCamelCase = (accelerator.state.process_index + 2, 10) _lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device) _lowerCamelCase = '' _lowerCamelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." _lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." _lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
704
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
59
0
from datetime import datetime import matplotlib.pyplot as plt import torch def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): for param in module.parameters(): SCREAMING_SNAKE_CASE__ = False def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """cuda""" if torch.cuda.is_available() else """cpu""" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): SCREAMING_SNAKE_CASE__ = """mps""" if device == "mps": print( """WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch""" """ errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues""" """ with generations.""" ) return device def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = plt.imshow(UpperCamelCase__ ) fig.axes.get_xaxis().set_visible(UpperCamelCase__ ) fig.axes.get_yaxis().set_visible(UpperCamelCase__ ) plt.show() def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = datetime.now() SCREAMING_SNAKE_CASE__ = current_time.strftime("""%H:%M:%S""" ) return timestamp
705
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__ )}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
0
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = emb.weight.shape SCREAMING_SNAKE_CASE__ = nn.Linear(UpperCamelCase__ , UpperCamelCase__ , bias=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = emb.weight.data return lin_layer def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ = mam_aaa["""args"""] or mam_aaa["""cfg"""]["""model"""] SCREAMING_SNAKE_CASE__ = mam_aaa["""model"""] remove_ignore_keys_(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = state_dict["""encoder.embed_tokens.weight"""].shape[0] SCREAMING_SNAKE_CASE__ = MaMaaaConfig( vocab_size=UpperCamelCase__ , max_position_embeddings=1_024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , ) SCREAMING_SNAKE_CASE__ = state_dict["""decoder.embed_tokens.weight"""] SCREAMING_SNAKE_CASE__ = MaMaaaForConditionalGeneration(UpperCamelCase__ ) model.model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": _lowerCamelCase = 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.') _lowerCamelCase = parser.parse_args() _lowerCamelCase = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
706
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
59
0
import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel _lowerCamelCase = '0.12' # assumed parallelism: 8 @require_flax @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): @classmethod def _snake_case ( cls :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TOKEN HfFolder.save_token(__A ) @classmethod def _snake_case ( cls :str ) -> List[Any]: """simple docstring""" try: delete_repo(token=cls._token , repo_id="""test-model-flax""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-model-flax-org""" ) except HTTPError: pass def _snake_case ( self :List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) SCREAMING_SNAKE_CASE__ = FlaxBertModel(__A ) model.push_to_hub("""test-model-flax""" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(f'''{USER}/test-model-flax''' ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__A , 1E-3 , msg=f'''{key} not identical''' ) # Reset repo delete_repo(token=self._token , repo_id="""test-model-flax""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(__A , repo_id="""test-model-flax""" , push_to_hub=__A , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(f'''{USER}/test-model-flax''' ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__A , 1E-3 , msg=f'''{key} not identical''' ) def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) SCREAMING_SNAKE_CASE__ = FlaxBertModel(__A ) model.push_to_hub("""valid_org/test-model-flax-org""" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained("""valid_org/test-model-flax-org""" ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__A , 1E-3 , msg=f'''{key} not identical''' ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-model-flax-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( __A , repo_id="""valid_org/test-model-flax-org""" , push_to_hub=__A , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained("""valid_org/test-model-flax-org""" ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__A , 1E-3 , msg=f'''{key} not identical''' ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = flatten_dict(modela.params ) SCREAMING_SNAKE_CASE__ = flatten_dict(modela.params ) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1e-4: SCREAMING_SNAKE_CASE__ = False return models_are_equal @require_flax class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) SCREAMING_SNAKE_CASE__ = FlaxBertModel(__A ) SCREAMING_SNAKE_CASE__ = """bert""" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(__A , __A ) ) with self.assertRaises(__A ): SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A , subfolder=__A ) self.assertTrue(check_models_equal(__A , __A ) ) def _snake_case ( self :Union[str, Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) SCREAMING_SNAKE_CASE__ = FlaxBertModel(__A ) SCREAMING_SNAKE_CASE__ = """bert""" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(__A , __A ) , max_shard_size="""10KB""" ) with self.assertRaises(__A ): SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A , subfolder=__A ) self.assertTrue(check_models_equal(__A , __A ) ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = """bert""" SCREAMING_SNAKE_CASE__ = """hf-internal-testing/tiny-random-bert-subfolder""" with self.assertRaises(__A ): SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A , subfolder=__A ) self.assertIsNotNone(__A ) def _snake_case ( self :List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """bert""" SCREAMING_SNAKE_CASE__ = """hf-internal-testing/tiny-random-bert-sharded-subfolder""" with self.assertRaises(__A ): SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A , subfolder=__A ) self.assertIsNotNone(__A )
707
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
59
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json', 'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json', 'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "big_bird" def __init__( self :Any , __A :Union[str, Any]=5_0358 , __A :List[str]=768 , __A :Dict=12 , __A :Tuple=12 , __A :Optional[Any]=3072 , __A :Optional[int]="gelu_new" , __A :Union[str, Any]=0.1 , __A :str=0.1 , __A :int=4096 , __A :List[Any]=2 , __A :List[Any]=0.0_2 , __A :int=1E-12 , __A :Optional[Any]=True , __A :List[Any]=0 , __A :Union[str, Any]=1 , __A :List[Any]=2 , __A :List[str]=66 , __A :Any="block_sparse" , __A :Dict=True , __A :List[Any]=False , __A :int=64 , __A :Optional[Any]=3 , __A :List[str]=None , **__A :int , ) -> Optional[Any]: """simple docstring""" super().__init__( pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , sep_token_id=__A , **__A , ) SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = rescale_embeddings SCREAMING_SNAKE_CASE__ = attention_type SCREAMING_SNAKE_CASE__ = use_bias SCREAMING_SNAKE_CASE__ = block_size SCREAMING_SNAKE_CASE__ = num_random_blocks SCREAMING_SNAKE_CASE__ = classifier_dropout class UpperCamelCase_ ( UpperCamelCase__ ): @property def _snake_case ( self :Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """choice""", 2: """sequence"""} else: SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
708
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , default=512 , help="""Maximum sequence length. For training on TPUs, it helps to have a maximum""" """ sequence length that is a multiple of 8.""" , ) parser.add_argument( """--output_dir""" , default="""tf-tpu""" , type=UpperCamelCase__ , help="""Output directory where the TFRecord shards will be saved. If the""" """ path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord""" """ shards will be directly saved to a Google Cloud Storage bucket.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """input_ids""": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["""input_ids"""][i] ) ), """attention_mask""": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["""attention_mask"""][i] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , num_proc=4 , remove_columns=["""text"""] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) shard_count += 1 total_records += records_containing with open(f'''split-{args.split}-records-count.txt''' , """w""" ) as f: print(f'''Total {args.split} records: {total_records}''' , file=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
59
0
import warnings from functools import wraps from typing import Callable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Callable ): @wraps(UpperCamelCase__ ) def _inner_fn(*UpperCamelCase__: Dict , **UpperCamelCase__: Any ): warnings.warn( (f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , UpperCamelCase__ , ) return fn(*UpperCamelCase__ , **UpperCamelCase__ ) return _inner_fn
709
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [] for data in source_data: for i, el in enumerate(UpperCamelCase__ ): if len(UpperCamelCase__ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(UpperCamelCase__ ) ) return data_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = [] for dlist, weight in zip(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: SCREAMING_SNAKE_CASE__ = f'''Invalid weight of {weight:f} provided''' raise ValueError(UpperCamelCase__ ) score_lists.append(UpperCamelCase__ ) return score_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = get_data(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = calculate_each_score(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = generate_final_scores(UpperCamelCase__ ) # append scores to source data for i, ele in enumerate(UpperCamelCase__ ): source_data[i].append(UpperCamelCase__ ) return source_data
59
0
import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ = 8 # DPR tok SCREAMING_SNAKE_CASE__ = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """dpr_tokenizer""" ) os.makedirs(__A , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , DPR_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] ) ) # BART tok SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] SCREAMING_SNAKE_CASE__ = {"""unk_token""": """<unk>"""} SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """bart_tokenizer""" ) os.makedirs(__A , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , BART_VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , BART_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 _snake_case ( self :Tuple ) -> DPRQuestionEncoderTokenizer: """simple docstring""" return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def _snake_case ( self :Tuple ) -> BartTokenizer: """simple docstring""" return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , """bart_tokenizer""" ) ) def _snake_case ( self :List[str] ) -> Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) @require_tokenizers def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """rag_tokenizer""" ) SCREAMING_SNAKE_CASE__ = RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() ) SCREAMING_SNAKE_CASE__ = RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer() ) rag_config.save_pretrained(__A ) rag_tokenizer.save_pretrained(__A ) SCREAMING_SNAKE_CASE__ = RagTokenizer.from_pretrained(__A , config=__A ) self.assertIsInstance(new_rag_tokenizer.question_encoder , __A ) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab() ) self.assertIsInstance(new_rag_tokenizer.generator , __A ) self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab() ) @slow def _snake_case ( self :List[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = RagTokenizer.from_pretrained("""facebook/rag-token-nq""" ) SCREAMING_SNAKE_CASE__ = [ """who got the first nobel prize in physics""", """when is the next deadpool movie being released""", """which mode is used for short wave broadcast service""", """who is the owner of reading football club""", """when is the next scandal episode coming out""", """when is the last time the philadelphia won the superbowl""", """what is the most current adobe flash player version""", """how many episodes are there in dragon ball z""", """what is the first step in the evolution of the eye""", """where is gall bladder situated in human body""", """what is the main mineral in lithium batteries""", """who is the president of usa right now""", """where do the greasers live in the outsiders""", """panda is a national animal of which country""", """what is the name of manchester united stadium""", ] SCREAMING_SNAKE_CASE__ = tokenizer(__A ) self.assertIsNotNone(__A ) @slow def _snake_case ( self :List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = RagTokenizer.from_pretrained("""facebook/rag-sequence-nq""" ) SCREAMING_SNAKE_CASE__ = [ """who got the first nobel prize in physics""", """when is the next deadpool movie being released""", """which mode is used for short wave broadcast service""", """who is the owner of reading football club""", """when is the next scandal episode coming out""", """when is the last time the philadelphia won the superbowl""", """what is the most current adobe flash player version""", """how many episodes are there in dragon ball z""", """what is the first step in the evolution of the eye""", """where is gall bladder situated in human body""", """what is the main mineral in lithium batteries""", """who is the president of usa right now""", """where do the greasers live in the outsiders""", """panda is a national animal of which country""", """what is the name of manchester united stadium""", ] SCREAMING_SNAKE_CASE__ = tokenizer(__A ) self.assertIsNotNone(__A )
710
import warnings from functools import wraps from typing import Callable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Callable ): @wraps(UpperCamelCase__ ) def _inner_fn(*UpperCamelCase__: Dict , **UpperCamelCase__: Any ): warnings.warn( (f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , UpperCamelCase__ , ) return fn(*UpperCamelCase__ , **UpperCamelCase__ ) return _inner_fn
59
0
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 _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
711
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RoCBertTokenizer lowerCamelCase_ = None lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = filter_non_english def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(__A , __A , ensure_ascii=__A ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(__A , __A , ensure_ascii=__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(__A , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__A ) , [5, 6, 2, 5, 7, 8] ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=__A , 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 _snake_case ( self :Any ) -> str: """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 _snake_case ( self :int ) -> str: """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 _snake_case ( self :List[str] ) -> List[str]: """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 _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def _snake_case ( self :int ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(__A , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE__ = ( [ ((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 _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你好""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你是谁""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( __A , __A , __A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(__A , add_special_tokens=__A ) self.assertEqual(__A , __A )
59
0
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": _lowerCamelCase = pd.read_csv('sample_data.csv', header=None) _lowerCamelCase = df.shape[:1][0] # If you're using some other dataset input the target column _lowerCamelCase = df.iloc[:, 1:2] _lowerCamelCase = actual_data.values.reshape(len_data, 1) _lowerCamelCase = MinMaxScaler().fit_transform(actual_data) _lowerCamelCase = 10 _lowerCamelCase = 5 _lowerCamelCase = 20 _lowerCamelCase = len_data - periods * look_back _lowerCamelCase = actual_data[:division] _lowerCamelCase = actual_data[division - look_back :] _lowerCamelCase , _lowerCamelCase = [], [] _lowerCamelCase , _lowerCamelCase = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) _lowerCamelCase = np.array(train_x) _lowerCamelCase = np.array(test_x) _lowerCamelCase = np.array([list(i.ravel()) for i in train_y]) _lowerCamelCase = np.array([list(i.ravel()) for i in test_y]) _lowerCamelCase = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss='mean_squared_error', optimizer='adam') _lowerCamelCase = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) _lowerCamelCase = model.predict(x_test)
712
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = original_name.split(""".""" )[0] SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 2] ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 1] ) SCREAMING_SNAKE_CASE__ = orig_block_num - offset SCREAMING_SNAKE_CASE__ = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = OrderedDict() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): SCREAMING_SNAKE_CASE__ = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 SCREAMING_SNAKE_CASE__ = key[: key.find("""proj""" )] SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , f'''patch_embeddings.{total_embed_found}.''' ) SCREAMING_SNAKE_CASE__ = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: SCREAMING_SNAKE_CASE__ = """poolformer.encoder.""" + key if "mlp.fc1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm1""" , """before_norm""" ) if "norm2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: SCREAMING_SNAKE_CASE__ = key.replace("""head""" , """classifier""" ) SCREAMING_SNAKE_CASE__ = value return new_state_dict def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = PoolFormerConfig() # set attributes based on model_name SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = model_name[-3:] SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = (1, 1_000) # set config attributes SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if size == "s12": SCREAMING_SNAKE_CASE__ = [2, 2, 6, 2] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s24": SCREAMING_SNAKE_CASE__ = [4, 4, 12, 4] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "m36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 elif size == "m48": SCREAMING_SNAKE_CASE__ = [8, 8, 24, 8] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) # Prepare image SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location=torch.device("""cpu""" ) ) # rename keys SCREAMING_SNAKE_CASE__ = rename_keys(UpperCamelCase__ ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ = PoolFormerForImageClassification(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Define image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.logits # define expected logit slices for different models if size == "s12": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": SCREAMING_SNAKE_CASE__ = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": SCREAMING_SNAKE_CASE__ = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": SCREAMING_SNAKE_CASE__ = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , UpperCamelCase__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
0
'''simple docstring''' import pytest _lowerCamelCase = '__dummy_dataset1__' _lowerCamelCase = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def SCREAMING_SNAKE_CASE__ ( ): return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def SCREAMING_SNAKE_CASE__ ( ): return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Tuple , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = dataset_loading_script_name SCREAMING_SNAKE_CASE__ = tmp_path / """datasets""" / script_name script_dir.mkdir(parents=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = script_dir / f'''{script_name}.py''' with open(UpperCamelCase__ , """w""" ) as f: f.write(UpperCamelCase__ ) return str(UpperCamelCase__ )
713
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_text_model" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :Union[str, Any] , __A :Any=5_0244 , __A :Optional[Any]=768 , __A :Tuple=64 , __A :List[str]=2048 , __A :int=12 , __A :str=12 , __A :Any=32 , __A :Tuple=128 , __A :int=0.1 , __A :str=1E-6 , __A :Optional[Any]=1.0 , __A :Union[str, Any]="gelu_new" , __A :Any=0 , __A :List[str]=False , __A :Optional[Any]=0 , __A :int=1 , __A :Optional[int]=False , __A :Optional[Any]=True , **__A :List[Any] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = d_kv SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = num_layers SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = decoder_start_token_id # for backwards compatibility SCREAMING_SNAKE_CASE__ = dense_act_fn super().__init__( pad_token_id=__A , eos_token_id=__A , decoder_start_token_id=__A , tie_word_embeddings=__A , is_decoder=__A , **__A , ) @classmethod def _snake_case ( cls :Optional[int] , __A :Union[str, os.PathLike] , **__A :Optional[int] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = 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(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_vision_model" def __init__( self :Optional[int] , __A :int=768 , __A :Optional[Any]=768 , __A :Union[str, Any]=2048 , __A :int=64 , __A :Union[str, Any]=12 , __A :str=12 , __A :Any="gelu_new" , __A :List[Any]=1E-6 , __A :Dict=0.0 , __A :int=0.0 , __A :int=1E-10 , __A :Dict=1.0 , __A :int=4096 , __A :int=32 , __A :int=128 , **__A :Tuple , ) -> str: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = patch_embed_hidden_size SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = dense_act_fn SCREAMING_SNAKE_CASE__ = seq_len SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = d_kv @classmethod def _snake_case ( cls :str , __A :Union[str, os.PathLike] , **__A :str ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = 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(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct" lowerCamelCase_ = True def __init__( self :str , __A :Optional[Any]=None , __A :List[str]=None , __A :Optional[Any]=1.0 , __A :Optional[Any]=0.0_2 , __A :Any=False , __A :Tuple=False , __A :Any=True , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__(tie_word_embeddings=__A , is_encoder_decoder=__A , **__A ) if text_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE__ = PixaStructTextConfig(**__A ) SCREAMING_SNAKE_CASE__ = PixaStructVisionConfig(**__A ) SCREAMING_SNAKE_CASE__ = self.text_config.decoder_start_token_id SCREAMING_SNAKE_CASE__ = self.text_config.pad_token_id SCREAMING_SNAKE_CASE__ = self.text_config.eos_token_id SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = is_vqa @classmethod def _snake_case ( cls :Union[str, Any] , __A :PixaStructTextConfig , __A :PixaStructVisionConfig , **__A :Optional[int] ) -> Optional[Any]: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__A ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
0
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = XLMProphetNetTokenizer lowerCamelCase_ = False lowerCamelCase_ = True def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ = XLMProphetNetTokenizer(__A , keep_accents=__A ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self :Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """[PAD]""" SCREAMING_SNAKE_CASE__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__A ) , __A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__A ) , __A ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """[PAD]""" ) self.assertEqual(vocab_keys[1] , """[CLS]""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(__A ) , 1012 ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1012 ) def _snake_case ( self :Union[str, Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = XLMProphetNetTokenizer(__A , keep_accents=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__A , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__A ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __A , [ 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""", """é""", """.""", ] , ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) self.assertListEqual( __A , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(__A ) self.assertListEqual( __A , [ 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 _snake_case ( self :Tuple ) -> Any: """simple docstring""" return XLMProphetNetTokenizer.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased""" ) @slow def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """Hello World!""" SCREAMING_SNAKE_CASE__ = [3_5389, 6672, 49, 2] self.assertListEqual(__A , self.big_tokenizer.encode(__A ) ) @slow def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = {"""input_ids""": [[1_1073, 8_2783, 18, 26, 8_2783, 549, 5_1540, 248, 1_7209, 1301, 217, 20, 21_5186, 1325, 147, 1_7209, 1301, 217, 20, 5_6370, 53, 12_2020, 20, 1_6477, 27, 8_7355, 4548, 20, 4728, 7_8392, 17, 15_9969, 18, 26, 2_4491, 629, 15, 538, 2_2704, 5439, 15, 2788, 2_4491, 9885, 15, 4_3534, 605, 15, 814, 1_8403, 3_3200, 29, 15, 4_3534, 2_4458, 1_2410, 111, 2_4966, 8_3669, 9637, 14_4068, 26, 850, 2_2346, 27, 147, 2_4966, 8_3669, 8_3490, 26, 3_9113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 12_2020, 11_5785, 34, 816, 1339, 4_6887, 18, 147, 5_3905, 1951, 4_2238, 4_1170, 1_7732, 834, 436, 15, 2_7523, 9_8733, 217, 147, 5542, 4981, 930, 1_7347, 16, 2], [2_0091, 629, 94, 8_2786, 58, 490, 20, 1528, 84, 5_3905, 344, 8_0592, 11_0128, 1_8822, 5267, 1306, 62, 15_2537, 308, 7997, 401, 12_4427, 549, 3_5442, 225, 109, 1_5055, 2_5748, 147, 7119, 4_3712, 34, 767, 13_5366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 6_3784, 11_9466, 17, 14_7808, 8_8214, 18, 656, 81, 32, 3296, 1_0280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__A , model_name="""microsoft/xprophetnet-large-wiki100-cased""" , revision="""1acad1643ddd54a44df6a1b797ada8373685d90e""" , )
714
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[int] ) -> str: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__A , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = Accelerator() _lowerCamelCase = (accelerator.state.process_index + 2, 10) _lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device) _lowerCamelCase = '' _lowerCamelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." _lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." _lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
0
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class UpperCamelCase_ : def __init__( self :Tuple , __A :str , __A :Optional[int]=13 , __A :Union[str, Any]=7 , __A :Optional[Any]=True , __A :Any=True , __A :List[Any]=False , __A :List[Any]=True , __A :Any=99 , __A :List[str]=32 , __A :int=5 , __A :Any=4 , __A :List[Any]=37 , __A :int="gelu" , __A :Tuple=0.1 , __A :Optional[int]=0.1 , __A :Dict=512 , __A :Optional[Any]=16 , __A :List[Any]=2 , __A :Dict=0.0_2 , __A :Dict=3 , __A :Dict=4 , __A :int=None , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_mask SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = scope def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self :Optional[int] ) -> int: """simple docstring""" return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__A , initializer_range=self.initializer_range , use_stable_embedding=__A , ) def _snake_case ( self :Optional[Any] , __A :Optional[int] , __A :Optional[Any] , __A :Union[str, Any] , __A :List[str] , __A :Dict , __A :Dict , __A :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenLlamaModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :Optional[int] , __A :Union[str, Any] , __A :List[Any] , __A :str , __A :Dict , __A :Dict , __A :Optional[Any] , __A :Tuple , __A :Dict , __A :Union[str, Any] , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = OpenLlamaModel(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , ) SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , encoder_hidden_states=__A , ) SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :Any , __A :Tuple , __A :Any , __A :Optional[int] , __A :str , __A :Optional[Any] , __A :List[Any] , __A :str , __A :Tuple , __A :List[Any] , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenLlamaForCausalLM(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :Union[str, Any] , __A :List[str] , __A :Optional[int] , __A :Dict , __A :Tuple , __A :Tuple , __A :Optional[Any] , __A :str , __A :Optional[Any] , __A :Tuple , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = OpenLlamaForCausalLM(config=__A ) model.to(__A ) model.eval() # first forward pass SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , use_cache=__A , ) SCREAMING_SNAKE_CASE__ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ = torch.cat([input_mask, next_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , output_hidden_states=__A , )["""hidden_states"""][0] SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , past_key_values=__A , output_hidden_states=__A , )["""hidden_states"""][0] # select random slice SCREAMING_SNAKE_CASE__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__A , __A , atol=1E-3 ) ) def _snake_case ( self :List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) lowerCamelCase_ = (OpenLlamaForCausalLM,) if is_torch_available() else () lowerCamelCase_ = ( { "feature-extraction": OpenLlamaModel, "text-classification": OpenLlamaForSequenceClassification, "text-generation": OpenLlamaForCausalLM, "zero-shot": OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenLlamaModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , hidden_size=37 ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ = type self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ = input_ids.ne(1 ).to(__A ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = OpenLlamaForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _snake_case ( self :Dict ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = """single_label_classification""" SCREAMING_SNAKE_CASE__ = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ = input_ids.ne(1 ).to(__A ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = OpenLlamaForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = """multi_label_classification""" SCREAMING_SNAKE_CASE__ = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ = input_ids.ne(1 ).to(__A ) SCREAMING_SNAKE_CASE__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ = OpenLlamaForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("""Open-Llama buffers include complex numbers, which breaks this test""" ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def _snake_case ( self :Tuple , __A :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = ids_tensor([1, 10] , config.vocab_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE__ = OpenLlamaModel(__A ) original_model.to(__A ) original_model.eval() SCREAMING_SNAKE_CASE__ = original_model(__A ).last_hidden_state SCREAMING_SNAKE_CASE__ = original_model(__A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE__ = {"""type""": scaling_type, """factor""": 10.0} SCREAMING_SNAKE_CASE__ = OpenLlamaModel(__A ) scaled_model.to(__A ) scaled_model.eval() SCREAMING_SNAKE_CASE__ = scaled_model(__A ).last_hidden_state SCREAMING_SNAKE_CASE__ = scaled_model(__A ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__A , __A , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(__A , __A , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__A , __A , atol=1E-5 ) )
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCamelCase = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3FeatureExtractor'] _lowerCamelCase = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
0
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 _lowerCamelCase = get_tests_dir('fixtures') class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = mock.Mock() SCREAMING_SNAKE_CASE__ = 500 SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = HTTPError SCREAMING_SNAKE_CASE__ = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained("""hf-internal-testing/tiny-random-vit""" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("""requests.Session.request""" , return_value=__A ) as mock_head: SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained("""hf-internal-testing/tiny-random-vit""" ) # This check we did call the fake head request mock_head.assert_called() def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained( """https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json""" ) def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" with self.assertRaises(__A ): # config is in subfolder, the following should not work without specifying the subfolder SCREAMING_SNAKE_CASE__ = AutoImageProcessor.from_pretrained("""hf-internal-testing/stable-diffusion-all-variants""" ) SCREAMING_SNAKE_CASE__ = AutoImageProcessor.from_pretrained( """hf-internal-testing/stable-diffusion-all-variants""" , subfolder="""feature_extractor""" ) self.assertIsNotNone(__A ) @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): @classmethod def _snake_case ( cls :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = TOKEN HfFolder.save_token(__A ) @classmethod def _snake_case ( cls :Optional[int] ) -> Optional[Any]: """simple docstring""" try: delete_repo(token=cls._token , repo_id="""test-image-processor""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-image-processor-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-image-processor""" ) except HTTPError: pass def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained(__A ) image_processor.push_to_hub("""test-image-processor""" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(__A , getattr(__A , __A ) ) # Reset repo delete_repo(token=self._token , repo_id="""test-image-processor""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( __A , repo_id="""test-image-processor""" , push_to_hub=__A , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(__A , getattr(__A , __A ) ) def _snake_case ( self :int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained(__A ) image_processor.push_to_hub("""valid_org/test-image-processor""" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained("""valid_org/test-image-processor""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__A , getattr(__A , __A ) ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-image-processor""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( __A , repo_id="""valid_org/test-image-processor-org""" , push_to_hub=__A , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained("""valid_org/test-image-processor-org""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__A , getattr(__A , __A ) ) def _snake_case ( self :Optional[Any] ) -> int: """simple docstring""" CustomImageProcessor.register_for_auto_class() SCREAMING_SNAKE_CASE__ = CustomImageProcessor.from_pretrained(__A ) image_processor.push_to_hub("""test-dynamic-image-processor""" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {"""AutoImageProcessor""": """custom_image_processing.CustomImageProcessor"""} , ) SCREAMING_SNAKE_CASE__ = AutoImageProcessor.from_pretrained( f'''{USER}/test-dynamic-image-processor''' , trust_remote_code=__A ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , """CustomImageProcessor""" )
716
import inspect import unittest class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self :Any ) -> Any: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ = inspect.getmembers(__A , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ = """k-diffusion""" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ = """invisible-watermark""" assert backend in deps, f'''{backend} is not in the deps table!'''
59
0
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# _lowerCamelCase = [ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] _lowerCamelCase = [ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] _lowerCamelCase = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks _lowerCamelCase = F'''down_blocks.{i}.resnets.{j}.''' _lowerCamelCase = F'''input_blocks.{3*i + j + 1}.0.''' unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 _lowerCamelCase = F'''down_blocks.{i}.attentions.{j}.''' _lowerCamelCase = F'''input_blocks.{3*i + j + 1}.1.''' unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks _lowerCamelCase = F'''up_blocks.{i}.resnets.{j}.''' _lowerCamelCase = F'''output_blocks.{3*i + j}.0.''' unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 _lowerCamelCase = F'''up_blocks.{i}.attentions.{j}.''' _lowerCamelCase = F'''output_blocks.{3*i + j}.1.''' unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 _lowerCamelCase = F'''down_blocks.{i}.downsamplers.0.conv.''' _lowerCamelCase = F'''input_blocks.{3*(i+1)}.0.op.''' unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 _lowerCamelCase = F'''up_blocks.{i}.upsamplers.0.''' _lowerCamelCase = F'''output_blocks.{3*i + 2}.{1 if i == 0 else 2}.''' unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) _lowerCamelCase = 'mid_block.attentions.0.' _lowerCamelCase = 'middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): _lowerCamelCase = F'''mid_block.resnets.{j}.''' _lowerCamelCase = F'''middle_block.{2*j}.''' unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # buyer beware: this is a *brittle* function, # and correct output requires that all of these pieces interact in # the exact order in which I have arranged them. SCREAMING_SNAKE_CASE__ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: SCREAMING_SNAKE_CASE__ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: SCREAMING_SNAKE_CASE__ = v.replace(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: SCREAMING_SNAKE_CASE__ = v.replace(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = v SCREAMING_SNAKE_CASE__ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# _lowerCamelCase = [ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): _lowerCamelCase = F'''encoder.down_blocks.{i}.resnets.{j}.''' _lowerCamelCase = F'''encoder.down.{i}.block.{j}.''' vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: _lowerCamelCase = F'''down_blocks.{i}.downsamplers.0.''' _lowerCamelCase = F'''down.{i}.downsample.''' vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) _lowerCamelCase = F'''up_blocks.{i}.upsamplers.0.''' _lowerCamelCase = F'''up.{3-i}.upsample.''' vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): _lowerCamelCase = F'''decoder.up_blocks.{i}.resnets.{j}.''' _lowerCamelCase = F'''decoder.up.{3-i}.block.{j}.''' vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): _lowerCamelCase = F'''mid_block.resnets.{i}.''' _lowerCamelCase = F'''mid.block_{i+1}.''' vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) _lowerCamelCase = [ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): # convert HF linear weights to SD conv2d weights return w.reshape(*w.shape , 1 , 1 ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: SCREAMING_SNAKE_CASE__ = v.replace(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: SCREAMING_SNAKE_CASE__ = v.replace(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = v SCREAMING_SNAKE_CASE__ = {v: vae_state_dict[k] for k, v in mapping.items()} SCREAMING_SNAKE_CASE__ = ["""q""", """k""", """v""", """proj_out"""] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f'''mid.attn_1.{weight_name}.weight''' in k: print(f'''Reshaping {k} for SD format''' ) SCREAMING_SNAKE_CASE__ = reshape_weight_for_sd(UpperCamelCase__ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# _lowerCamelCase = [ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] _lowerCamelCase = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} _lowerCamelCase = re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp _lowerCamelCase = {'q': 0, 'k': 1, 'v': 2} def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for k, v in text_enc_dict.items(): if ( k.endswith(""".self_attn.q_proj.weight""" ) or k.endswith(""".self_attn.k_proj.weight""" ) or k.endswith(""".self_attn.v_proj.weight""" ) ): SCREAMING_SNAKE_CASE__ = k[: -len(""".q_proj.weight""" )] SCREAMING_SNAKE_CASE__ = k[-len("""q_proj.weight""" )] if k_pre not in capture_qkv_weight: SCREAMING_SNAKE_CASE__ = [None, None, None] SCREAMING_SNAKE_CASE__ = v continue if ( k.endswith(""".self_attn.q_proj.bias""" ) or k.endswith(""".self_attn.k_proj.bias""" ) or k.endswith(""".self_attn.v_proj.bias""" ) ): SCREAMING_SNAKE_CASE__ = k[: -len(""".q_proj.bias""" )] SCREAMING_SNAKE_CASE__ = k[-len("""q_proj.bias""" )] if k_pre not in capture_qkv_bias: SCREAMING_SNAKE_CASE__ = [None, None, None] SCREAMING_SNAKE_CASE__ = v continue SCREAMING_SNAKE_CASE__ = textenc_pattern.sub(lambda UpperCamelCase__ : protected[re.escape(m.group(0 ) )] , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("""CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing""" ) SCREAMING_SNAKE_CASE__ = textenc_pattern.sub(lambda UpperCamelCase__ : protected[re.escape(m.group(0 ) )] , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("""CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing""" ) SCREAMING_SNAKE_CASE__ = textenc_pattern.sub(lambda UpperCamelCase__ : protected[re.escape(m.group(0 ) )] , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ ) return new_state_dict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): return text_enc_dict if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) _lowerCamelCase = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors _lowerCamelCase = osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') _lowerCamelCase = osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') _lowerCamelCase = osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): _lowerCamelCase = load_file(unet_path, device='cpu') else: _lowerCamelCase = osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') _lowerCamelCase = torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): _lowerCamelCase = load_file(vae_path, device='cpu') else: _lowerCamelCase = osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') _lowerCamelCase = torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): _lowerCamelCase = load_file(text_enc_path, device='cpu') else: _lowerCamelCase = osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') _lowerCamelCase = torch.load(text_enc_path, map_location='cpu') # Convert the UNet model _lowerCamelCase = convert_unet_state_dict(unet_state_dict) _lowerCamelCase = {'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model _lowerCamelCase = convert_vae_state_dict(vae_state_dict) _lowerCamelCase = {'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper _lowerCamelCase = 'text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm _lowerCamelCase = {'transformer.' + k: v for k, v in text_enc_dict.items()} _lowerCamelCase = convert_text_enc_state_dict_vaa(text_enc_dict) _lowerCamelCase = {'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: _lowerCamelCase = convert_text_enc_state_dict(text_enc_dict) _lowerCamelCase = {'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint _lowerCamelCase = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: _lowerCamelCase = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: _lowerCamelCase = {'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
717
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 _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
59
0
'''simple docstring''' from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class UpperCamelCase_ : def _snake_case ( self :Any , __A :Tuple ) -> Optional[Any]: """simple docstring""" raise NotImplementedError() def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" raise NotImplementedError() class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Optional[int] , __A :"AutoTokenizer" , __A :bool = False , **__A :Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = tokenizer SCREAMING_SNAKE_CASE__ = skip_prompt SCREAMING_SNAKE_CASE__ = decode_kwargs # variables used in the streaming process SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = True def _snake_case ( self :Optional[Any] , __A :List[str] ) -> Union[str, Any]: """simple docstring""" if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError("""TextStreamer only supports batch size 1""" ) elif len(value.shape ) > 1: SCREAMING_SNAKE_CASE__ = value[0] if self.skip_prompt and self.next_tokens_are_prompt: SCREAMING_SNAKE_CASE__ = False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) SCREAMING_SNAKE_CASE__ = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith("""\n""" ): SCREAMING_SNAKE_CASE__ = text[self.print_len :] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 # If the last token is a CJK character, we print the characters. elif len(__A ) > 0 and self._is_chinese_char(ord(text[-1] ) ): SCREAMING_SNAKE_CASE__ = text[self.print_len :] self.print_len += len(__A ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: SCREAMING_SNAKE_CASE__ = text[self.print_len : text.rfind(""" """ ) + 1] self.print_len += len(__A ) self.on_finalized_text(__A ) def _snake_case ( self :Union[str, Any] ) -> int: """simple docstring""" if len(self.token_cache ) > 0: SCREAMING_SNAKE_CASE__ = self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) SCREAMING_SNAKE_CASE__ = text[self.print_len :] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 else: SCREAMING_SNAKE_CASE__ = """""" SCREAMING_SNAKE_CASE__ = True self.on_finalized_text(__A , stream_end=__A ) def _snake_case ( self :int , __A :str , __A :bool = False ) -> Union[str, Any]: """simple docstring""" print(__A , flush=__A , end="""""" if not stream_end else None ) def _snake_case ( self :Optional[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" if ( (cp >= 0X4E_00 and cp <= 0X9F_FF) or (cp >= 0X34_00 and cp <= 0X4D_BF) # or (cp >= 0X2_00_00 and cp <= 0X2_A6_DF) # or (cp >= 0X2_A7_00 and cp <= 0X2_B7_3F) # or (cp >= 0X2_B7_40 and cp <= 0X2_B8_1F) # or (cp >= 0X2_B8_20 and cp <= 0X2_CE_AF) # or (cp >= 0XF9_00 and cp <= 0XFA_FF) or (cp >= 0X2_F8_00 and cp <= 0X2_FA_1F) # ): # return True return False class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , __A :"AutoTokenizer" , __A :bool = False , __A :Optional[float] = None , **__A :Optional[int] ) -> List[Any]: """simple docstring""" super().__init__(__A , __A , **__A ) SCREAMING_SNAKE_CASE__ = Queue() SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = timeout def _snake_case ( self :str , __A :str , __A :bool = False ) -> str: """simple docstring""" self.text_queue.put(__A , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__( self :List[str] ) -> Tuple: """simple docstring""" return self def _snake_case ( self :Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
718
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = OpenAIGPTTokenizer lowerCamelCase_ = OpenAIGPTTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Union[str, Any] , __A :str ) -> List[Any]: """simple docstring""" return "lower newer", "lower newer" def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE__ = """lower""" SCREAMING_SNAKE_CASE__ = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] , __A :Optional[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) # Simple input SCREAMING_SNAKE_CASE__ = """This is a simple input""" SCREAMING_SNAKE_CASE__ = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE__ = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) # Pair input self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ ): pass
59
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
719
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
0
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
720
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "ChineseCLIPImageProcessor" lowerCamelCase_ = ("BertTokenizer", "BertTokenizerFast") def __init__( self :List[str] , __A :int=None , __A :Optional[Any]=None , **__A :Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __A , ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__A , __A ) SCREAMING_SNAKE_CASE__ = self.image_processor def __call__( self :List[str] , __A :Tuple=None , __A :int=None , __A :Optional[int]=None , **__A :List[Any] ) -> Tuple: """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: SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :List[Any] , *__A :Union[str, Any] , **__A :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Any , *__A :Optional[int] , **__A :str ) -> List[Any]: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __A , ) return self.image_processor_class
721
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
59
0
from __future__ import annotations import typing from collections import Counter def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(UpperCamelCase__ , max_perimeter + 1 ): SCREAMING_SNAKE_CASE__ = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 1_000 ): SCREAMING_SNAKE_CASE__ = pythagorean_triple(UpperCamelCase__ ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(F'''Perimeter {solution()} has maximum solutions''')
700
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__: float ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
59
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. 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 UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "Salesforce/blip-image-captioning-base" lowerCamelCase_ = ( "This is a tool that generates a description of an image. It takes an input named `image` which should be the " "image to caption, and returns a text that contains the description in English." ) lowerCamelCase_ = "image_captioner" lowerCamelCase_ = AutoModelForVisionaSeq lowerCamelCase_ = ["image"] lowerCamelCase_ = ["text"] def __init__( self :Tuple , *__A :str , **__A :Tuple ) -> Union[str, Any]: """simple docstring""" requires_backends(self , ["""vision"""] ) super().__init__(*__A , **__A ) def _snake_case ( self :Optional[int] , __A :"Image" ) -> List[Any]: """simple docstring""" return self.pre_processor(images=__A , return_tensors="""pt""" ) def _snake_case ( self :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" return self.model.generate(**__A ) def _snake_case ( self :Tuple , __A :List[str] ) -> Dict: """simple docstring""" return self.pre_processor.batch_decode(__A , skip_special_tokens=__A )[0].strip()
701
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} _lowerCamelCase = { 'tokenizer_file': { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json', }, } _lowerCamelCase = { 'gpt-neox-20b': 2048, } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = ["input_ids", "attention_mask"] def __init__( self :str , __A :Dict=None , __A :Tuple=None , __A :Union[str, Any]=None , __A :List[Any]="<|endoftext|>" , __A :int="<|endoftext|>" , __A :Tuple="<|endoftext|>" , __A :Optional[int]=False , **__A :int , ) -> Tuple: """simple docstring""" super().__init__( __A , __A , tokenizer_file=__A , unk_token=__A , bos_token=__A , eos_token=__A , add_prefix_space=__A , **__A , ) SCREAMING_SNAKE_CASE__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , __A ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = getattr(__A , pre_tok_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = pre_tok_class(**__A ) SCREAMING_SNAKE_CASE__ = add_prefix_space def _snake_case ( self :Dict , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._tokenizer.model.save(__A , name=__A ) return tuple(__A ) def _snake_case ( self :Optional[int] , __A :"Conversation" ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__A , add_special_tokens=__A ) + [self.eos_token_id] ) if len(__A ) > self.model_max_length: SCREAMING_SNAKE_CASE__ = input_ids[-self.model_max_length :] return input_ids
702
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCamelCase__ ) EnvironmentCommand.register_subcommand(UpperCamelCase__ ) TestCommand.register_subcommand(UpperCamelCase__ ) RunBeamCommand.register_subcommand(UpperCamelCase__ ) DummyDataCommand.register_subcommand(UpperCamelCase__ ) # Parse args SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_known_args() if not hasattr(UpperCamelCase__ , """func""" ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE__ = parse_unknown_args(UpperCamelCase__ ) # Run SCREAMING_SNAKE_CASE__ = args.func(UpperCamelCase__ , **UpperCamelCase__ ) service.run() if __name__ == "__main__": main()
59
0
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: Optional[Any] ): assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(UpperCamelCase__ , cache_dir=UpperCamelCase__ , keep_in_memory=UpperCamelCase__ ).read() _check_parquet_dataset(UpperCamelCase__ , UpperCamelCase__ ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: int , UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} SCREAMING_SNAKE_CASE__ = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE__ = ( Features({feature: Value(UpperCamelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(UpperCamelCase__ , features=UpperCamelCase__ , cache_dir=UpperCamelCase__ ).read() _check_parquet_dataset(UpperCamelCase__ , UpperCamelCase__ ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(UpperCamelCase__ , cache_dir=UpperCamelCase__ , split=UpperCamelCase__ ).read() _check_parquet_dataset(UpperCamelCase__ , UpperCamelCase__ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Tuple , UpperCamelCase__: Union[str, Any] ): if issubclass(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = parquet_path elif issubclass(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = [parquet_path] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(UpperCamelCase__ , cache_dir=UpperCamelCase__ ).read() _check_parquet_dataset(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: Dict , UpperCamelCase__: Any=("train",) ): assert isinstance(UpperCamelCase__ , UpperCamelCase__ ) for split in splits: SCREAMING_SNAKE_CASE__ = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE__ = ParquetDatasetReader( {"""train""": parquet_path} , cache_dir=UpperCamelCase__ , keep_in_memory=UpperCamelCase__ ).read() _check_parquet_datasetdict(UpperCamelCase__ , UpperCamelCase__ ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: List[str] , UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} SCREAMING_SNAKE_CASE__ = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE__ = ( Features({feature: Value(UpperCamelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) SCREAMING_SNAKE_CASE__ = ParquetDatasetReader({"""train""": parquet_path} , features=UpperCamelCase__ , cache_dir=UpperCamelCase__ ).read() _check_parquet_datasetdict(UpperCamelCase__ , UpperCamelCase__ ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: str ): if split: SCREAMING_SNAKE_CASE__ = {split: parquet_path} else: SCREAMING_SNAKE_CASE__ = """train""" SCREAMING_SNAKE_CASE__ = {"""train""": parquet_path, """test""": parquet_path} SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(UpperCamelCase__ , cache_dir=UpperCamelCase__ ).read() _check_parquet_datasetdict(UpperCamelCase__ , UpperCamelCase__ , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[int] ): SCREAMING_SNAKE_CASE__ = ParquetDatasetWriter(UpperCamelCase__ , tmp_path / """foo.parquet""" ) assert writer.write() > 0 SCREAMING_SNAKE_CASE__ = pq.ParquetFile(tmp_path / """foo.parquet""" ) SCREAMING_SNAKE_CASE__ = pf.read() assert dataset.data.table == output_table def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = str(shared_datadir / """test_image_rgb.jpg""" ) SCREAMING_SNAKE_CASE__ = {"""image""": [image_path]} SCREAMING_SNAKE_CASE__ = Features({"""image""": Image()} ) SCREAMING_SNAKE_CASE__ = Dataset.from_dict(UpperCamelCase__ , features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = ParquetDatasetWriter(UpperCamelCase__ , tmp_path / """foo.parquet""" ) assert writer.write() > 0 SCREAMING_SNAKE_CASE__ = Dataset.from_parquet(str(tmp_path / """foo.parquet""" ) ) assert dataset.features == reloaded_dataset.features SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(str(tmp_path / """foo.parquet""" ) , streaming=UpperCamelCase__ ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( """feature, expected""" , [ (Features({"""foo""": Value("""int32""" )} ), None), (Features({"""image""": Image(), """foo""": Value("""int32""" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"""nested""": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Any ): assert get_writer_batch_size(UpperCamelCase__ ) == expected
703
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , *__A :Tuple , **__A :Dict ) -> None: """simple docstring""" warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __A , ) super().__init__(*__A , **__A )
59
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
704
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
59
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase = {'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
705
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__ )}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
0
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [] for data in source_data: for i, el in enumerate(UpperCamelCase__ ): if len(UpperCamelCase__ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(UpperCamelCase__ ) ) return data_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = [] for dlist, weight in zip(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: SCREAMING_SNAKE_CASE__ = f'''Invalid weight of {weight:f} provided''' raise ValueError(UpperCamelCase__ ) score_lists.append(UpperCamelCase__ ) return score_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = get_data(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = calculate_each_score(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = generate_final_scores(UpperCamelCase__ ) # append scores to source data for i, ele in enumerate(UpperCamelCase__ ): source_data[i].append(UpperCamelCase__ ) return source_data
706
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
59
0
import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 _lowerCamelCase = sys.version_info >= (3, 10) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any=None , UpperCamelCase__: Tuple=None ): return field(default_factory=lambda: default , metadata=UpperCamelCase__ ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = field(default="toto" , metadata={"help": "help message"} ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = None class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "titi" lowerCamelCase_ = "toto" class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "titi" lowerCamelCase_ = "toto" lowerCamelCase_ = 42 @dataclass class UpperCamelCase_ : lowerCamelCase_ = "toto" def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = BasicEnum(self.foo ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = "toto" def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = MixedTypeEnum(self.foo ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = None lowerCamelCase_ = field(default=UpperCamelCase__ , metadata={"help": "help message"} ) lowerCamelCase_ = None lowerCamelCase_ = list_field(default=[] ) lowerCamelCase_ = list_field(default=[] ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = list_field(default=[] ) lowerCamelCase_ = list_field(default=[1, 2, 3] ) lowerCamelCase_ = list_field(default=["Hallo", "Bonjour", "Hello"] ) lowerCamelCase_ = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = field() lowerCamelCase_ = field() lowerCamelCase_ = field() def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = BasicEnum(self.required_enum ) @dataclass class UpperCamelCase_ : lowerCamelCase_ = 42 lowerCamelCase_ = field() lowerCamelCase_ = None lowerCamelCase_ = field(default="toto" , metadata={"help": "help message"} ) lowerCamelCase_ = list_field(default=["Hallo", "Bonjour", "Hello"] ) if is_python_no_less_than_3_10: @dataclass class UpperCamelCase_ : lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = None @dataclass class UpperCamelCase_ : lowerCamelCase_ = None lowerCamelCase_ = field(default=UpperCamelCase__ , metadata={"help": "help message"} ) lowerCamelCase_ = None lowerCamelCase_ = list_field(default=[] ) lowerCamelCase_ = list_field(default=[] ) class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str , __A :argparse.ArgumentParser , __A :argparse.ArgumentParser ) -> List[str]: """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): SCREAMING_SNAKE_CASE__ = {k: v for k, v in vars(__A ).items() if k != """container"""} SCREAMING_SNAKE_CASE__ = {k: v for k, v in vars(__A ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , __A ) and yy.get("""choices""" , __A ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](__A ) , yy["""type"""](__A ) ) del xx["type"], yy["type"] self.assertEqual(__A , __A ) def _snake_case ( self :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=__A , required=__A ) expected.add_argument("""--bar""" , type=__A , required=__A ) expected.add_argument("""--baz""" , type=__A , required=__A ) expected.add_argument("""--flag""" , type=__A , default=__A , const=__A , nargs="""?""" ) self.argparsersEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((SCREAMING_SNAKE_CASE__ ) , ) = parser.parse_args_into_dataclasses(__A , look_for_args_file=__A ) self.assertFalse(example.flag ) def _snake_case ( self :Tuple ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=__A ) expected.add_argument("""--baz""" , default="""toto""" , type=__A , help="""help message""" ) self.argparsersEqual(__A , __A ) def _snake_case ( self :List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=__A , default=__A , const=__A , nargs="""?""" ) expected.add_argument("""--baz""" , type=__A , default=__A , const=__A , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=__A , dest="""baz""" ) expected.add_argument("""--opt""" , type=__A , default=__A ) SCREAMING_SNAKE_CASE__ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(__A ) for dataclass_type in dataclass_types: SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) self.argparsersEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = parser.parse_args([] ) self.assertEqual(__A , Namespace(foo=__A , baz=__A , opt=__A ) ) SCREAMING_SNAKE_CASE__ = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(__A , Namespace(foo=__A , baz=__A , opt=__A ) ) SCREAMING_SNAKE_CASE__ = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(__A , Namespace(foo=__A , baz=__A , opt=__A ) ) SCREAMING_SNAKE_CASE__ = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(__A , Namespace(foo=__A , baz=__A , opt=__A ) ) SCREAMING_SNAKE_CASE__ = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(__A , Namespace(foo=__A , baz=__A , opt=__A ) ) def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) SCREAMING_SNAKE_CASE__ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) SCREAMING_SNAKE_CASE__ = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) SCREAMING_SNAKE_CASE__ = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) SCREAMING_SNAKE_CASE__ = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) SCREAMING_SNAKE_CASE__ = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def _snake_case ( self :int ) -> Any: """simple docstring""" @dataclass class UpperCamelCase_ : lowerCamelCase_ = "toto" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) SCREAMING_SNAKE_CASE__ = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) SCREAMING_SNAKE_CASE__ = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) def _snake_case ( self :Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=__A ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=__A ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=__A ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=__A ) self.argparsersEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = parser.parse_args([] ) self.assertEqual( __A , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) SCREAMING_SNAKE_CASE__ = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(__A , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=__A , type=__A ) expected.add_argument("""--bar""" , default=__A , type=__A , help="""help message""" ) expected.add_argument("""--baz""" , default=__A , type=__A ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=__A ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=__A ) SCREAMING_SNAKE_CASE__ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(__A ) for dataclass_type in dataclass_types: SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) self.argparsersEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = parser.parse_args([] ) self.assertEqual(__A , Namespace(foo=__A , bar=__A , baz=__A , ces=[] , des=[] ) ) SCREAMING_SNAKE_CASE__ = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(__A , Namespace(foo=12 , bar=3.1_4 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def _snake_case ( self :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=__A , required=__A ) expected.add_argument("""--required_str""" , type=__A , required=__A ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=__A , ) self.argparsersEqual(__A , __A ) def _snake_case ( self :Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=__A , required=__A ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=__A , ) expected.add_argument("""--opt""" , type=__A , default=__A ) expected.add_argument("""--baz""" , default="""toto""" , type=__A , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=__A ) self.argparsersEqual(__A , __A ) def _snake_case ( self :int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = { """foo""": 12, """bar""": 3.1_4, """baz""": """42""", """flag""": True, } SCREAMING_SNAKE_CASE__ = parser.parse_dict(__A )[0] SCREAMING_SNAKE_CASE__ = BasicExample(**__A ) self.assertEqual(__A , __A ) def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = { """foo""": 12, """bar""": 3.1_4, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(__A , parser.parse_dict , __A , allow_extra_keys=__A ) def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = { """foo""": 12, """bar""": 3.1_4, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ = os.path.join(__A , """temp_json""" ) os.mkdir(__A ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(__A , __A ) SCREAMING_SNAKE_CASE__ = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] SCREAMING_SNAKE_CASE__ = BasicExample(**__A ) self.assertEqual(__A , __A ) def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) SCREAMING_SNAKE_CASE__ = { """foo""": 12, """bar""": 3.1_4, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ = os.path.join(__A , """temp_yaml""" ) os.mkdir(__A ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(__A , __A ) SCREAMING_SNAKE_CASE__ = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] SCREAMING_SNAKE_CASE__ = BasicExample(**__A ) self.assertEqual(__A , __A ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = HfArgumentParser(__A ) self.assertIsNotNone(__A )
707
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
59
0
'''simple docstring''' import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__ )}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
708
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , default=512 , help="""Maximum sequence length. For training on TPUs, it helps to have a maximum""" """ sequence length that is a multiple of 8.""" , ) parser.add_argument( """--output_dir""" , default="""tf-tpu""" , type=UpperCamelCase__ , help="""Output directory where the TFRecord shards will be saved. If the""" """ path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord""" """ shards will be directly saved to a Google Cloud Storage bucket.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """input_ids""": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["""input_ids"""][i] ) ), """attention_mask""": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["""attention_mask"""][i] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , num_proc=4 , remove_columns=["""text"""] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) shard_count += 1 total_records += records_containing with open(f'''split-{args.split}-records-count.txt''' , """w""" ) as f: print(f'''Total {args.split} records: {total_records}''' , file=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
59
0
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
709
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [] for data in source_data: for i, el in enumerate(UpperCamelCase__ ): if len(UpperCamelCase__ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(UpperCamelCase__ ) ) return data_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = [] for dlist, weight in zip(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: SCREAMING_SNAKE_CASE__ = f'''Invalid weight of {weight:f} provided''' raise ValueError(UpperCamelCase__ ) score_lists.append(UpperCamelCase__ ) return score_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = get_data(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = calculate_each_score(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = generate_final_scores(UpperCamelCase__ ) # append scores to source data for i, ele in enumerate(UpperCamelCase__ ): source_data[i].append(UpperCamelCase__ ) return source_data
59
0
import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTokenizerFast from utils import get_device, get_timestamp, show_pil class UpperCamelCase_ : def __init__( self :List[Any] , __A :str = "cpu" , __A :str = "openai/clip-vit-large-patch14" ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = device SCREAMING_SNAKE_CASE__ = CLIPTokenizerFast.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] SCREAMING_SNAKE_CASE__ = [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] SCREAMING_SNAKE_CASE__ = torchvision.transforms.Normalize(self.image_mean , self.image_std ) SCREAMING_SNAKE_CASE__ = torchvision.transforms.Resize(224 ) SCREAMING_SNAKE_CASE__ = torchvision.transforms.CenterCrop(224 ) def _snake_case ( self :Any , __A :List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.resize(__A ) SCREAMING_SNAKE_CASE__ = self.center_crop(__A ) SCREAMING_SNAKE_CASE__ = self.normalize(__A ) return images def __call__( self :Optional[Any] , __A :Dict=None , __A :Optional[Any]=None , **__A :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer(text=__A , **__A ) SCREAMING_SNAKE_CASE__ = self.preprocess_img(__A ) SCREAMING_SNAKE_CASE__ = {key: value.to(self.device ) for (key, value) in encoding.items()} return encoding class UpperCamelCase_ ( nn.Module ): def __init__( self :int , __A :Union[str, Any]=10 , __A :Tuple=0.0_1 , __A :List[str]=None , __A :int=None , __A :Optional[int]=None , __A :List[Any]=None , __A :Optional[Any]=None , __A :Any=None , __A :List[str]=False , __A :Optional[int]=True , __A :Dict="image" , __A :int=True , __A :Optional[Any]=False , __A :Dict=False , __A :str=False , ) -> None: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = device if device else get_device() if vqgan: SCREAMING_SNAKE_CASE__ = vqgan else: SCREAMING_SNAKE_CASE__ = load_vqgan(self.device , conf_path=__A , ckpt_path=__A ) self.vqgan.eval() if clip: SCREAMING_SNAKE_CASE__ = clip else: SCREAMING_SNAKE_CASE__ = CLIPModel.from_pretrained("""openai/clip-vit-base-patch32""" ) self.clip.to(self.device ) SCREAMING_SNAKE_CASE__ = ProcessorGradientFlow(device=self.device ) SCREAMING_SNAKE_CASE__ = iterations SCREAMING_SNAKE_CASE__ = lr SCREAMING_SNAKE_CASE__ = log SCREAMING_SNAKE_CASE__ = make_grid SCREAMING_SNAKE_CASE__ = return_val SCREAMING_SNAKE_CASE__ = quantize SCREAMING_SNAKE_CASE__ = self.vqgan.decoder.z_shape def _snake_case ( self :Tuple , __A :str=None , __A :int=None , __A :Union[str, Any]=5 , __A :List[str]=True ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [] if output_path is None: SCREAMING_SNAKE_CASE__ = """./animation.gif""" if input_path is None: SCREAMING_SNAKE_CASE__ = self.save_path SCREAMING_SNAKE_CASE__ = sorted(glob(input_path + """/*""" ) ) if not len(__A ): raise ValueError( """No images found in save path, aborting (did you pass save_intermediate=True to the generate""" """ function?)""" ) if len(__A ) == 1: print("""Only one image found in save path, (did you pass save_intermediate=True to the generate function?)""" ) SCREAMING_SNAKE_CASE__ = total_duration / len(__A ) SCREAMING_SNAKE_CASE__ = [frame_duration] * len(__A ) if extend_frames: SCREAMING_SNAKE_CASE__ = 1.5 SCREAMING_SNAKE_CASE__ = 3 for file_name in paths: if file_name.endswith(""".png""" ): images.append(imageio.imread(__A ) ) imageio.mimsave(__A , __A , duration=__A ) print(f'''gif saved to {output_path}''' ) def _snake_case ( self :Dict , __A :int=None , __A :Optional[Any]=None ) -> str: """simple docstring""" if not (path or img): raise ValueError("""Input either path or tensor""" ) if img is not None: raise NotImplementedError SCREAMING_SNAKE_CASE__ = preprocess(Image.open(__A ) , target_image_size=256 ).to(self.device ) SCREAMING_SNAKE_CASE__ = preprocess_vqgan(__A ) SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ = self.vqgan.encode(__A ) return z def _snake_case ( self :Any , __A :List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.latent.detach().requires_grad_() SCREAMING_SNAKE_CASE__ = base_latent + transform_vector if self.quantize: SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ = self.vqgan.quantize(__A ) else: SCREAMING_SNAKE_CASE__ = trans_latent return self.vqgan.decode(__A ) def _snake_case ( self :Any , __A :Optional[Any] , __A :Tuple , __A :Optional[Any]=None ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.clip_preprocessor(text=__A , images=__A , return_tensors="""pt""" , padding=__A ) SCREAMING_SNAKE_CASE__ = self.clip(**__A ) SCREAMING_SNAKE_CASE__ = clip_outputs.logits_per_image if weights is not None: SCREAMING_SNAKE_CASE__ = similarity_logits * weights return similarity_logits.sum() def _snake_case ( self :Dict , __A :Optional[Any] , __A :Dict , __A :List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._get_clip_similarity(pos_prompts["""prompts"""] , __A , weights=(1 / pos_prompts["""weights"""]) ) if neg_prompts: SCREAMING_SNAKE_CASE__ = self._get_clip_similarity(neg_prompts["""prompts"""] , __A , weights=neg_prompts["""weights"""] ) else: SCREAMING_SNAKE_CASE__ = torch.tensor([1] , device=self.device ) SCREAMING_SNAKE_CASE__ = -torch.log(__A ) + torch.log(__A ) return loss def _snake_case ( self :Dict , __A :str , __A :int , __A :List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch.randn_like(self.latent , requires_grad=__A , device=self.device ) SCREAMING_SNAKE_CASE__ = torch.optim.Adam([vector] , lr=self.lr ) for i in range(self.iterations ): optim.zero_grad() SCREAMING_SNAKE_CASE__ = self._add_vector(__A ) SCREAMING_SNAKE_CASE__ = loop_post_process(__A ) SCREAMING_SNAKE_CASE__ = self._get_CLIP_loss(__A , __A , __A ) print("""CLIP loss""" , __A ) if self.log: wandb.log({"""CLIP Loss""": clip_loss} ) clip_loss.backward(retain_graph=__A ) optim.step() if self.return_val == "image": yield custom_to_pil(transformed_img[0] ) else: yield vector def _snake_case ( self :List[str] , __A :List[Any] , __A :Optional[Any] , __A :Any ) -> Union[str, Any]: """simple docstring""" wandb.init(reinit=__A , project="""face-editor""" ) wandb.config.update({"""Positive Prompts""": positive_prompts} ) wandb.config.update({"""Negative Prompts""": negative_prompts} ) wandb.config.update({"""lr""": self.lr, """iterations""": self.iterations} ) if image_path: SCREAMING_SNAKE_CASE__ = Image.open(__A ) SCREAMING_SNAKE_CASE__ = image.resize((256, 256) ) wandb.log("""Original Image""" , wandb.Image(__A ) ) def _snake_case ( self :Union[str, Any] , __A :Optional[Any] ) -> Optional[int]: """simple docstring""" if not prompts: return [] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] if isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = [prompt.strip() for prompt in prompts.split("""|""" )] for prompt in prompts: if isinstance(__A , (tuple, list) ): SCREAMING_SNAKE_CASE__ = prompt[0] SCREAMING_SNAKE_CASE__ = float(prompt[1] ) elif ":" in prompt: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = prompt.split(""":""" ) SCREAMING_SNAKE_CASE__ = float(__A ) else: SCREAMING_SNAKE_CASE__ = prompt SCREAMING_SNAKE_CASE__ = 1.0 processed_prompts.append(__A ) weights.append(__A ) return { "prompts": processed_prompts, "weights": torch.tensor(__A , device=self.device ), } def _snake_case ( self :List[str] , __A :str , __A :Any=None , __A :List[Any]=None , __A :Any=True , __A :str=False , __A :int=True , __A :Tuple=True , __A :Union[str, Any]=None , ) -> Tuple: """simple docstring""" if image_path: SCREAMING_SNAKE_CASE__ = self._get_latent(__A ) else: SCREAMING_SNAKE_CASE__ = torch.randn(self.latent_dim , device=self.device ) if self.log: self._init_logging(__A , __A , __A ) assert pos_prompts, "You must provide at least one positive prompt." SCREAMING_SNAKE_CASE__ = self.process_prompts(__A ) SCREAMING_SNAKE_CASE__ = self.process_prompts(__A ) if save_final and save_path is None: SCREAMING_SNAKE_CASE__ = os.path.join("""./outputs/""" , """_""".join(pos_prompts["""prompts"""] ) ) if not os.path.exists(__A ): os.makedirs(__A ) else: SCREAMING_SNAKE_CASE__ = save_path + """_""" + get_timestamp() os.makedirs(__A ) SCREAMING_SNAKE_CASE__ = save_path SCREAMING_SNAKE_CASE__ = self.vqgan.decode(self.latent )[0] if show_intermediate: print("""Original Image""" ) show_pil(custom_to_pil(__A ) ) SCREAMING_SNAKE_CASE__ = loop_post_process(__A ) for iter, transformed_img in enumerate(self._optimize_CLIP(__A , __A , __A ) ): if show_intermediate: show_pil(__A ) if save_intermediate: transformed_img.save(os.path.join(self.save_path , f'''iter_{iter:03d}.png''' ) ) if self.log: wandb.log({"""Image""": wandb.Image(__A )} ) if show_final: show_pil(__A ) if save_final: transformed_img.save(os.path.join(self.save_path , f'''iter_{iter:03d}_final.png''' ) )
710
import warnings from functools import wraps from typing import Callable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Callable ): @wraps(UpperCamelCase__ ) def _inner_fn(*UpperCamelCase__: Dict , **UpperCamelCase__: Any ): warnings.warn( (f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , UpperCamelCase__ , ) return fn(*UpperCamelCase__ , **UpperCamelCase__ ) return _inner_fn
59
0
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING _lowerCamelCase = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , **__A :Optional[Any] ) -> int: """simple docstring""" super().__init__(**__A ) requires_backends(self , """vision""" ) requires_backends(self , """torch""" ) if self.framework != "pt": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' ) self.check_model_type(__A ) def _snake_case ( self :str , **__A :Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} # preprocess args if "points_per_batch" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""points_per_batch"""] if "points_per_crop" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""points_per_crop"""] if "crops_n_layers" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""crops_n_layers"""] if "crop_overlap_ratio" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""crop_overlap_ratio"""] if "crop_n_points_downscale_factor" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""crop_n_points_downscale_factor"""] # postprocess args if "pred_iou_thresh" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""pred_iou_thresh"""] if "stability_score_offset" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""stability_score_offset"""] if "mask_threshold" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""mask_threshold"""] if "stability_score_thresh" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""stability_score_thresh"""] if "crops_nms_thresh" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""crops_nms_thresh"""] if "output_rle_mask" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""output_rle_mask"""] if "output_bboxes_mask" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""output_bboxes_mask"""] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self :List[Any] , __A :List[str] , *__A :Tuple , __A :Optional[int]=None , __A :str=None , **__A :Union[str, Any] ) -> List[Any]: """simple docstring""" return super().__call__(__A , *__A , num_workers=__A , batch_size=__A , **__A ) def _snake_case ( self :Any , __A :int , __A :Optional[int]=64 , __A :int = 0 , __A :float = 512 / 1500 , __A :Optional[int] = 32 , __A :Optional[int] = 1 , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = load_image(__A ) SCREAMING_SNAKE_CASE__ = self.image_processor.size["""longest_edge"""] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processor.generate_crop_boxes( __A , __A , __A , __A , __A , __A ) SCREAMING_SNAKE_CASE__ = self.image_processor(images=__A , return_tensors="""pt""" ) with self.device_placement(): if self.framework == "pt": SCREAMING_SNAKE_CASE__ = self.get_inference_context() with inference_context(): SCREAMING_SNAKE_CASE__ = self._ensure_tensor_on_device(__A , device=self.device ) SCREAMING_SNAKE_CASE__ = self.model.get_image_embeddings(model_inputs.pop("""pixel_values""" ) ) SCREAMING_SNAKE_CASE__ = image_embeddings SCREAMING_SNAKE_CASE__ = grid_points.shape[1] SCREAMING_SNAKE_CASE__ = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( """Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. """ """To return all points at once, set points_per_batch to None""" ) for i in range(0 , __A , __A ): SCREAMING_SNAKE_CASE__ = grid_points[:, i : i + points_per_batch, :, :] SCREAMING_SNAKE_CASE__ = input_labels[:, i : i + points_per_batch] SCREAMING_SNAKE_CASE__ = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def _snake_case ( self :Optional[Any] , __A :str , __A :List[Any]=0.8_8 , __A :Tuple=0.9_5 , __A :Optional[Any]=0 , __A :List[Any]=1 , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = model_inputs.pop("""input_boxes""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""is_last""" ) SCREAMING_SNAKE_CASE__ = model_inputs.pop("""original_sizes""" ).tolist() SCREAMING_SNAKE_CASE__ = model_inputs.pop("""reshaped_input_sizes""" ).tolist() SCREAMING_SNAKE_CASE__ = self.model(**__A ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks SCREAMING_SNAKE_CASE__ = model_outputs["""pred_masks"""] SCREAMING_SNAKE_CASE__ = self.image_processor.post_process_masks( __A , __A , __A , __A , binarize=__A ) SCREAMING_SNAKE_CASE__ = model_outputs["""iou_scores"""] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __A , __A , __A , __A , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def _snake_case ( self :Union[str, Any] , __A :Union[str, Any] , __A :Any=False , __A :Any=False , __A :str=0.7 , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] for model_output in model_outputs: all_scores.append(model_output.pop("""iou_scores""" ) ) all_masks.extend(model_output.pop("""masks""" ) ) all_boxes.append(model_output.pop("""boxes""" ) ) SCREAMING_SNAKE_CASE__ = torch.cat(__A ) SCREAMING_SNAKE_CASE__ = torch.cat(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processor.post_process_for_mask_generation( __A , __A , __A , __A ) SCREAMING_SNAKE_CASE__ = defaultdict(__A ) for output in model_outputs: for k, v in output.items(): extra[k].append(__A ) SCREAMING_SNAKE_CASE__ = {} if output_rle_mask: SCREAMING_SNAKE_CASE__ = rle_mask if output_bboxes_mask: SCREAMING_SNAKE_CASE__ = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
711
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RoCBertTokenizer lowerCamelCase_ = None lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = filter_non_english def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(__A , __A , ensure_ascii=__A ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(__A , __A , ensure_ascii=__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(__A , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__A ) , [5, 6, 2, 5, 7, 8] ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=__A , 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 _snake_case ( self :Any ) -> str: """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 _snake_case ( self :int ) -> str: """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 _snake_case ( self :List[str] ) -> List[str]: """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 _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def _snake_case ( self :int ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(__A , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE__ = ( [ ((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 _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你好""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你是谁""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( __A , __A , __A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(__A , add_special_tokens=__A ) self.assertEqual(__A , __A )
59
0
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
712
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = original_name.split(""".""" )[0] SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 2] ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 1] ) SCREAMING_SNAKE_CASE__ = orig_block_num - offset SCREAMING_SNAKE_CASE__ = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = OrderedDict() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): SCREAMING_SNAKE_CASE__ = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 SCREAMING_SNAKE_CASE__ = key[: key.find("""proj""" )] SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , f'''patch_embeddings.{total_embed_found}.''' ) SCREAMING_SNAKE_CASE__ = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: SCREAMING_SNAKE_CASE__ = """poolformer.encoder.""" + key if "mlp.fc1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm1""" , """before_norm""" ) if "norm2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: SCREAMING_SNAKE_CASE__ = key.replace("""head""" , """classifier""" ) SCREAMING_SNAKE_CASE__ = value return new_state_dict def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = PoolFormerConfig() # set attributes based on model_name SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = model_name[-3:] SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = (1, 1_000) # set config attributes SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if size == "s12": SCREAMING_SNAKE_CASE__ = [2, 2, 6, 2] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s24": SCREAMING_SNAKE_CASE__ = [4, 4, 12, 4] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "m36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 elif size == "m48": SCREAMING_SNAKE_CASE__ = [8, 8, 24, 8] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) # Prepare image SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location=torch.device("""cpu""" ) ) # rename keys SCREAMING_SNAKE_CASE__ = rename_keys(UpperCamelCase__ ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ = PoolFormerForImageClassification(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Define image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.logits # define expected logit slices for different models if size == "s12": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": SCREAMING_SNAKE_CASE__ = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": SCREAMING_SNAKE_CASE__ = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": SCREAMING_SNAKE_CASE__ = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , UpperCamelCase__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor _lowerCamelCase = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] SCREAMING_SNAKE_CASE__ = [trans(img.convert("""RGB""" ) ) for img in image] SCREAMING_SNAKE_CASE__ = torch.stack(UpperCamelCase__ ) return image class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Dict , __A :int , __A :List[str] ) -> Union[str, Any]: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM SCREAMING_SNAKE_CASE__ = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=__A , scheduler=__A ) def _snake_case ( self :str , __A :Optional[Any] ) -> Any: """simple docstring""" if strength < 0 or strength > 1: raise ValueError(f'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def _snake_case ( self :Union[str, Any] , __A :List[Any] , __A :Any , __A :Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = min(int(num_inference_steps * strength ) , __A ) SCREAMING_SNAKE_CASE__ = max(num_inference_steps - init_timestep , 0 ) SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def _snake_case ( self :List[str] , __A :Optional[int] , __A :Any , __A :List[Any] , __A :Any , __A :Dict , __A :Union[str, Any]=None ) -> Any: """simple docstring""" if not isinstance(__A , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(__A )}''' ) SCREAMING_SNAKE_CASE__ = image.to(device=__A , dtype=__A ) if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = init_latents.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=__A , dtype=__A ) # get latents print("""add noise to latents at timestep""" , __A ) SCREAMING_SNAKE_CASE__ = self.scheduler.add_noise(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = init_latents return latents @torch.no_grad() def __call__( self :Any , __A :Union[torch.FloatTensor, PIL.Image.Image] = None , __A :float = 0.8 , __A :int = 1 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :float = 0.0 , __A :int = 50 , __A :Optional[bool] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" self.check_inputs(__A ) # 2. Preprocess image SCREAMING_SNAKE_CASE__ = preprocess(__A ) # 3. set timesteps self.scheduler.set_timesteps(__A , device=self.device ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.get_timesteps(__A , __A , self.device ) SCREAMING_SNAKE_CASE__ = timesteps[:1].repeat(__A ) # 4. Prepare latent variables SCREAMING_SNAKE_CASE__ = self.prepare_latents(__A , __A , __A , self.unet.dtype , self.device , __A ) SCREAMING_SNAKE_CASE__ = latents # 5. Denoising loop for t in self.progress_bar(__A ): # 1. predict noise model_output SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step( __A , __A , __A , eta=__A , use_clipped_model_output=__A , generator=__A , ).prev_sample SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=__A )
713
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_text_model" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :Union[str, Any] , __A :Any=5_0244 , __A :Optional[Any]=768 , __A :Tuple=64 , __A :List[str]=2048 , __A :int=12 , __A :str=12 , __A :Any=32 , __A :Tuple=128 , __A :int=0.1 , __A :str=1E-6 , __A :Optional[Any]=1.0 , __A :Union[str, Any]="gelu_new" , __A :Any=0 , __A :List[str]=False , __A :Optional[Any]=0 , __A :int=1 , __A :Optional[int]=False , __A :Optional[Any]=True , **__A :List[Any] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = d_kv SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = num_layers SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = decoder_start_token_id # for backwards compatibility SCREAMING_SNAKE_CASE__ = dense_act_fn super().__init__( pad_token_id=__A , eos_token_id=__A , decoder_start_token_id=__A , tie_word_embeddings=__A , is_decoder=__A , **__A , ) @classmethod def _snake_case ( cls :Optional[int] , __A :Union[str, os.PathLike] , **__A :Optional[int] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = 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(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_vision_model" def __init__( self :Optional[int] , __A :int=768 , __A :Optional[Any]=768 , __A :Union[str, Any]=2048 , __A :int=64 , __A :Union[str, Any]=12 , __A :str=12 , __A :Any="gelu_new" , __A :List[Any]=1E-6 , __A :Dict=0.0 , __A :int=0.0 , __A :int=1E-10 , __A :Dict=1.0 , __A :int=4096 , __A :int=32 , __A :int=128 , **__A :Tuple , ) -> str: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = patch_embed_hidden_size SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = dense_act_fn SCREAMING_SNAKE_CASE__ = seq_len SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = d_kv @classmethod def _snake_case ( cls :str , __A :Union[str, os.PathLike] , **__A :str ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = 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(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct" lowerCamelCase_ = True def __init__( self :str , __A :Optional[Any]=None , __A :List[str]=None , __A :Optional[Any]=1.0 , __A :Optional[Any]=0.0_2 , __A :Any=False , __A :Tuple=False , __A :Any=True , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__(tie_word_embeddings=__A , is_encoder_decoder=__A , **__A ) if text_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE__ = PixaStructTextConfig(**__A ) SCREAMING_SNAKE_CASE__ = PixaStructVisionConfig(**__A ) SCREAMING_SNAKE_CASE__ = self.text_config.decoder_start_token_id SCREAMING_SNAKE_CASE__ = self.text_config.pad_token_id SCREAMING_SNAKE_CASE__ = self.text_config.eos_token_id SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = is_vqa @classmethod def _snake_case ( cls :Union[str, Any] , __A :PixaStructTextConfig , __A :PixaStructVisionConfig , **__A :Optional[int] ) -> Optional[Any]: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__A ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
714
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[int] ) -> str: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__A , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = Accelerator() _lowerCamelCase = (accelerator.state.process_index + 2, 10) _lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device) _lowerCamelCase = '' _lowerCamelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." _lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." _lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _lowerCamelCase = {'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTConfig', 'DeiTOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['DeiTFeatureExtractor'] _lowerCamelCase = ['DeiTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DeiTForImageClassification', 'DeiTForImageClassificationWithTeacher', 'DeiTForMaskedImageModeling', 'DeiTModel', 'DeiTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDeiTForImageClassification', 'TFDeiTForImageClassificationWithTeacher', 'TFDeiTForMaskedImageModeling', 'TFDeiTModel', 'TFDeiTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCamelCase = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3FeatureExtractor'] _lowerCamelCase = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
0
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
716
import inspect import unittest class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self :Any ) -> Any: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ = inspect.getmembers(__A , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ = """k-diffusion""" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ = """invisible-watermark""" assert backend in deps, f'''{backend} is not in the deps table!'''
59
0
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: ndarray ): return np.dot(UpperCamelCase__ , UpperCamelCase__ ) class UpperCamelCase_ : def __init__( self :str , *, __A :float = np.inf , __A :str = "linear" , __A :float = 0.0 , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = regularization SCREAMING_SNAKE_CASE__ = gamma if kernel == "linear": SCREAMING_SNAKE_CASE__ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("""rbf kernel requires gamma""" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("""gamma must be float or int""" ) if not self.gamma > 0: raise ValueError("""gamma must be > 0""" ) SCREAMING_SNAKE_CASE__ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: SCREAMING_SNAKE_CASE__ = f'''Unknown kernel: {kernel}''' raise ValueError(__A ) def _snake_case ( self :Dict , __A :ndarray , __A :ndarray ) -> float: """simple docstring""" return np.dot(__A , __A ) def _snake_case ( self :List[Any] , __A :ndarray , __A :ndarray ) -> float: """simple docstring""" return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _snake_case ( self :Tuple , __A :list[ndarray] , __A :ndarray ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = observations SCREAMING_SNAKE_CASE__ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((SCREAMING_SNAKE_CASE__ ) , ) = np.shape(__A ) def to_minimize(__A :ndarray ) -> float: SCREAMING_SNAKE_CASE__ = 0 ((SCREAMING_SNAKE_CASE__ ) , ) = np.shape(__A ) for i in range(__A ): for j in range(__A ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__A ) SCREAMING_SNAKE_CASE__ = LinearConstraint(__A , 0 , 0 ) SCREAMING_SNAKE_CASE__ = Bounds(0 , self.regularization ) SCREAMING_SNAKE_CASE__ = minimize( __A , np.ones(__A ) , bounds=__A , constraints=[ly_contraint] ).x SCREAMING_SNAKE_CASE__ = l_star # calculating mean offset of separation plane to points SCREAMING_SNAKE_CASE__ = 0 for i in range(__A ): for j in range(__A ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) SCREAMING_SNAKE_CASE__ = s / n def _snake_case ( self :Optional[int] , __A :ndarray ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __A ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
717
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 _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
59
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = { 'configuration_gpt_neo': ['GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoConfig', 'GPTNeoOnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoForCausalLM', 'GPTNeoForQuestionAnswering', 'GPTNeoForSequenceClassification', 'GPTNeoForTokenClassification', 'GPTNeoModel', 'GPTNeoPreTrainedModel', 'load_tf_weights_in_gpt_neo', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'FlaxGPTNeoForCausalLM', 'FlaxGPTNeoModel', 'FlaxGPTNeoPreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
718
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = OpenAIGPTTokenizer lowerCamelCase_ = OpenAIGPTTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Union[str, Any] , __A :str ) -> List[Any]: """simple docstring""" return "lower newer", "lower newer" def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE__ = """lower""" SCREAMING_SNAKE_CASE__ = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] , __A :Optional[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) # Simple input SCREAMING_SNAKE_CASE__ = """This is a simple input""" SCREAMING_SNAKE_CASE__ = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE__ = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) # Pair input self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ ): pass
59
0
import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'nvidia/segformer-b0-finetuned-ade-512-512': ( 'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json' ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "segformer" def __init__( self :Optional[int] , __A :List[Any]=3 , __A :Optional[Any]=4 , __A :int=[2, 2, 2, 2] , __A :Union[str, Any]=[8, 4, 2, 1] , __A :Optional[int]=[32, 64, 160, 256] , __A :int=[7, 3, 3, 3] , __A :Tuple=[4, 2, 2, 2] , __A :str=[1, 2, 5, 8] , __A :Union[str, Any]=[4, 4, 4, 4] , __A :Any="gelu" , __A :List[str]=0.0 , __A :List[Any]=0.0 , __A :Any=0.1 , __A :Optional[int]=0.0_2 , __A :List[Any]=0.1 , __A :int=1E-6 , __A :int=256 , __A :Dict=255 , **__A :Any , ) -> List[Any]: """simple docstring""" super().__init__(**__A ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be""" """ removed, as the behaviour will default to that of reshape_last_stage = True.""" , __A , ) SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = num_encoder_blocks SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = sr_ratios SCREAMING_SNAKE_CASE__ = hidden_sizes SCREAMING_SNAKE_CASE__ = patch_sizes SCREAMING_SNAKE_CASE__ = strides SCREAMING_SNAKE_CASE__ = mlp_ratios SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = classifier_dropout_prob SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = decoder_hidden_size SCREAMING_SNAKE_CASE__ = kwargs.get("""reshape_last_stage""" , __A ) SCREAMING_SNAKE_CASE__ = semantic_loss_ignore_index class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = version.parse("1.11" ) @property def _snake_case ( self :Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _snake_case ( self :Optional[Any] ) -> float: """simple docstring""" return 1E-4 @property def _snake_case ( self :str ) -> int: """simple docstring""" return 12
719
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = '▁' _lowerCamelCase = {'vocab_file': 'sentencepiece.bpe.model'} _lowerCamelCase = { 'vocab_file': { 'facebook/mbart-large-en-ro': ( 'https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model' ), 'facebook/mbart-large-cc25': ( 'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model' ), } } _lowerCamelCase = { 'facebook/mbart-large-en-ro': 1024, 'facebook/mbart-large-cc25': 1024, } # fmt: off _lowerCamelCase = ['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN'] class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = ["input_ids", "attention_mask"] lowerCamelCase_ = [] lowerCamelCase_ = [] def __init__( self :List[str] , __A :Optional[int] , __A :Tuple="<s>" , __A :Optional[Any]="</s>" , __A :List[Any]="</s>" , __A :Tuple="<s>" , __A :Optional[Any]="<unk>" , __A :str="<pad>" , __A :Tuple="<mask>" , __A :str=None , __A :str=None , __A :List[Any]=None , __A :Optional[Dict[str, Any]] = None , __A :int=None , **__A :Dict , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token SCREAMING_SNAKE_CASE__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , tokenizer_file=__A , src_lang=__A , tgt_lang=__A , additional_special_tokens=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) SCREAMING_SNAKE_CASE__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) SCREAMING_SNAKE_CASE__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE__ = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = len(self.sp_model ) SCREAMING_SNAKE_CASE__ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__A ) } SCREAMING_SNAKE_CASE__ = {v: k for k, v in self.lang_code_to_id.items()} SCREAMING_SNAKE_CASE__ = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) SCREAMING_SNAKE_CASE__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} SCREAMING_SNAKE_CASE__ = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) SCREAMING_SNAKE_CASE__ = src_lang if src_lang is not None else """en_XX""" SCREAMING_SNAKE_CASE__ = self.lang_code_to_id[self._src_lang] SCREAMING_SNAKE_CASE__ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.__dict__.copy() SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() return state def __setstate__( self :Tuple , __A :List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self :Optional[int] , __A :str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self :Dict , __A :List[int] , __A :Optional[List[int]] = None , __A :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = [1] * len(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__A )) + suffix_ones return prefix_ones + ([0] * len(__A )) + ([0] * len(__A )) + suffix_ones def _snake_case ( self :Any , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self :List[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self :List[Any] , __A :str , __A :str , __A :Optional[str] , __A :Optional[str] , **__A :List[str] ) -> Union[str, Any]: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) SCREAMING_SNAKE_CASE__ = src_lang SCREAMING_SNAKE_CASE__ = self(__A , add_special_tokens=__A , return_tensors=__A , **__A ) SCREAMING_SNAKE_CASE__ = self.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tgt_lang_id return inputs def _snake_case ( self :List[str] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = {self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self :List[str] , __A :str ) -> List[str]: """simple docstring""" return self.sp_model.encode(__A , out_type=__A ) def _snake_case ( self :str , __A :Tuple ) -> Optional[int]: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE__ = self.sp_model.PieceToId(__A ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self :Optional[int] , __A :Dict ) -> Dict: """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self :Optional[Any] , __A :Dict ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """""".join(__A ).replace(__A , """ """ ).strip() return out_string def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ = os.path.join( __A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , """wb""" ) as fi: SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,) def _snake_case ( self :Optional[int] , __A :List[str] , __A :str = "en_XX" , __A :Optional[List[str]] = None , __A :str = "ro_RO" , **__A :Optional[int] , ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ = src_lang SCREAMING_SNAKE_CASE__ = tgt_lang return super().prepare_seqaseq_batch(__A , __A , **__A ) def _snake_case ( self :Dict ) -> Dict: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self :List[Any] ) -> List[str]: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self :str , __A :Union[str, Any] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.lang_code_to_id[src_lang] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self :int , __A :str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.lang_code_to_id[lang] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [self.eos_token_id, self.cur_lang_code]
720
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
0
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , *__A :Tuple , **__A :Dict ) -> None: """simple docstring""" warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __A , ) super().__init__(*__A , **__A )
721
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
59
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 .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any=None ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser(add_help=UpperCamelCase__ , allow_abbrev=UpperCamelCase__ ) # The main config parser SCREAMING_SNAKE_CASE__ = config_command_parser(UpperCamelCase__ ) # The subparser to add commands to SCREAMING_SNAKE_CASE__ = config_parser.add_subparsers(title="""subcommands""" , dest="""subcommand""" ) # Then add other parsers with the parent parser default_command_parser(UpperCamelCase__ , parents=[parent_parser] ) update_command_parser(UpperCamelCase__ , parents=[parent_parser] ) return config_parser def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = get_config_parser() SCREAMING_SNAKE_CASE__ = config_parser.parse_args() if not hasattr(UpperCamelCase__ , """func""" ): config_parser.print_help() exit(1 ) # Run args.func(UpperCamelCase__ ) if __name__ == "__main__": main()
700
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__: float ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
59
0
'''simple docstring''' from math import ceil, sqrt def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 1_000_000 ): SCREAMING_SNAKE_CASE__ = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: SCREAMING_SNAKE_CASE__ = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: SCREAMING_SNAKE_CASE__ = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(F'''{solution() = }''')
701
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
0
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "CLIPImageProcessor" lowerCamelCase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__( self :Optional[int] , __A :Dict=None , __A :str=None , **__A :str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __A , ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__A , __A ) def __call__( self :Any , __A :Dict=None , __A :List[str]=None , __A :int=None , **__A :int ) -> 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: SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :Union[str, Any] , *__A :List[Any] , **__A :Optional[int] ) -> Optional[int]: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Union[str, Any] , *__A :Dict , **__A :Tuple ) -> Optional[int]: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
702
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCamelCase__ ) EnvironmentCommand.register_subcommand(UpperCamelCase__ ) TestCommand.register_subcommand(UpperCamelCase__ ) RunBeamCommand.register_subcommand(UpperCamelCase__ ) DummyDataCommand.register_subcommand(UpperCamelCase__ ) # Parse args SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_known_args() if not hasattr(UpperCamelCase__ , """func""" ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE__ = parse_unknown_args(UpperCamelCase__ ) # Run SCREAMING_SNAKE_CASE__ = args.func(UpperCamelCase__ , **UpperCamelCase__ ) service.run() if __name__ == "__main__": main()
59
0
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: torch.nn.Module , UpperCamelCase__: BnbQuantizationConfig , UpperCamelCase__: Union[str, os.PathLike] = None , UpperCamelCase__: Optional[Dict[str, Union[int, str, torch.device]]] = None , UpperCamelCase__: Optional[List[str]] = None , UpperCamelCase__: Optional[Dict[Union[int, str], Union[int, str]]] = None , UpperCamelCase__: Optional[Union[str, os.PathLike]] = None , UpperCamelCase__: bool = False , ): SCREAMING_SNAKE_CASE__ = bnb_quantization_config.load_in_abit SCREAMING_SNAKE_CASE__ = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( """You have a version of `bitsandbytes` that is not compatible with 8bit quantization,""" """ make sure you have the latest version of `bitsandbytes` installed.""" ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( """You have a version of `bitsandbytes` that is not compatible with 4bit quantization,""" """make sure you have the latest version of `bitsandbytes` installed.""" ) SCREAMING_SNAKE_CASE__ = [] # custom device map if isinstance(UpperCamelCase__ , UpperCamelCase__ ) and len(device_map.keys() ) > 1: SCREAMING_SNAKE_CASE__ = [key for key, value in device_map.items() if value in ["""disk""", """cpu"""]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: SCREAMING_SNAKE_CASE__ = get_keys_to_not_convert(UpperCamelCase__ ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(UpperCamelCase__ ) # compatibility with peft SCREAMING_SNAKE_CASE__ = load_in_abit SCREAMING_SNAKE_CASE__ = load_in_abit SCREAMING_SNAKE_CASE__ = get_parameter_device(UpperCamelCase__ ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( """It is not recommended to quantize a loaded model. """ """The model should be instantiated under the `init_empty_weights` context manager.""" ) SCREAMING_SNAKE_CASE__ = replace_with_bnb_layers(UpperCamelCase__ , UpperCamelCase__ , modules_to_not_convert=UpperCamelCase__ ) # convert param to the right dtype SCREAMING_SNAKE_CASE__ = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: SCREAMING_SNAKE_CASE__ = name.replace(""".weight""" , """""" ).replace(""".bias""" , """""" ) SCREAMING_SNAKE_CASE__ = getattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(UpperCamelCase__ ): param.to(UpperCamelCase__ ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info( f'''The model device type is {model_device.type}. However, cuda is needed for quantization.''' """We move the model to cuda.""" ) return model elif weights_location is None: raise RuntimeError( f'''`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ''' ) else: with init_empty_weights(): SCREAMING_SNAKE_CASE__ = replace_with_bnb_layers( UpperCamelCase__ , UpperCamelCase__ , modules_to_not_convert=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_quantized_model_device_map( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , max_memory=UpperCamelCase__ , no_split_module_classes=UpperCamelCase__ , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = any(x in list(device_map.values() ) for x in ["""cpu""", """disk"""] ) load_checkpoint_in_model( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , dtype=bnb_quantization_config.torch_dtype , offload_folder=UpperCamelCase__ , offload_state_dict=UpperCamelCase__ , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(UpperCamelCase__ , device_map=UpperCamelCase__ , offload_dir=UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: Union[str, Any]=None , UpperCamelCase__: str=None , UpperCamelCase__: int=None ): if device_map is None: if torch.cuda.is_available(): SCREAMING_SNAKE_CASE__ = {"""""": torch.cuda.current_device()} else: raise RuntimeError("""No GPU found. A GPU is needed for quantization.""" ) logger.info("""The device_map was not initialized.""" """Setting device_map to `{'':torch.cuda.current_device()}`.""" ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( """If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or """ """'sequential'.""" ) SCREAMING_SNAKE_CASE__ = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = special_dtypes SCREAMING_SNAKE_CASE__ = no_split_module_classes SCREAMING_SNAKE_CASE__ = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": SCREAMING_SNAKE_CASE__ = get_balanced_memory( UpperCamelCase__ , low_zero=(device_map == """balanced_low_0""") , max_memory=UpperCamelCase__ , **UpperCamelCase__ , ) SCREAMING_SNAKE_CASE__ = max_memory SCREAMING_SNAKE_CASE__ = infer_auto_device_map(UpperCamelCase__ , **UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ): # check if don't have any quantized module on the cpu SCREAMING_SNAKE_CASE__ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules SCREAMING_SNAKE_CASE__ = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( """ Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. """ ) else: logger.info( """Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit""" ) del device_map_without_some_modules return device_map def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int , UpperCamelCase__: List[Any]=None , UpperCamelCase__: List[str]=None ): if modules_to_not_convert is None: SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = _replace_with_bnb_layers( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: int=None , UpperCamelCase__: List[Any]=None , ): SCREAMING_SNAKE_CASE__ = False for name, module in model.named_children(): if current_key_name is None: SCREAMING_SNAKE_CASE__ = [] current_key_name.append(UpperCamelCase__ ) if isinstance(UpperCamelCase__ , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` SCREAMING_SNAKE_CASE__ = """.""".join(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: SCREAMING_SNAKE_CASE__ = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: SCREAMING_SNAKE_CASE__ = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=UpperCamelCase__ , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: SCREAMING_SNAKE_CASE__ = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("""load_in_8bit and load_in_4bit can't be both False""" ) SCREAMING_SNAKE_CASE__ = module.weight.data if module.bias is not None: SCREAMING_SNAKE_CASE__ = module.bias.data bnb_module.requires_grad_(UpperCamelCase__ ) setattr(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = True if len(list(module.children() ) ) > 0: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = _replace_with_bnb_layers( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): # Create a copy of the model with init_empty_weights(): SCREAMING_SNAKE_CASE__ = deepcopy(UpperCamelCase__ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` SCREAMING_SNAKE_CASE__ = find_tied_parameters(UpperCamelCase__ ) # For compatibility with Accelerate < 0.18 if isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: SCREAMING_SNAKE_CASE__ = sum(UpperCamelCase__ , [] ) SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 # Check if it is a base model SCREAMING_SNAKE_CASE__ = False if hasattr(UpperCamelCase__ , """base_model_prefix""" ): SCREAMING_SNAKE_CASE__ = not hasattr(UpperCamelCase__ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head SCREAMING_SNAKE_CASE__ = list(model.named_children() ) SCREAMING_SNAKE_CASE__ = [list_modules[-1][0]] # add last module together with tied weights SCREAMING_SNAKE_CASE__ = set(UpperCamelCase__ ) - set(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = list(set(UpperCamelCase__ ) ) + list(UpperCamelCase__ ) # remove ".weight" from the keys SCREAMING_SNAKE_CASE__ = [""".weight""", """.bias"""] SCREAMING_SNAKE_CASE__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: SCREAMING_SNAKE_CASE__ = name.replace(UpperCamelCase__ , """""" ) filtered_module_names.append(UpperCamelCase__ ) return filtered_module_names def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): for m in model.modules(): if isinstance(UpperCamelCase__ , bnb.nn.Linearabit ): return True return False def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: nn.Module ): return next(parameter.parameters() ).device def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: int , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Dict ): # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(UpperCamelCase__ , UpperCamelCase__ , 0 , dtype=UpperCamelCase__ , value=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = param_name SCREAMING_SNAKE_CASE__ = model if "." in tensor_name: SCREAMING_SNAKE_CASE__ = tensor_name.split(""".""" ) for split in splits[:-1]: SCREAMING_SNAKE_CASE__ = getattr(UpperCamelCase__ , UpperCamelCase__ ) if new_module is None: raise ValueError(f'''{module} has no attribute {split}.''' ) SCREAMING_SNAKE_CASE__ = new_module SCREAMING_SNAKE_CASE__ = splits[-1] # offload weights SCREAMING_SNAKE_CASE__ = False offload_weight(module._parameters[tensor_name] , UpperCamelCase__ , UpperCamelCase__ , index=UpperCamelCase__ ) if hasattr(module._parameters[tensor_name] , """SCB""" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("""weight""" , """SCB""" ) , UpperCamelCase__ , index=UpperCamelCase__ , ) else: offload_weight(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , index=UpperCamelCase__ ) offload_weight(UpperCamelCase__ , param_name.replace("""weight""" , """SCB""" ) , UpperCamelCase__ , index=UpperCamelCase__ ) set_module_tensor_to_device(UpperCamelCase__ , UpperCamelCase__ , """meta""" , dtype=UpperCamelCase__ , value=torch.empty(*param.size() ) )
703
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , *__A :Tuple , **__A :Dict ) -> None: """simple docstring""" warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __A , ) super().__init__(*__A , **__A )
59
0
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__: float ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
704
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
59
0
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int | float] , UpperCamelCase__: int , UpperCamelCase__: int ): if len(UpperCamelCase__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(UpperCamelCase__ ) or left < -len(UpperCamelCase__ ) or right >= len(UpperCamelCase__ ) or right < -len(UpperCamelCase__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ = find_max(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ = find_max(UpperCamelCase__ , mid + 1 , UpperCamelCase__ ) # 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)
705
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__ )}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
0
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list ): for i in range(len(UpperCamelCase__ ) - 1 , 0 , -1 ): SCREAMING_SNAKE_CASE__ = False for j in range(UpperCamelCase__ , 0 , -1 ): if unsorted[j] < unsorted[j - 1]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = unsorted[j - 1], unsorted[j] SCREAMING_SNAKE_CASE__ = True for j in range(UpperCamelCase__ ): if unsorted[j] > unsorted[j + 1]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = unsorted[j + 1], unsorted[j] SCREAMING_SNAKE_CASE__ = True if not swapped: break return unsorted if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase = input('Enter numbers separated by a comma:\n').strip() _lowerCamelCase = [int(item) for item in user_input.split(',')] print(F'''{cocktail_shaker_sort(unsorted) = }''')
706
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
59
0
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ : def __init__( self :Any , __A :int , __A :str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = question_encoder SCREAMING_SNAKE_CASE__ = generator SCREAMING_SNAKE_CASE__ = self.question_encoder def _snake_case ( self :Optional[Any] , __A :Optional[Any] ) -> Optional[int]: """simple docstring""" if os.path.isfile(__A ): raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(__A , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , """question_encoder_tokenizer""" ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , """generator_tokenizer""" ) self.question_encoder.save_pretrained(__A ) self.generator.save_pretrained(__A ) @classmethod def _snake_case ( cls :List[str] , __A :Optional[int] , **__A :str ) -> Optional[int]: """simple docstring""" from ..auto.tokenization_auto import AutoTokenizer SCREAMING_SNAKE_CASE__ = kwargs.pop("""config""" , __A ) if config is None: SCREAMING_SNAKE_CASE__ = RagConfig.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained( __A , config=config.question_encoder , subfolder="""question_encoder_tokenizer""" ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained( __A , config=config.generator , subfolder="""generator_tokenizer""" ) return cls(question_encoder=__A , generator=__A ) def __call__( self :Optional[int] , *__A :List[Any] , **__A :str ) -> Optional[Any]: """simple docstring""" return self.current_tokenizer(*__A , **__A ) def _snake_case ( self :Optional[int] , *__A :Optional[Any] , **__A :List[Any] ) -> Optional[int]: """simple docstring""" return self.generator.batch_decode(*__A , **__A ) def _snake_case ( self :Union[str, Any] , *__A :int , **__A :List[Any] ) -> List[Any]: """simple docstring""" return self.generator.decode(*__A , **__A ) def _snake_case ( self :int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.question_encoder def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.generator def _snake_case ( self :str , __A :List[str] , __A :Optional[List[str]] = None , __A :Optional[int] = None , __A :Optional[int] = None , __A :str = "longest" , __A :str = None , __A :bool = True , **__A :int , ) -> BatchEncoding: """simple docstring""" warnings.warn( """`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the """ """regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` """ """context manager to prepare your targets. See the documentation of your specific tokenizer for more """ """details""" , __A , ) if max_length is None: SCREAMING_SNAKE_CASE__ = self.current_tokenizer.model_max_length SCREAMING_SNAKE_CASE__ = self( __A , add_special_tokens=__A , return_tensors=__A , max_length=__A , padding=__A , truncation=__A , **__A , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: SCREAMING_SNAKE_CASE__ = self.current_tokenizer.model_max_length SCREAMING_SNAKE_CASE__ = self( text_target=__A , add_special_tokens=__A , return_tensors=__A , padding=__A , max_length=__A , truncation=__A , **__A , ) SCREAMING_SNAKE_CASE__ = labels["""input_ids"""] return model_inputs
707
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
59
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase = { 'configuration_whisper': ['WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'WhisperConfig', 'WhisperOnnxConfig'], 'feature_extraction_whisper': ['WhisperFeatureExtractor'], 'processing_whisper': ['WhisperProcessor'], 'tokenization_whisper': ['WhisperTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['WhisperTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST', 'WhisperForConditionalGeneration', 'WhisperModel', 'WhisperPreTrainedModel', 'WhisperForAudioClassification', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFWhisperForConditionalGeneration', 'TFWhisperModel', 'TFWhisperPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'FlaxWhisperForConditionalGeneration', 'FlaxWhisperModel', 'FlaxWhisperPreTrainedModel', 'FlaxWhisperForAudioClassification', ] if TYPE_CHECKING: from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig from .feature_extraction_whisper import WhisperFeatureExtractor from .processing_whisper import WhisperProcessor from .tokenization_whisper import WhisperTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_whisper_fast import WhisperTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_whisper import ( WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, WhisperForAudioClassification, WhisperForConditionalGeneration, WhisperModel, WhisperPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_whisper import ( TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, TFWhisperForConditionalGeneration, TFWhisperModel, TFWhisperPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_whisper import ( FlaxWhisperForAudioClassification, FlaxWhisperForConditionalGeneration, FlaxWhisperModel, FlaxWhisperPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
708
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , default=512 , help="""Maximum sequence length. For training on TPUs, it helps to have a maximum""" """ sequence length that is a multiple of 8.""" , ) parser.add_argument( """--output_dir""" , default="""tf-tpu""" , type=UpperCamelCase__ , help="""Output directory where the TFRecord shards will be saved. If the""" """ path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord""" """ shards will be directly saved to a Google Cloud Storage bucket.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """input_ids""": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["""input_ids"""][i] ) ), """attention_mask""": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["""attention_mask"""][i] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , num_proc=4 , remove_columns=["""text"""] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) shard_count += 1 total_records += records_containing with open(f'''split-{args.split}-records-count.txt''' , """w""" ) as f: print(f'''Total {args.split} records: {total_records}''' , file=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
59
0
from __future__ import annotations _lowerCamelCase = [] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] , UpperCamelCase__: int , UpperCamelCase__: int ): for i in range(len(UpperCamelCase__ ) ): if board[row][i] == 1: return False for i in range(len(UpperCamelCase__ ) ): if board[i][column] == 1: return False for i, j in zip(range(UpperCamelCase__ , -1 , -1 ) , range(UpperCamelCase__ , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(UpperCamelCase__ , -1 , -1 ) , range(UpperCamelCase__ , len(UpperCamelCase__ ) ) ): if board[i][j] == 1: return False return True def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] , UpperCamelCase__: int ): if row >= len(UpperCamelCase__ ): solution.append(UpperCamelCase__ ) printboard(UpperCamelCase__ ) print() return True for i in range(len(UpperCamelCase__ ) ): if is_safe(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = 1 solve(UpperCamelCase__ , row + 1 ) SCREAMING_SNAKE_CASE__ = 0 return False def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] ): for i in range(len(UpperCamelCase__ ) ): for j in range(len(UpperCamelCase__ ) ): if board[i][j] == 1: print("""Q""" , end=""" """ ) else: print(""".""" , end=""" """ ) print() # n=int(input("The no. of queens")) _lowerCamelCase = 8 _lowerCamelCase = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print('The total no. of solutions are :', len(solution))
709
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [] for data in source_data: for i, el in enumerate(UpperCamelCase__ ): if len(UpperCamelCase__ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(UpperCamelCase__ ) ) return data_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = [] for dlist, weight in zip(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: SCREAMING_SNAKE_CASE__ = f'''Invalid weight of {weight:f} provided''' raise ValueError(UpperCamelCase__ ) score_lists.append(UpperCamelCase__ ) return score_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = get_data(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = calculate_each_score(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = generate_final_scores(UpperCamelCase__ ) # append scores to source data for i, ele in enumerate(UpperCamelCase__ ): source_data[i].append(UpperCamelCase__ ) return source_data
59
0
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = CustomTokenizer pass
710
import warnings from functools import wraps from typing import Callable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Callable ): @wraps(UpperCamelCase__ ) def _inner_fn(*UpperCamelCase__: Dict , **UpperCamelCase__: Any ): warnings.warn( (f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , UpperCamelCase__ , ) return fn(*UpperCamelCase__ , **UpperCamelCase__ ) return _inner_fn
59
0
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: BertModel , UpperCamelCase__: str , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = ("""dense.weight""", """attention.self.query""", """attention.self.key""", """attention.self.value""") SCREAMING_SNAKE_CASE__ = ( ("""layer.""", """layer_"""), ("""word_embeddings.weight""", """word_embeddings"""), ("""position_embeddings.weight""", """position_embeddings"""), ("""token_type_embeddings.weight""", """token_type_embeddings"""), (""".""", """/"""), ("""LayerNorm/weight""", """LayerNorm/gamma"""), ("""LayerNorm/bias""", """LayerNorm/beta"""), ("""weight""", """kernel"""), ) if not os.path.isdir(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = model.state_dict() def to_tf_var_name(UpperCamelCase__: str ): for patt, repl in iter(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = name.replace(UpperCamelCase__ , UpperCamelCase__ ) return f'''bert/{name}''' def create_tf_var(UpperCamelCase__: np.ndarray , UpperCamelCase__: str , UpperCamelCase__: tf.Session ): SCREAMING_SNAKE_CASE__ = tf.dtypes.as_dtype(tensor.dtype ) SCREAMING_SNAKE_CASE__ = tf.get_variable(dtype=UpperCamelCase__ , shape=tensor.shape , name=UpperCamelCase__ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(UpperCamelCase__ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: SCREAMING_SNAKE_CASE__ = to_tf_var_name(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): SCREAMING_SNAKE_CASE__ = torch_tensor.T SCREAMING_SNAKE_CASE__ = create_tf_var(tensor=UpperCamelCase__ , name=UpperCamelCase__ , session=UpperCamelCase__ ) tf.keras.backend.set_value(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = session.run(UpperCamelCase__ ) print(f'''Successfully created {tf_name}: {np.allclose(UpperCamelCase__ , UpperCamelCase__ )}''' ) SCREAMING_SNAKE_CASE__ = tf.train.Saver(tf.trainable_variables() ) saver.save(UpperCamelCase__ , os.path.join(UpperCamelCase__ , model_name.replace("""-""" , """_""" ) + """.ckpt""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int]=None ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() parser.add_argument("""--model_name""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""model name e.g. bert-base-uncased""" ) parser.add_argument( """--cache_dir""" , type=UpperCamelCase__ , default=UpperCamelCase__ , required=UpperCamelCase__ , help="""Directory containing pytorch model""" ) parser.add_argument("""--pytorch_model_path""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""/path/to/<pytorch-model-name>.bin""" ) parser.add_argument("""--tf_cache_dir""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""Directory in which to save tensorflow model""" ) SCREAMING_SNAKE_CASE__ = parser.parse_args(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=UpperCamelCase__ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
711
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RoCBertTokenizer lowerCamelCase_ = None lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = filter_non_english def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(__A , __A , ensure_ascii=__A ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(__A , __A , ensure_ascii=__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(__A , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__A ) , [5, 6, 2, 5, 7, 8] ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=__A , 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 _snake_case ( self :Any ) -> str: """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 _snake_case ( self :int ) -> str: """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 _snake_case ( self :List[str] ) -> List[str]: """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 _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def _snake_case ( self :int ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(__A , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE__ = ( [ ((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 _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你好""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你是谁""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( __A , __A , __A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(__A , add_special_tokens=__A ) self.assertEqual(__A , __A )
59
0
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int] , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) # Initialize Result SCREAMING_SNAKE_CASE__ = [] # Traverse through all denomination for denomination in reversed(UpperCamelCase__ ): # Find denominations while int(UpperCamelCase__ ) >= int(UpperCamelCase__ ): total_value -= int(UpperCamelCase__ ) answer.append(UpperCamelCase__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": _lowerCamelCase = [] _lowerCamelCase = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): _lowerCamelCase = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(F'''Denomination {i}: ''').strip())) _lowerCamelCase = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter _lowerCamelCase = [1, 2, 5, 10, 20, 50, 100, 500, 2000] _lowerCamelCase = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(F'''Following is minimal change for {value}: ''') _lowerCamelCase = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
712
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = original_name.split(""".""" )[0] SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 2] ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 1] ) SCREAMING_SNAKE_CASE__ = orig_block_num - offset SCREAMING_SNAKE_CASE__ = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = OrderedDict() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): SCREAMING_SNAKE_CASE__ = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 SCREAMING_SNAKE_CASE__ = key[: key.find("""proj""" )] SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , f'''patch_embeddings.{total_embed_found}.''' ) SCREAMING_SNAKE_CASE__ = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: SCREAMING_SNAKE_CASE__ = """poolformer.encoder.""" + key if "mlp.fc1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm1""" , """before_norm""" ) if "norm2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: SCREAMING_SNAKE_CASE__ = key.replace("""head""" , """classifier""" ) SCREAMING_SNAKE_CASE__ = value return new_state_dict def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = PoolFormerConfig() # set attributes based on model_name SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = model_name[-3:] SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = (1, 1_000) # set config attributes SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if size == "s12": SCREAMING_SNAKE_CASE__ = [2, 2, 6, 2] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s24": SCREAMING_SNAKE_CASE__ = [4, 4, 12, 4] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "m36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 elif size == "m48": SCREAMING_SNAKE_CASE__ = [8, 8, 24, 8] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) # Prepare image SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location=torch.device("""cpu""" ) ) # rename keys SCREAMING_SNAKE_CASE__ = rename_keys(UpperCamelCase__ ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ = PoolFormerForImageClassification(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Define image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.logits # define expected logit slices for different models if size == "s12": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": SCREAMING_SNAKE_CASE__ = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": SCREAMING_SNAKE_CASE__ = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": SCREAMING_SNAKE_CASE__ = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , UpperCamelCase__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
0
'''simple docstring''' import numpy as np def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: np.array ): return 1 / (1 + np.exp(-vector )) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: np.array ): return vector * sigmoid(1.7_0_2 * vector ) if __name__ == "__main__": import doctest doctest.testmod()
713
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_text_model" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :Union[str, Any] , __A :Any=5_0244 , __A :Optional[Any]=768 , __A :Tuple=64 , __A :List[str]=2048 , __A :int=12 , __A :str=12 , __A :Any=32 , __A :Tuple=128 , __A :int=0.1 , __A :str=1E-6 , __A :Optional[Any]=1.0 , __A :Union[str, Any]="gelu_new" , __A :Any=0 , __A :List[str]=False , __A :Optional[Any]=0 , __A :int=1 , __A :Optional[int]=False , __A :Optional[Any]=True , **__A :List[Any] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = d_kv SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = num_layers SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = decoder_start_token_id # for backwards compatibility SCREAMING_SNAKE_CASE__ = dense_act_fn super().__init__( pad_token_id=__A , eos_token_id=__A , decoder_start_token_id=__A , tie_word_embeddings=__A , is_decoder=__A , **__A , ) @classmethod def _snake_case ( cls :Optional[int] , __A :Union[str, os.PathLike] , **__A :Optional[int] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = 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(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_vision_model" def __init__( self :Optional[int] , __A :int=768 , __A :Optional[Any]=768 , __A :Union[str, Any]=2048 , __A :int=64 , __A :Union[str, Any]=12 , __A :str=12 , __A :Any="gelu_new" , __A :List[Any]=1E-6 , __A :Dict=0.0 , __A :int=0.0 , __A :int=1E-10 , __A :Dict=1.0 , __A :int=4096 , __A :int=32 , __A :int=128 , **__A :Tuple , ) -> str: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = patch_embed_hidden_size SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = dense_act_fn SCREAMING_SNAKE_CASE__ = seq_len SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = d_kv @classmethod def _snake_case ( cls :str , __A :Union[str, os.PathLike] , **__A :str ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = 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(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct" lowerCamelCase_ = True def __init__( self :str , __A :Optional[Any]=None , __A :List[str]=None , __A :Optional[Any]=1.0 , __A :Optional[Any]=0.0_2 , __A :Any=False , __A :Tuple=False , __A :Any=True , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__(tie_word_embeddings=__A , is_encoder_decoder=__A , **__A ) if text_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE__ = PixaStructTextConfig(**__A ) SCREAMING_SNAKE_CASE__ = PixaStructVisionConfig(**__A ) SCREAMING_SNAKE_CASE__ = self.text_config.decoder_start_token_id SCREAMING_SNAKE_CASE__ = self.text_config.pad_token_id SCREAMING_SNAKE_CASE__ = self.text_config.eos_token_id SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = is_vqa @classmethod def _snake_case ( cls :Union[str, Any] , __A :PixaStructTextConfig , __A :PixaStructVisionConfig , **__A :Optional[int] ) -> Optional[Any]: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__A ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
0
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , default=512 , help="""Maximum sequence length. For training on TPUs, it helps to have a maximum""" """ sequence length that is a multiple of 8.""" , ) parser.add_argument( """--output_dir""" , default="""tf-tpu""" , type=UpperCamelCase__ , help="""Output directory where the TFRecord shards will be saved. If the""" """ path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord""" """ shards will be directly saved to a Google Cloud Storage bucket.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """input_ids""": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["""input_ids"""][i] ) ), """attention_mask""": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["""attention_mask"""][i] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , num_proc=4 , remove_columns=["""text"""] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) shard_count += 1 total_records += records_containing with open(f'''split-{args.split}-records-count.txt''' , """w""" ) as f: print(f'''Total {args.split} records: {total_records}''' , file=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
714
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[int] ) -> str: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__A , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = Accelerator() _lowerCamelCase = (accelerator.state.process_index + 2, 10) _lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device) _lowerCamelCase = '' _lowerCamelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." _lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." _lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "decision_transformer" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self :str , __A :List[Any]=17 , __A :Optional[int]=4 , __A :str=128 , __A :int=4096 , __A :Any=True , __A :int=1 , __A :int=1024 , __A :int=3 , __A :Union[str, Any]=1 , __A :int=None , __A :str="relu" , __A :Union[str, Any]=0.1 , __A :Tuple=0.1 , __A :Optional[int]=0.1 , __A :Optional[int]=1E-5 , __A :int=0.0_2 , __A :Any=True , __A :Dict=True , __A :Optional[int]=5_0256 , __A :Dict=5_0256 , __A :str=False , __A :Optional[Any]=False , **__A :Any , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = state_dim SCREAMING_SNAKE_CASE__ = act_dim SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = max_ep_len SCREAMING_SNAKE_CASE__ = action_tanh SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = n_positions SCREAMING_SNAKE_CASE__ = n_layer SCREAMING_SNAKE_CASE__ = n_head SCREAMING_SNAKE_CASE__ = n_inner SCREAMING_SNAKE_CASE__ = activation_function SCREAMING_SNAKE_CASE__ = resid_pdrop SCREAMING_SNAKE_CASE__ = embd_pdrop SCREAMING_SNAKE_CASE__ = attn_pdrop SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = scale_attn_weights SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = scale_attn_by_inverse_layer_idx SCREAMING_SNAKE_CASE__ = reorder_and_upcast_attn SCREAMING_SNAKE_CASE__ = bos_token_id SCREAMING_SNAKE_CASE__ = eos_token_id super().__init__(bos_token_id=__A , eos_token_id=__A , **__A )
715
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCamelCase = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3FeatureExtractor'] _lowerCamelCase = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
0
import inspect import unittest class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self :Any ) -> Any: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ = inspect.getmembers(__A , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ = """k-diffusion""" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ = """invisible-watermark""" assert backend in deps, f'''{backend} is not in the deps table!'''
716
import inspect import unittest class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self :Any ) -> Any: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ = inspect.getmembers(__A , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ = """k-diffusion""" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ = """invisible-watermark""" assert backend in deps, f'''{backend} is not in the deps table!'''
59
0
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () _lowerCamelCase = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). _lowerCamelCase = [0, 25, 50] _lowerCamelCase = [25, 50, 75] _lowerCamelCase = fuzz.membership.trimf(X, abca) _lowerCamelCase = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. _lowerCamelCase = np.ones(75) _lowerCamelCase = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) _lowerCamelCase = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) _lowerCamelCase = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) _lowerCamelCase = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) _lowerCamelCase = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] _lowerCamelCase = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) _lowerCamelCase = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] _lowerCamelCase = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] _lowerCamelCase = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
717
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 _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
59
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _lowerCamelCase = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
718
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = OpenAIGPTTokenizer lowerCamelCase_ = OpenAIGPTTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Union[str, Any] , __A :str ) -> List[Any]: """simple docstring""" return "lower newer", "lower newer" def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE__ = """lower""" SCREAMING_SNAKE_CASE__ = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] , __A :Optional[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) # Simple input SCREAMING_SNAKE_CASE__ = """This is a simple input""" SCREAMING_SNAKE_CASE__ = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE__ = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) # Pair input self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ ): pass
59
0
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCamelCase_ : def __init__( self :Optional[Any] , __A :Tuple , __A :List[Any]=2 , __A :Tuple=3 , __A :Union[str, Any]=4 , __A :List[Any]=2 , __A :List[str]=7 , __A :str=True , __A :List[Any]=True , __A :str=True , __A :Union[str, Any]=True , __A :Dict=99 , __A :Union[str, Any]=36 , __A :Dict=3 , __A :int=4 , __A :Tuple=37 , __A :Union[str, Any]="gelu" , __A :int=0.1 , __A :Optional[Any]=0.1 , __A :int=512 , __A :List[Any]=16 , __A :Any=2 , __A :Dict=0.0_2 , __A :List[Any]=6 , __A :Union[str, Any]=6 , __A :Tuple=3 , __A :Tuple=4 , __A :Optional[Any]=None , __A :str=1000 , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = text_seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_mask SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = coordinate_size SCREAMING_SNAKE_CASE__ = shape_size SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = scope SCREAMING_SNAKE_CASE__ = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) SCREAMING_SNAKE_CASE__ = text_seq_length SCREAMING_SNAKE_CASE__ = (image_size // patch_size) ** 2 + 1 SCREAMING_SNAKE_CASE__ = self.text_seq_length + self.image_seq_length def _snake_case ( self :str ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: SCREAMING_SNAKE_CASE__ = bbox[i, j, 3] SCREAMING_SNAKE_CASE__ = bbox[i, j, 1] SCREAMING_SNAKE_CASE__ = t if bbox[i, j, 2] < bbox[i, j, 0]: SCREAMING_SNAKE_CASE__ = bbox[i, j, 2] SCREAMING_SNAKE_CASE__ = bbox[i, j, 0] SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.text_seq_length] ) SCREAMING_SNAKE_CASE__ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self :Any , __A :Optional[Any] , __A :Optional[Any] , __A :List[str] , __A :List[str] , __A :int , __A :Optional[Any] , __A :Tuple , __A :Tuple ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = LayoutLMvaModel(config=__A ) model.to(__A ) model.eval() # text + image SCREAMING_SNAKE_CASE__ = model(__A , pixel_values=__A ) SCREAMING_SNAKE_CASE__ = model( __A , bbox=__A , pixel_values=__A , attention_mask=__A , token_type_ids=__A ) SCREAMING_SNAKE_CASE__ = model(__A , bbox=__A , pixel_values=__A , token_type_ids=__A ) SCREAMING_SNAKE_CASE__ = model(__A , bbox=__A , pixel_values=__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only SCREAMING_SNAKE_CASE__ = model(pixel_values=__A ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self :List[Any] , __A :List[Any] , __A :Optional[Any] , __A :Union[str, Any] , __A :int , __A :List[str] , __A :Any , __A :str , __A :Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = LayoutLMvaForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model( __A , bbox=__A , pixel_values=__A , attention_mask=__A , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self :List[Any] , __A :int , __A :List[Any] , __A :Optional[int] , __A :Dict , __A :Optional[Any] , __A :Union[str, Any] , __A :List[str] , __A :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = LayoutLMvaForTokenClassification(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model( __A , bbox=__A , pixel_values=__A , attention_mask=__A , token_type_ids=__A , labels=__A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self :Union[str, Any] , __A :Tuple , __A :Union[str, Any] , __A :Tuple , __A :Optional[Any] , __A :List[Any] , __A :Union[str, Any] , __A :Optional[int] , __A :int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = LayoutLMvaForQuestionAnswering(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model( __A , bbox=__A , pixel_values=__A , attention_mask=__A , token_type_ids=__A , start_positions=__A , end_positions=__A , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = { """input_ids""": input_ids, """bbox""": bbox, """pixel_values""": pixel_values, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) lowerCamelCase_ = ( {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel} if is_torch_available() else {} ) def _snake_case ( self :Any , __A :str , __A :Dict , __A :Optional[int] , __A :List[str] , __A :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return True def _snake_case ( self :int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = LayoutLMvaModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , hidden_size=37 ) def _snake_case ( self :str , __A :Any , __A :Union[str, Any] , __A :List[str]=False ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(__A ) if model_class in get_values(__A ): SCREAMING_SNAKE_CASE__ = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(__A , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(__A ): SCREAMING_SNAKE_CASE__ = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=__A ) elif model_class in get_values(__A ): SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) elif model_class in [ *get_values(__A ), ]: SCREAMING_SNAKE_CASE__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__A ) elif model_class in [ *get_values(__A ), ]: SCREAMING_SNAKE_CASE__ = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=__A , ) return inputs_dict def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ = type self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__A ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__A ) def _snake_case ( self :Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__A ) @slow def _snake_case ( self :Optional[int] ) -> Optional[int]: """simple docstring""" for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = LayoutLMvaModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class UpperCamelCase_ ( unittest.TestCase ): @cached_property def _snake_case ( self :str ) -> int: """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=__A ) if is_vision_available() else None @slow def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = LayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" ).to(__A ) SCREAMING_SNAKE_CASE__ = self.default_image_processor SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""pt""" ).pixel_values.to(__A ) SCREAMING_SNAKE_CASE__ = torch.tensor([[1, 2]] ) SCREAMING_SNAKE_CASE__ = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass SCREAMING_SNAKE_CASE__ = model( input_ids=input_ids.to(__A ) , bbox=bbox.to(__A ) , pixel_values=pixel_values.to(__A ) , ) # verify the logits SCREAMING_SNAKE_CASE__ = torch.Size((1, 199, 768) ) self.assertEqual(outputs.last_hidden_state.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ).to(__A ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __A , atol=1E-4 ) )
719
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = None class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = 2 @register_to_config def __init__( self :Any , __A :float = 0.0_2 , __A :float = 100 , __A :float = 1.0_0_7 , __A :float = 80 , __A :float = 0.0_5 , __A :float = 50 , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sigma_max # setable values SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # sigma(t_i) def _snake_case ( self :Optional[int] , __A :torch.FloatTensor , __A :Optional[int] = None ) -> torch.FloatTensor: """simple docstring""" return sample def _snake_case ( self :Union[str, Any] , __A :int , __A :Union[str, torch.device] = None ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = num_inference_steps SCREAMING_SNAKE_CASE__ = np.arange(0 , self.num_inference_steps )[::-1].copy() SCREAMING_SNAKE_CASE__ = torch.from_numpy(__A ).to(__A ) SCREAMING_SNAKE_CASE__ = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] SCREAMING_SNAKE_CASE__ = torch.tensor(__A , dtype=torch.floataa , device=__A ) def _snake_case ( self :List[Any] , __A :torch.FloatTensor , __A :float , __A :Optional[torch.Generator] = None ) -> Tuple[torch.FloatTensor, float]: """simple docstring""" if self.config.s_min <= sigma <= self.config.s_max: SCREAMING_SNAKE_CASE__ = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: SCREAMING_SNAKE_CASE__ = 0 # sample eps ~ N(0, S_noise^2 * I) SCREAMING_SNAKE_CASE__ = self.config.s_noise * randn_tensor(sample.shape , generator=__A ).to(sample.device ) SCREAMING_SNAKE_CASE__ = sigma + gamma * sigma SCREAMING_SNAKE_CASE__ = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def _snake_case ( self :Optional[int] , __A :torch.FloatTensor , __A :float , __A :float , __A :torch.FloatTensor , __A :bool = True , ) -> Union[KarrasVeOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sample_hat + sigma_hat * model_output SCREAMING_SNAKE_CASE__ = (sample_hat - pred_original_sample) / sigma_hat SCREAMING_SNAKE_CASE__ = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=__A , derivative=__A , pred_original_sample=__A ) def _snake_case ( self :List[Any] , __A :torch.FloatTensor , __A :float , __A :float , __A :torch.FloatTensor , __A :torch.FloatTensor , __A :torch.FloatTensor , __A :bool = True , ) -> Union[KarrasVeOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sample_prev + sigma_prev * model_output SCREAMING_SNAKE_CASE__ = (sample_prev - pred_original_sample) / sigma_prev SCREAMING_SNAKE_CASE__ = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=__A , derivative=__A , pred_original_sample=__A ) def _snake_case ( self :str , __A :str , __A :Dict , __A :Tuple ) -> Any: """simple docstring""" raise NotImplementedError()
720
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP 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 from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = KandinskyInpaintPipeline lowerCamelCase_ = ["prompt", "image_embeds", "negative_image_embeds", "image", "mask_image"] lowerCamelCase_ = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", "mask_image", ] lowerCamelCase_ = [ "generator", "height", "width", "latents", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] lowerCamelCase_ = False @property def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" return 32 @property def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" return 32 @property def _snake_case ( self :List[str] ) -> int: """simple docstring""" return self.time_input_dim @property def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" return self.time_input_dim * 4 @property def _snake_case ( self :Optional[int] ) -> int: """simple docstring""" return 100 @property def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def _snake_case ( self :List[str] ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) SCREAMING_SNAKE_CASE__ = MultilingualCLIP(__A ) SCREAMING_SNAKE_CASE__ = text_encoder.eval() return text_encoder @property def _snake_case ( self :List[str] ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = { """in_channels""": 9, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } SCREAMING_SNAKE_CASE__ = UNetaDConditionModel(**__A ) return model @property def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = VQModel(**self.dummy_movq_kwargs ) return model def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ = self.dummy_tokenizer SCREAMING_SNAKE_CASE__ = self.dummy_unet SCREAMING_SNAKE_CASE__ = self.dummy_movq SCREAMING_SNAKE_CASE__ = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="""linear""" , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , clip_sample=__A , set_alpha_to_one=__A , steps_offset=1 , prediction_type="""epsilon""" , thresholding=__A , ) SCREAMING_SNAKE_CASE__ = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def _snake_case ( self :Dict , __A :Optional[int] , __A :Union[str, Any]=0 ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__A ) ).to(__A ) SCREAMING_SNAKE_CASE__ = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(__A ) # create init_image SCREAMING_SNAKE_CASE__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(__A ) ).to(__A ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ = Image.fromarray(np.uinta(__A ) ).convert("""RGB""" ).resize((256, 256) ) # create mask SCREAMING_SNAKE_CASE__ = np.ones((64, 64) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = 0 if str(__A ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ = torch.manual_seed(__A ) else: SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(__A ) SCREAMING_SNAKE_CASE__ = { """prompt""": """horse""", """image""": init_image, """mask_image""": mask, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 2, """guidance_scale""": 4.0, """output_type""": """np""", } return inputs def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = """cpu""" SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**__A ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = pipe(**self.get_dummy_inputs(__A ) ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = pipe( **self.get_dummy_inputs(__A ) , return_dict=__A , )[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = image_from_tuple[0, -3:, -3:, -1] print(f'''image.shape {image.shape}''' ) assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ = np.array( [0.8_3_2_6_9_1_9, 0.7_3_7_9_0_4_6_7, 0.2_0_9_1_8_5_8_1, 0.9_3_0_9_6_1_2, 0.5_5_1_1_7_9_1, 0.4_3_7_1_3_3_2_8, 0.5_5_1_3_3_2_1, 0.4_9_9_2_2_9_3_4, 0.5_9_4_9_7_7_8_6] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' def _snake_case ( self :Dict ) -> str: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy""" ) SCREAMING_SNAKE_CASE__ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) SCREAMING_SNAKE_CASE__ = np.ones((768, 768) , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = """a hat""" SCREAMING_SNAKE_CASE__ = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(__A ) SCREAMING_SNAKE_CASE__ = KandinskyInpaintPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-inpaint""" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ = pipeline.to(__A ) pipeline.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = pipe_prior( __A , generator=__A , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() SCREAMING_SNAKE_CASE__ = pipeline( __A , image=__A , mask_image=__A , image_embeds=__A , negative_image_embeds=__A , generator=__A , num_inference_steps=100 , height=768 , width=768 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__A , __A )
721
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
59
0
import argparse import glob import logging import os import sys import time from collections import defaultdict from pathlib import Path from typing import Dict, List, Tuple import numpy as np import pytorch_lightning as pl import torch from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback from torch import nn from torch.utils.data import DataLoader from transformers import MBartTokenizer, TaForConditionalGeneration from transformers.models.bart.modeling_bart import shift_tokens_right from utils import ( ROUGE_KEYS, LegacySeqaSeqDataset, SeqaSeqDataset, assert_all_frozen, calculate_bleu, calculate_rouge, check_output_dir, flatten_list, freeze_embeds, freeze_params, get_git_info, label_smoothed_nll_loss, lmap, pickle_save, save_git_info, save_json, use_task_specific_params, ) # need the parent dir module sys.path.insert(2, str(Path(__file__).resolve().parents[1])) from lightning_base import BaseTransformer, add_generic_args, generic_train # noqa __snake_case :str = logging.getLogger(__name__) class _A ( __UpperCAmelCase ): UpperCamelCase__ : Union[str, Any] = '''summarization''' UpperCamelCase__ : List[Any] = ['''loss'''] UpperCamelCase__ : str = ROUGE_KEYS UpperCamelCase__ : List[str] = '''rouge2''' def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : Dict , **__SCREAMING_SNAKE_CASE : Any): '''simple docstring''' if hparams.sortish_sampler and hparams.gpus > 1: __a = False elif hparams.max_tokens_per_batch is not None: if hparams.gpus > 1: raise NotImplementedError('''Dynamic Batch size does not work for multi-gpu training''') if hparams.sortish_sampler: raise ValueError('''--sortish_sampler and --max_tokens_per_batch may not be used simultaneously''') super().__init__(__SCREAMING_SNAKE_CASE , num_labels=__SCREAMING_SNAKE_CASE , mode=self.mode , **__SCREAMING_SNAKE_CASE) use_task_specific_params(self.model , '''summarization''') save_git_info(self.hparams.output_dir) __a = Path(self.output_dir) / '''metrics.json''' __a = Path(self.output_dir) / '''hparams.pkl''' pickle_save(self.hparams , self.hparams_save_path) __a = 0 __a = defaultdict(__SCREAMING_SNAKE_CASE) __a = self.config.model_type __a = self.config.tgt_vocab_size if self.model_type == '''fsmt''' else self.config.vocab_size __a = { "data_dir": self.hparams.data_dir, "max_source_length": self.hparams.max_source_length, "prefix": self.model.config.prefix or "", } __a = { '''train''': self.hparams.n_train, '''val''': self.hparams.n_val, '''test''': self.hparams.n_test, } __a = {k: v if v >= 0 else None for k, v in n_observations_per_split.items()} __a = { '''train''': self.hparams.max_target_length, '''val''': self.hparams.val_max_target_length, '''test''': self.hparams.test_max_target_length, } assert self.target_lens["train"] <= self.target_lens["val"], F'target_lens: {self.target_lens}' assert self.target_lens["train"] <= self.target_lens["test"], F'target_lens: {self.target_lens}' if self.hparams.freeze_embeds: freeze_embeds(self.model) if self.hparams.freeze_encoder: freeze_params(self.model.get_encoder()) assert_all_frozen(self.model.get_encoder()) __a = get_git_info()['''repo_sha'''] __a = hparams.num_workers __a = None # default to config if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer , __SCREAMING_SNAKE_CASE): __a = self.tokenizer.lang_code_to_id[hparams.tgt_lang] __a = self.decoder_start_token_id __a = ( SeqaSeqDataset if hasattr(self.tokenizer , '''prepare_seq2seq_batch''') else LegacySeqaSeqDataset ) __a = False __a = self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams if self.hparams.eval_max_gen_length is not None: __a = self.hparams.eval_max_gen_length else: __a = self.model.config.max_length __a = self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric def _lowerCamelCase ( self : List[str] , __SCREAMING_SNAKE_CASE : Dict[str, torch.Tensor]): '''simple docstring''' __a = { k: self.tokenizer.batch_decode(v.tolist()) if '''mask''' not in k else v.shape for k, v in batch.items() } save_json(__SCREAMING_SNAKE_CASE , Path(self.output_dir) / '''text_batch.json''') save_json({k: v.tolist() for k, v in batch.items()} , Path(self.output_dir) / '''tok_batch.json''') __a = True return readable_batch def _lowerCamelCase ( self : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any] , **__SCREAMING_SNAKE_CASE : List[str]): '''simple docstring''' return self.model(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : str , __SCREAMING_SNAKE_CASE : List[int]): '''simple docstring''' __a = self.tokenizer.batch_decode( __SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE) return lmap(str.strip , __SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : int , __SCREAMING_SNAKE_CASE : dict): '''simple docstring''' __a = self.tokenizer.pad_token_id __a , __a = batch['''input_ids'''], batch['''attention_mask'''] __a = batch['''labels'''] if isinstance(self.model , __SCREAMING_SNAKE_CASE): __a = self.model._shift_right(__SCREAMING_SNAKE_CASE) else: __a = shift_tokens_right(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) if not self.already_saved_batch: # This would be slightly better if it only happened on rank zero __a = decoder_input_ids self.save_readable_batch(__SCREAMING_SNAKE_CASE) __a = self(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , decoder_input_ids=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE) __a = outputs['''logits'''] if self.hparams.label_smoothing == 0: # Same behavior as modeling_bart.py, besides ignoring pad_token_id __a = nn.CrossEntropyLoss(ignore_index=__SCREAMING_SNAKE_CASE) assert lm_logits.shape[-1] == self.vocab_size __a = ce_loss_fct(lm_logits.view(-1 , lm_logits.shape[-1]) , tgt_ids.view(-1)) else: __a = nn.functional.log_softmax(__SCREAMING_SNAKE_CASE , dim=-1) __a , __a = label_smoothed_nll_loss( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , self.hparams.label_smoothing , ignore_index=__SCREAMING_SNAKE_CASE) return (loss,) @property def _lowerCamelCase ( self : Optional[int]): '''simple docstring''' return self.tokenizer.pad_token_id def _lowerCamelCase ( self : Any , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[Any]): '''simple docstring''' __a = self._step(__SCREAMING_SNAKE_CASE) __a = dict(zip(self.loss_names , __SCREAMING_SNAKE_CASE)) # tokens per batch __a = batch['''input_ids'''].ne(self.pad).sum() + batch['''labels'''].ne(self.pad).sum() __a = batch['''input_ids'''].shape[0] __a = batch['''input_ids'''].eq(self.pad).sum() __a = batch['''input_ids'''].eq(self.pad).float().mean() # TODO(SS): make a wandb summary metric for this return {"loss": loss_tensors[0], "log": logs} def _lowerCamelCase ( self : int , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Union[str, Any]): '''simple docstring''' return self._generative_step(__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Dict , __SCREAMING_SNAKE_CASE : List[str] , __SCREAMING_SNAKE_CASE : Optional[Any]="val"): '''simple docstring''' self.step_count += 1 __a = {k: torch.stack([x[k] for x in outputs]).mean() for k in self.loss_names} __a = losses['''loss'''] __a = { k: np.array([x[k] for x in outputs]).mean() for k in self.metric_names + ['''gen_time''', '''gen_len'''] } __a = ( generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric] ) __a = torch.tensor(__SCREAMING_SNAKE_CASE).type_as(__SCREAMING_SNAKE_CASE) generative_metrics.update({k: v.item() for k, v in losses.items()}) losses.update(__SCREAMING_SNAKE_CASE) __a = {F'{prefix}_avg_{k}': x for k, x in losses.items()} __a = self.step_count self.metrics[prefix].append(__SCREAMING_SNAKE_CASE) # callback writes this to self.metrics_save_path __a = flatten_list([x['''preds'''] for x in outputs]) return { "log": all_metrics, "preds": preds, F'{prefix}_loss': loss, F'{prefix}_{self.val_metric}': metric_tensor, } def _lowerCamelCase ( self : List[Any] , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Dict): '''simple docstring''' return calculate_rouge(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Any , __SCREAMING_SNAKE_CASE : dict): '''simple docstring''' __a = time.time() # parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens') __a = self.model.generate( batch['''input_ids'''] , attention_mask=batch['''attention_mask'''] , use_cache=__SCREAMING_SNAKE_CASE , decoder_start_token_id=self.decoder_start_token_id , num_beams=self.eval_beams , max_length=self.eval_max_length , ) __a = (time.time() - ta) / batch['''input_ids'''].shape[0] __a = self.ids_to_clean_text(__SCREAMING_SNAKE_CASE) __a = self.ids_to_clean_text(batch['''labels''']) __a = self._step(__SCREAMING_SNAKE_CASE) __a = dict(zip(self.loss_names , __SCREAMING_SNAKE_CASE)) __a = self.calc_generative_metrics(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) __a = np.mean(lmap(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE)) base_metrics.update(gen_time=__SCREAMING_SNAKE_CASE , gen_len=__SCREAMING_SNAKE_CASE , preds=__SCREAMING_SNAKE_CASE , target=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) return base_metrics def _lowerCamelCase ( self : int , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Dict): '''simple docstring''' return self._generative_step(__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any]): '''simple docstring''' return self.validation_epoch_end(__SCREAMING_SNAKE_CASE , prefix='''test''') def _lowerCamelCase ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[str]): '''simple docstring''' __a = self.n_obs[type_path] __a = self.target_lens[type_path] __a = self.dataset_class( self.tokenizer , type_path=__SCREAMING_SNAKE_CASE , n_obs=__SCREAMING_SNAKE_CASE , max_target_length=__SCREAMING_SNAKE_CASE , **self.dataset_kwargs , ) return dataset def _lowerCamelCase ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : bool = False): '''simple docstring''' __a = self.get_dataset(__SCREAMING_SNAKE_CASE) if self.hparams.sortish_sampler and type_path != "test" and type_path != "val": __a = dataset.make_sortish_sampler(__SCREAMING_SNAKE_CASE , distributed=self.hparams.gpus > 1) return DataLoader( __SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , shuffle=__SCREAMING_SNAKE_CASE , num_workers=self.num_workers , sampler=__SCREAMING_SNAKE_CASE , ) elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val": __a = dataset.make_dynamic_sampler( self.hparams.max_tokens_per_batch , distributed=self.hparams.gpus > 1) return DataLoader( __SCREAMING_SNAKE_CASE , batch_sampler=__SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , num_workers=self.num_workers , ) else: return DataLoader( __SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , collate_fn=dataset.collate_fn , shuffle=__SCREAMING_SNAKE_CASE , num_workers=self.num_workers , sampler=__SCREAMING_SNAKE_CASE , ) def _lowerCamelCase ( self : int): '''simple docstring''' __a = self.get_dataloader('''train''' , batch_size=self.hparams.train_batch_size , shuffle=__SCREAMING_SNAKE_CASE) return dataloader def _lowerCamelCase ( self : int): '''simple docstring''' return self.get_dataloader('''val''' , batch_size=self.hparams.eval_batch_size) def _lowerCamelCase ( self : int): '''simple docstring''' return self.get_dataloader('''test''' , batch_size=self.hparams.eval_batch_size) @staticmethod def _lowerCamelCase ( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : List[Any]): '''simple docstring''' BaseTransformer.add_model_specific_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) add_generic_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) parser.add_argument( '''--max_source_length''' , default=1_024 , type=__SCREAMING_SNAKE_CASE , help=( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) , ) parser.add_argument( '''--max_target_length''' , default=56 , type=__SCREAMING_SNAKE_CASE , help=( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) , ) parser.add_argument( '''--val_max_target_length''' , default=142 , type=__SCREAMING_SNAKE_CASE , help=( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) , ) parser.add_argument( '''--test_max_target_length''' , default=142 , type=__SCREAMING_SNAKE_CASE , help=( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) , ) parser.add_argument('''--freeze_encoder''' , action='''store_true''') parser.add_argument('''--freeze_embeds''' , action='''store_true''') parser.add_argument('''--sortish_sampler''' , action='''store_true''' , default=__SCREAMING_SNAKE_CASE) parser.add_argument('''--overwrite_output_dir''' , action='''store_true''' , default=__SCREAMING_SNAKE_CASE) parser.add_argument('''--max_tokens_per_batch''' , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE) parser.add_argument('''--logger_name''' , type=__SCREAMING_SNAKE_CASE , choices=['''default''', '''wandb''', '''wandb_shared'''] , default='''default''') parser.add_argument('''--n_train''' , type=__SCREAMING_SNAKE_CASE , default=-1 , required=__SCREAMING_SNAKE_CASE , help='''# examples. -1 means use all.''') parser.add_argument('''--n_val''' , type=__SCREAMING_SNAKE_CASE , default=500 , required=__SCREAMING_SNAKE_CASE , help='''# examples. -1 means use all.''') parser.add_argument('''--n_test''' , type=__SCREAMING_SNAKE_CASE , default=-1 , required=__SCREAMING_SNAKE_CASE , help='''# examples. -1 means use all.''') parser.add_argument( '''--task''' , type=__SCREAMING_SNAKE_CASE , default='''summarization''' , required=__SCREAMING_SNAKE_CASE , help='''# examples. -1 means use all.''') parser.add_argument('''--label_smoothing''' , type=__SCREAMING_SNAKE_CASE , default=0.0 , required=__SCREAMING_SNAKE_CASE) parser.add_argument('''--src_lang''' , type=__SCREAMING_SNAKE_CASE , default='''''' , required=__SCREAMING_SNAKE_CASE) parser.add_argument('''--tgt_lang''' , type=__SCREAMING_SNAKE_CASE , default='''''' , required=__SCREAMING_SNAKE_CASE) parser.add_argument('''--eval_beams''' , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE) parser.add_argument( '''--val_metric''' , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , choices=['''bleu''', '''rouge2''', '''loss''', None]) parser.add_argument('''--eval_max_gen_length''' , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help='''never generate more than n tokens''') parser.add_argument('''--save_top_k''' , type=__SCREAMING_SNAKE_CASE , default=1 , required=__SCREAMING_SNAKE_CASE , help='''How many checkpoints to save''') parser.add_argument( '''--early_stopping_patience''' , type=__SCREAMING_SNAKE_CASE , default=-1 , required=__SCREAMING_SNAKE_CASE , help=( '''-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So''' ''' val_check_interval will effect it.''' ) , ) return parser class _A ( __UpperCAmelCase ): UpperCamelCase__ : Union[str, Any] = '''translation''' UpperCamelCase__ : int = ['''loss'''] UpperCamelCase__ : Optional[Any] = ['''bleu'''] UpperCamelCase__ : Union[str, Any] = '''bleu''' def __init__( self : int , __SCREAMING_SNAKE_CASE : List[Any] , **__SCREAMING_SNAKE_CASE : List[Any]): '''simple docstring''' super().__init__(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) __a = hparams.src_lang __a = hparams.tgt_lang def _lowerCamelCase ( self : int , __SCREAMING_SNAKE_CASE : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[int]): '''simple docstring''' return calculate_bleu(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) def __snake_case ( _UpperCAmelCase , _UpperCAmelCase=None ): Path(args.output_dir ).mkdir(exist_ok=_UpperCAmelCase ) check_output_dir(_UpperCAmelCase , expected_items=3 ) if model is None: if "summarization" in args.task: __a = SummarizationModule(_UpperCAmelCase ) else: __a = TranslationModule(_UpperCAmelCase ) __a = Path(args.data_dir ).name if ( args.logger_name == "default" or args.fast_dev_run or str(args.output_dir ).startswith('''/tmp''' ) or str(args.output_dir ).startswith('''/var''' ) ): __a = True # don't pollute wandb logs unnecessarily elif args.logger_name == "wandb": from pytorch_lightning.loggers import WandbLogger __a = os.environ.get('''WANDB_PROJECT''' , _UpperCAmelCase ) __a = WandbLogger(name=model.output_dir.name , project=_UpperCAmelCase ) elif args.logger_name == "wandb_shared": from pytorch_lightning.loggers import WandbLogger __a = WandbLogger(name=model.output_dir.name , project=f'hf_{dataset}' ) if args.early_stopping_patience >= 0: __a = get_early_stopping_callback(model.val_metric , args.early_stopping_patience ) else: __a = False __a = args.val_metric == '''loss''' __a = generic_train( _UpperCAmelCase , _UpperCAmelCase , logging_callback=SeqaSeqLoggingCallback() , checkpoint_callback=get_checkpoint_callback( args.output_dir , model.val_metric , args.save_top_k , _UpperCAmelCase ) , early_stopping_callback=_UpperCAmelCase , logger=_UpperCAmelCase , ) pickle_save(model.hparams , model.output_dir / '''hparams.pkl''' ) if not args.do_predict: return model __a = '''''' __a = sorted(glob.glob(os.path.join(args.output_dir , '''*.ckpt''' ) , recursive=_UpperCAmelCase ) ) if checkpoints: __a = checkpoints[-1] __a = checkpoints[-1] trainer.logger.log_hyperparams(model.hparams ) # test() without a model tests using the best checkpoint automatically trainer.test() return model if __name__ == "__main__": __snake_case :Optional[int] = argparse.ArgumentParser() __snake_case :Any = pl.Trainer.add_argparse_args(parser) __snake_case :Dict = SummarizationModule.add_model_specific_args(parser, os.getcwd()) __snake_case :Dict = parser.parse_args() main(args)
60
def __snake_case ( _UpperCAmelCase ): __a = '''''' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def __snake_case ( _UpperCAmelCase ): __a = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key __a = remove_duplicates(key.upper() ) __a = len(_UpperCAmelCase ) # First fill cipher with key characters __a = {alphabet[i]: char for i, char in enumerate(_UpperCAmelCase )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(_UpperCAmelCase ) , 26 ): __a = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 __a = alphabet[i - offset] __a = char return cipher_alphabet def __snake_case ( _UpperCAmelCase , _UpperCAmelCase ): return "".join(cipher_map.get(_UpperCAmelCase , _UpperCAmelCase ) for ch in message.upper() ) def __snake_case ( _UpperCAmelCase , _UpperCAmelCase ): __a = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(_UpperCAmelCase , _UpperCAmelCase ) for ch in message.upper() ) def __snake_case ( ): __a = input('''Enter message to encode or decode: ''' ).strip() __a = input('''Enter keyword: ''' ).strip() __a = input('''Encipher or decipher? E/D:''' ).strip()[0].lower() try: __a = {'''e''': encipher, '''d''': decipher}[option] except KeyError: raise KeyError('''invalid input option''' ) __a = create_cipher_map(_UpperCAmelCase ) print(func(_UpperCAmelCase , _UpperCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
60
1