code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" from __future__ import annotations def _A ( lowercase , lowercase ): """simple docstring""" if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number_of_bytes!''' ) a =number_of_bytes // partitions a =[] for i in range(lowercase ): a =i * bytes_per_partition + 1 a =( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
81
"""simple docstring""" import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Any: 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 SCREAMING_SNAKE_CASE ( self ) -> str: self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_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]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =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 ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
1
"""simple docstring""" import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = TransfoXLTokenizer __lowerCAmelCase = False __lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self ) -> int: super().setUp() a =[ '''<unk>''', '''[CLS]''', '''[SEP]''', '''want''', '''unwanted''', '''wa''', '''un''', '''running''', ''',''', '''low''', '''l''', ] a =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self , **__A ) -> List[Any]: a =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Any: a ='''<unk> UNwanted , running''' a ='''<unk> unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=__A ) a =tokenizer.tokenize('''<unk> UNwanted , running''' ) self.assertListEqual(__A , ['''<unk>''', '''unwanted''', ''',''', '''running'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [0, 4, 8, 7] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =TransfoXLTokenizer(lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =TransfoXLTokenizer(lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =TransfoXLTokenizer(lower_case=__A ) a ='''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?''' a =[ '''Hello''', '''(''', '''bracket''', ''')''', '''and''', '''side''', '''@-@''', '''scrolled''', '''[''', '''and''', ''']''', '''Henry''', '''\'s''', '''$''', '''5''', '''@,@''', '''000''', '''with''', '''3''', '''@.@''', '''34''', '''m''', '''.''', '''What''', '''\'s''', '''up''', '''!''', '''?''', ] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) self.assertEqual(tokenizer.convert_tokens_to_string(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =self.get_tokenizer() a =len(__A ) tokenizer.add_tokens(['''new1''', '''new2'''] ) tokenizer.move_added_token('''new1''' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(__A ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('''new1''' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
81
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : str = { """configuration_trajectory_transformer""": [ """TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrajectoryTransformerConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[str] = [ """TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TrajectoryTransformerModel""", """TrajectoryTransformerPreTrainedModel""", """load_tf_weights_in_trajectory_transformer""", ] if TYPE_CHECKING: from .configuration_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TrajectoryTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TrajectoryTransformerModel, TrajectoryTransformerPreTrainedModel, load_tf_weights_in_trajectory_transformer, ) else: import sys lowerCamelCase_ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" while second != 0: a =first & second first ^= second a =c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Dict = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : List[Any] = int(input("""Enter the second number: """).strip()) print(F'{add(first, second) = }')
81
1
"""simple docstring""" import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate lowerCamelCase_ : Optional[Any] = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow("""""", """|""", """|"""), datarow=DataRow("""""", """|""", """|"""), padding=1, with_header_hide=None, ) lowerCamelCase_ : List[Any] = [] lowerCamelCase_ : Optional[Any] = [] lowerCamelCase_ : Optional[Any] = {"""type""": """section""", """text""": {"""type""": """plain_text""", """text""": """No failed tests! 🤗""", """emoji""": True}} lowerCamelCase_ : Dict = [ { """type""": """header""", """text""": { """type""": """plain_text""", """text""": F'🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results', """emoji""": True, }, } ] lowerCamelCase_ : List[Any] = 0 for log in Path().glob("""*.log"""): lowerCamelCase_ : List[Any] = 0 with open(log, """r""") as f: for line in f: lowerCamelCase_ : List[Any] = json.loads(line) if line.get("""nodeid""", """""") != "": lowerCamelCase_ : Any = line["""nodeid"""] if line.get("""duration""", None) is not None: lowerCamelCase_ : List[Any] = F'{line["duration"]:.4f}' if line.get("""outcome""", """""") == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split("""_""")[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) lowerCamelCase_ : List[str] = [] log.unlink() lowerCamelCase_ : List[Any] = """""" lowerCamelCase_ : List[Any] = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += F"*{name[1:]}: {num_failed} failed test*\n" else: message += F"*{name[1:]}: {num_failed} failed tests*\n" lowerCamelCase_ : Optional[Any] = [] lowerCamelCase_ : Optional[int] = {} for test in failed_tests: lowerCamelCase_ : Union[str, Any] = test[0].split("""::""") lowerCamelCase_ : Union[str, Any] = data[0].split("""/""")[-1] if data[0] not in filesafailed: lowerCamelCase_ : str = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) lowerCamelCase_ : Optional[Any] = [test[0] for test in failed_table] lowerCamelCase_ : str = list(set(files)) # Count number of instances in failed_tests lowerCamelCase_ : int = [] for file in individual_files: table.append([file, len(filesafailed[file])]) lowerCamelCase_ : str = tabulate( table, headers=["""Test Location""", """Num Failed"""], tablefmt=hf_table_format, stralign="""right""", ) message += F"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3_0_0_0: lowerCamelCase_ : int = """Too many failed tests, please see the full report in the Action results.""" lowerCamelCase_ : str = len(err) + 1_0 lowerCamelCase_ : Optional[Any] = message[: 3_0_0_0 - offset] + F'\n...\n```\n{err}' print(F'### {message}') else: lowerCamelCase_ : Optional[Any] = """No failed tests! 🤗""" print(F'## {message}') payload.append(no_error_payload) if os.environ.get("""TEST_TYPE""", """""") != "": from slack_sdk import WebClient lowerCamelCase_ : List[Any] = WebClient(token=os.environ["""SLACK_API_TOKEN"""]) if message != "No failed tests! 🤗": lowerCamelCase_ : Any = { """type""": """section""", """text""": { """type""": """mrkdwn""", """text""": message, }, } payload.append(md_report) lowerCamelCase_ : Dict = { """type""": """section""", """text""": { """type""": """mrkdwn""", """text""": """*For more details:*""", }, """accessory""": { """type""": """button""", """text""": { """type""": """plain_text""", """text""": """Check Action results""", """emoji""": True, }, """url""": F'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } payload.append(action_button) lowerCamelCase_ : Optional[Any] = { """type""": """context""", """elements""": [ { """type""": """plain_text""", """text""": F'Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}', } ], } payload.append(date_report) lowerCamelCase_ : Optional[int] = client.chat_postMessage(channel="""#accelerate-ci-daily""", text=message, blocks=payload) lowerCamelCase_ : Union[str, Any] = response.data["""ts"""] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name lowerCamelCase_ : int = """""" for i, row in enumerate(test_failures): if row[0] != test_class: lowerCamelCase_ : str = row[0] else: lowerCamelCase_ : str = """""" lowerCamelCase_ : Dict = { """type""": """section""", """text""": { """type""": """mrkdwn""", """text""": F'Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```', }, } client.chat_postMessage( channel="""#accelerate-ci-daily""", thread_ts=ts, blocks=[payload], )
81
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
1
"""simple docstring""" import numpy as np def _A ( lowercase ): """simple docstring""" return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
81
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCamelCase_ : str = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *__A , **__A ) -> None: warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , __A , ) super().__init__(*__A , **__A )
81
1
"""simple docstring""" import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup lowerCamelCase_ : List[str] = { """User-Agent""": """Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36""" """ (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582""" } def _A ( lowercase = "dhaka" , lowercase = 5 ): """simple docstring""" a =min(lowercase , 50 ) # Prevent abuse! a ={ '''q''': query, '''tbm''': '''isch''', '''hl''': '''en''', '''ijn''': '''0''', } a =requests.get('''https://www.google.com/search''' , params=lowercase , headers=lowercase ) a =BeautifulSoup(html.text , '''html.parser''' ) a =''''''.join( re.findall(R'''AF_initDataCallback\(([^<]+)\);''' , str(soup.select('''script''' ) ) ) ) a =json.dumps(lowercase ) a =json.loads(lowercase ) a =re.findall( R'''\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",''' , lowercase , ) if not matched_google_image_data: return 0 a =re.sub( R'''\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]''' , '''''' , str(lowercase ) , ) a =re.findall( R'''(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]''' , lowercase , ) for index, fixed_full_res_image in enumerate(lowercase ): if index >= max_images: return index a =bytes(lowercase , '''ascii''' ).decode( '''unicode-escape''' ) a =bytes(lowercase , '''ascii''' ).decode( '''unicode-escape''' ) a =urllib.request.build_opener() a =[ ( '''User-Agent''', '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36''' ''' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582''', ) ] urllib.request.install_opener(lowercase ) a =f'''query_{query.replace(" " , "_" )}''' if not os.path.exists(lowercase ): os.makedirs(lowercase ) urllib.request.urlretrieve( # noqa: S310 lowercase , f'''{path_name}/original_size_img_{index}.jpg''' ) return index if __name__ == "__main__": try: lowerCamelCase_ : List[str] = download_images_from_google_query(sys.argv[1]) print(F'{image_count} images were downloaded to disk.') except IndexError: print("""Please provide a search term.""") raise
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = """▁""" lowerCamelCase_ : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : Any = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowerCamelCase_ : Tuple = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} 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 , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a =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 a ={'''<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 a =1 a =len(self.sp_model ) + self.fairseq_offset a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: a =self.__dict__.copy() a =None a =self.sp_model.serialized_model_proto() return state def __setstate__( self , __A ) -> List[Any]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =''''''.join(__A ).replace(__A , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =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: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
1
"""simple docstring""" import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert import BertTokenizer lowerCamelCase_ : List[Any] = logging.get_logger(__name__) lowerCamelCase_ : Dict = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase_ : int = { """vocab_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-ctx_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-ctx_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCamelCase_ : Optional[Any] = { """vocab_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-question_encoder-single-nq-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-question_encoder-multiset-base""": ( """https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCamelCase_ : Tuple = { """vocab_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """facebook/dpr-reader-single-nq-base""": ( """https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json""" ), """facebook/dpr-reader-multiset-base""": ( """https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json""" ), }, } lowerCamelCase_ : Optional[Any] = { """facebook/dpr-ctx_encoder-single-nq-base""": 5_1_2, """facebook/dpr-ctx_encoder-multiset-base""": 5_1_2, } lowerCamelCase_ : Optional[Any] = { """facebook/dpr-question_encoder-single-nq-base""": 5_1_2, """facebook/dpr-question_encoder-multiset-base""": 5_1_2, } lowerCamelCase_ : Dict = { """facebook/dpr-reader-single-nq-base""": 5_1_2, """facebook/dpr-reader-multiset-base""": 5_1_2, } lowerCamelCase_ : Any = { """facebook/dpr-ctx_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-ctx_encoder-multiset-base""": {"""do_lower_case""": True}, } lowerCamelCase_ : List[Any] = { """facebook/dpr-question_encoder-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-question_encoder-multiset-base""": {"""do_lower_case""": True}, } lowerCamelCase_ : int = { """facebook/dpr-reader-single-nq-base""": {"""do_lower_case""": True}, """facebook/dpr-reader-multiset-base""": {"""do_lower_case""": True}, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION lowerCamelCase_ : str = collections.namedtuple( """DPRSpanPrediction""", ["""span_score""", """relevance_score""", """doc_id""", """start_index""", """end_index""", """text"""] ) lowerCamelCase_ : Any = collections.namedtuple("""DPRReaderOutput""", ["""start_logits""", """end_logits""", """relevance_logits"""]) lowerCamelCase_ : Union[str, Any] = R""" Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`. It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers), using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)` with the format: ``` [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids> ``` Args: questions (`str` or `List[str]`): The questions to be encoded. You can specify one question for many passages. In this case, the question will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in `titles` or `texts`. titles (`str` or `List[str]`): The passages titles to be encoded. This can be a string or a list of strings if there are several passages. texts (`str` or `List[str]`): The passages texts to be encoded. This can be a string or a list of strings if there are several passages. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Activates and controls padding. Accepts the following values: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`): Activates and controls truncation. Accepts the following values: - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max_length (`int`, *optional*): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors instead of list of python integers. Acceptable values are: - `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. return_attention_mask (`bool`, *optional*): Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer's default, defined by the `return_outputs` attribute. [What are attention masks?](../glossary#attention-mask) Returns: `Dict[str, List[List[int]]]`: A dictionary with the following keys: - `input_ids`: List of token ids to be fed to a model. - `attention_mask`: List of indices specifying which tokens should be attended to by the model. """ @add_start_docstrings(_SCREAMING_SNAKE_CASE ) class __A : """simple docstring""" def __call__( self , __A , __A = None , __A = None , __A = False , __A = False , __A = None , __A = None , __A = None , **__A , ) -> BatchEncoding: if titles is None and texts is None: return super().__call__( __A , padding=__A , truncation=__A , max_length=__A , return_tensors=__A , return_attention_mask=__A , **__A , ) elif titles is None or texts is None: a =titles if texts is None else texts return super().__call__( __A , __A , padding=__A , truncation=__A , max_length=__A , return_tensors=__A , return_attention_mask=__A , **__A , ) a =titles if not isinstance(__A , __A ) else [titles] a =texts if not isinstance(__A , __A ) else [texts] a =len(__A ) a =questions if not isinstance(__A , __A ) else [questions] * n_passages if len(__A ) != len(__A ): raise ValueError( f'''There should be as many titles than texts but got {len(__A )} titles and {len(__A )} texts.''' ) a =super().__call__(__A , __A , padding=__A , truncation=__A )['''input_ids'''] a =super().__call__(__A , add_special_tokens=__A , padding=__A , truncation=__A )['''input_ids'''] a ={ '''input_ids''': [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(__A , __A ) ] } if return_attention_mask is not False: a =[] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) a =attention_mask return self.pad(__A , padding=__A , max_length=__A , return_tensors=__A ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A = 16 , __A = 64 , __A = 4 , ) -> List[DPRSpanPrediction]: a =reader_input['''input_ids'''] a , a , a =reader_output[:3] a =len(__A ) a =sorted(range(__A ) , reverse=__A , key=relevance_logits.__getitem__ ) a =[] for doc_id in sorted_docs: a =list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence a =sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: a =sequence_ids.index(self.pad_token_id ) else: a =len(__A ) a =self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=__A , top_spans=__A , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=__A , start_index=__A , end_index=__A , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(__A ) >= num_spans: break return nbest_spans_predictions[:num_spans] def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , ) -> List[DPRSpanPrediction]: a =[] for start_index, start_score in enumerate(__A ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) a =sorted(__A , key=lambda __A : x[1] , reverse=__A ) a =[] for (start_index, end_index), score in scores: if start_index > end_index: raise ValueError(f'''Wrong span indices: [{start_index}:{end_index}]''' ) a =end_index - start_index + 1 if length > max_answer_length: raise ValueError(f'''Span is too long: {length} > {max_answer_length}''' ) if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(__A ) == top_spans: break return chosen_span_intervals @add_end_docstrings(_SCREAMING_SNAKE_CASE ) class __A ( _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = READER_PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = READER_PRETRAINED_INIT_CONFIGURATION __lowerCAmelCase = ["input_ids", "attention_mask"]
81
"""simple docstring""" lowerCamelCase_ : Any = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
81
1
"""simple docstring""" def _A ( lowercase ): """simple docstring""" return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') ) def _A ( lowercase ): """simple docstring""" a =credit_card_number a =0 a =len(lowercase ) - 2 for i in range(lowercase , -1 , -2 ): # double the value of every second digit a =int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 a =cc_number[:i] + str(lowercase ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(lowercase ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def _A ( lowercase ): """simple docstring""" a =f'''{credit_card_number} is an invalid credit card number because''' if not credit_card_number.isdigit(): print(f'''{error_message} it has nonnumerical characters.''' ) return False if not 13 <= len(lowercase ) <= 16: print(f'''{error_message} of its length.''' ) return False if not validate_initial_digits(lowercase ): print(f'''{error_message} of its first two digits.''' ) return False if not luhn_validation(lowercase ): print(f'''{error_message} it fails the Luhn check.''' ) return False print(f'''{credit_card_number} is a valid credit card number.''' ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number("""4111111111111111""") validate_credit_card_number("""32323""")
81
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ lowerCamelCase_ : Optional[Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ lowerCamelCase_ : Optional[int] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Optional[Any]: if return_pvalue: a =pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
81
1
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" if mass < 0: raise ValueError('''The mass of a body cannot be negative''' ) return 0.5 * mass * abs(lowercase ) * abs(lowercase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
81
"""simple docstring""" lowerCamelCase_ : int = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Union[str, Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = { """distilbert-base-uncased""": """https://huggingface.co/distilbert-base-uncased/resolve/main/config.json""", """distilbert-base-uncased-distilled-squad""": ( """https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json""" ), """distilbert-base-cased""": """https://huggingface.co/distilbert-base-cased/resolve/main/config.json""", """distilbert-base-cased-distilled-squad""": ( """https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json""" ), """distilbert-base-german-cased""": """https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json""", """distilbert-base-multilingual-cased""": ( """https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json""" ), """distilbert-base-uncased-finetuned-sst-2-english""": ( """https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "distilbert" __lowerCAmelCase = { "hidden_size": "dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", } def __init__( self , __A=3_0522 , __A=512 , __A=False , __A=6 , __A=12 , __A=768 , __A=4 * 768 , __A=0.1 , __A=0.1 , __A="gelu" , __A=0.02 , __A=0.1 , __A=0.2 , __A=0 , **__A , ) -> List[Any]: a =vocab_size a =max_position_embeddings a =sinusoidal_pos_embds a =n_layers a =n_heads a =dim a =hidden_dim a =dropout a =attention_dropout a =activation a =initializer_range a =qa_dropout a =seq_classif_dropout super().__init__(**__A , pad_token_id=__A ) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a ={0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: a ={0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
81
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowerCamelCase_ : int = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[int] = ["""GPTSw3Tokenizer"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys lowerCamelCase_ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" def _A ( lowercase ): """simple docstring""" if n_term == "": return [] a =[] for temp in range(int(lowercase ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowerCamelCase_ : Union[str, Any] = input("""Enter the last number (nth term) of the Harmonic Series""") print("""Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n""") print(harmonic_series(nth_term))
81
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy lowerCamelCase_ : Dict = logging.getLogger(__name__) lowerCamelCase_ : Tuple = """pytorch_model.bin""" @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}, ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "A csv or a json file containing the validation data."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The name of the task to train on."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) __lowerCAmelCase = dataclasses.field( default="accuracy", metadata={"help": "The evaluation metric used for the task."} ) __lowerCAmelCase = dataclasses.field( default="no", metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" }, ) __lowerCAmelCase = dataclasses.field( default=10, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." }, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}, ) __lowerCAmelCase = dataclasses.field( default=100, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Random seed for initialization."}, ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a =dataset.filter(lambda lowercase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a =int(eval_result * len(lowercase ) ) print(lowercase ) a =dataset.sort('''probability''' , reverse=lowercase ) a =dataset.select(range(lowercase ) ) a =dataset.remove_columns(['''label''', '''probability'''] ) a =dataset.rename_column('''prediction''' , '''label''' ) a =dataset.map(lambda lowercase : {"label": idalabel[example["label"]]} ) a =dataset.shuffle(seed=args.seed ) a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase , index=lowercase ) else: dataset.to_json(lowercase ) def _A ( lowercase , lowercase , lowercase , lowercase , **lowercase ): """simple docstring""" a =Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() a =STModelArguments(model_name_or_path=lowercase ) a =STDataArguments(train_file=lowercase , infer_file=lowercase ) a =STTrainingArguments(output_dir=lowercase ) a =argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase ).items(): setattr(lowercase , lowercase , lowercase ) for key, value in kwargs.items(): if hasattr(lowercase , lowercase ): setattr(lowercase , lowercase , lowercase ) # Sanity checks a ={} a =None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None a =args.train_file a =args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a =args.eval_file for key in data_files: a =data_files[key].split('''.''' )[-1] assert extension in ["csv", "json"], f'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: a =extension else: assert extension == args.data_file_extension, f'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), f'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info('''Creating the initial data directory for self-training...''' ) a =f'''{args.output_dir}/self-train_iter-{{}}'''.format a =data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) accelerator.wait_for_everyone() a =None a =None a =0 a =False # Show the progress bar a =tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): a =data_dir_format(lowercase ) assert os.path.exists(lowercase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a =os.path.join(lowercase , '''stage-1''' ) a ={ '''accelerator''': accelerator, '''model_name_or_path''': args.model_name_or_path, '''cache_dir''': args.cache_dir, '''do_train''': True, '''train_file''': data_files['''train'''] if iteration == 0 else data_files['''train_pseudo'''], '''do_eval''': True if args.eval_file is not None else False, '''eval_file''': data_files['''eval'''], '''do_predict''': True, '''infer_file''': data_files['''infer'''], '''task_name''': args.task_name, '''label_list''': args.label_list, '''output_dir''': current_output_dir, '''eval_metric''': args.eval_metric, '''evaluation_strategy''': args.evaluation_strategy, '''early_stopping_patience''': args.early_stopping_patience, '''early_stopping_threshold''': args.early_stopping_threshold, '''seed''': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(lowercase , lowercase ): arguments_dict.update({key: value} ) a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , lowercase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a =os.path.join(lowercase , '''best-checkpoint''' ) a =os.path.join(lowercase , '''stage-2''' ) # Update arguments_dict a =model_path a =data_files['''train'''] a =current_output_dir a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , lowercase ) a =iteration a =data_dir_format(iteration + 1 ) a =AutoConfig.from_pretrained(os.path.join(lowercase , '''best-checkpoint''' ) ) a =config.idalabel a =os.path.join(lowercase , '''eval_results_best-checkpoint.json''' ) a =os.path.join(lowercase , '''test_results_best-checkpoint.json''' ) assert os.path.exists(lowercase ) with open(lowercase , '''r''' ) as f: a =float(json.load(lowercase )[args.eval_metric] ) a =os.path.join(lowercase , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(lowercase ) # Loading the dataset from local csv or json files. a =load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )['''data'''] a =load_dataset('''csv''' , data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(lowercase , exist_ok=lowercase ) shutil.copy(lowercase , os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase ): shutil.copy(lowercase , os.path.join(lowercase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) accelerator.wait_for_everyone() a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a =eval_result if best_iteration is None: a =new_iteration a =new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a =new_iteration a =new_eval_result a =0 else: if new_eval_result == best_eval_result: a =new_iteration a =new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a =True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info('''Best iteration: %d''' , lowercase ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , ) else: # Assume that the last iteration is the best logger.info('''Best iteration: %d''' , args.max_selftrain_iterations - 1 ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , )
81
1
"""simple docstring""" 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_ : Optional[int] = """\ Text data. Second line of data.""" lowerCamelCase_ : Optional[int] = """file""" @pytest.fixture(scope='''session''' ) def _A ( lowercase ): """simple docstring""" a =tmp_path_factory.mktemp('''data''' ) / (FILE_PATH + '''.zstd''') a =bytes(lowercase , '''utf-8''' ) with zstd.open(lowercase , '''wb''' ) as f: f.write(lowercase ) return path @pytest.fixture def _A ( lowercase ): """simple docstring""" with open(os.path.join(tmpfs.local_root_dir , lowercase ) , '''w''' ) as f: f.write(lowercase ) return FILE_PATH @pytest.mark.parametrize('''compression_format''' , ['''gzip''', '''xz''', '''zstd'''] ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a ={'''gzip''': gz_file, '''xz''': xz_file, '''zstd''': zstd_path} a =input_paths[compression_format] a =tmp_path / '''cache''' a =DownloadConfig(cache_dir=lowercase , extract_compressed_file=lowercase ) a =cached_path(lowercase , download_config=lowercase ) with open(lowercase ) as f: a =f.read() with open(lowercase ) as f: a =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 _A ( lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a ='''custom_cache''' a ='''custom_extracted_dir''' a =tmp_path / '''custom_extracted_path''' if default_extracted: a =('''downloads''' if default_cache_dir else custom_cache_dir, '''extracted''') else: monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_DIR''' , lowercase ) monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(lowercase ) ) a =custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) a =xz_file a =( DownloadConfig(extract_compressed_file=lowercase ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=lowercase ) ) a =cached_path(lowercase , download_config=lowercase ) assert Path(lowercase ).parent.parts[-2:] == expected def _A ( lowercase ): """simple docstring""" # absolute path a =str(Path(lowercase ).resolve() ) assert cached_path(lowercase ) == text_file # relative path a =str(Path(lowercase ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(lowercase ) == text_file def _A ( lowercase ): """simple docstring""" # absolute path a =str(tmp_path.resolve() / '''__missing_file__.txt''' ) with pytest.raises(lowercase ): cached_path(lowercase ) # relative path a ='''./__missing_file__.txt''' with pytest.raises(lowercase ): cached_path(lowercase ) def _A ( lowercase ): """simple docstring""" a =get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(lowercase ) as f: a =f.read() assert output_file_content == FILE_CONTENT @patch('''datasets.config.HF_DATASETS_OFFLINE''' , lowercase ) def _A ( ): """simple docstring""" with pytest.raises(lowercase ): cached_path('''https://huggingface.co''' ) @patch('''datasets.config.HF_DATASETS_OFFLINE''' , lowercase ) def _A ( lowercase ): """simple docstring""" a =tmp_path_factory.mktemp('''data''' ) / '''file.html''' with pytest.raises(lowercase ): http_get('''https://huggingface.co''' , temp_file=lowercase ) with pytest.raises(lowercase ): http_head('''https://huggingface.co''' ) @patch('''datasets.config.HF_DATASETS_OFFLINE''' , lowercase ) def _A ( lowercase ): """simple docstring""" a =tmp_path_factory.mktemp('''data''' ) / '''file.html''' with pytest.raises(lowercase ): ftp_get('''ftp://huggingface.co''' , temp_file=lowercase ) with pytest.raises(lowercase ): ftp_head('''ftp://huggingface.co''' ) @patch('''datasets.config.HF_DATASETS_OFFLINE''' , lowercase ) def _A ( lowercase ): """simple docstring""" a =tmp_path_factory.mktemp('''data''' ) / '''file.html''' with pytest.raises(lowercase ): fsspec_get('''s3://huggingface.co''' , temp_file=lowercase ) with pytest.raises(lowercase ): fsspec_head('''s3://huggingface.co''' )
81
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
1
"""simple docstring""" import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCamelCase_ : List[Any] = logging.getLogger(__name__) def _A ( ): """simple docstring""" a =argparse.ArgumentParser( description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' ) parser.add_argument( '''--dataset_name''' , type=lowercase , default='''wikitext''' , help='''Name of the training. Explore datasets at: hf.co/datasets.''' , ) parser.add_argument( '''--dataset_config''' , type=lowercase , default='''wikitext-103-raw-v1''' , help='''Configuration name of the dataset.''' ) parser.add_argument( '''--tokenizer_name_or_path''' , type=lowercase , default='''sayakpaul/unigram-tokenizer-wikitext''' , help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' , ) parser.add_argument( '''--shard_size''' , type=lowercase , default=10_00 , help='''Number of entries to go in a single shard.''' , ) parser.add_argument('''--split''' , type=lowercase , default='''train''' , choices=['''train''', '''test''', '''validation'''] ) parser.add_argument( '''--limit''' , default=lowercase , type=lowercase , help='''Limit the number of shards (used for debugging).''' , ) parser.add_argument( '''--max_length''' , type=lowercase , default=5_12 , 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=lowercase , 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.''' , ) a =parser.parse_args() return args def _A ( lowercase ): """simple docstring""" def fn(lowercase ): return tokenizer(examples['''text'''] ) return fn def _A ( lowercase ): """simple docstring""" a =[] for i in range(len(tokenized_data['''input_ids'''] ) ): a ={ '''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] ) ), } a =tf.train.Features(feature=lowercase ) a =tf.train.Example(features=lowercase ) a =example.SerializeToString() records.append(lowercase ) return records def _A ( lowercase ): """simple docstring""" a =datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: a =min(len(lowercase ) , args.limit ) a =dataset.select(range(lowercase ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) a =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 ) a =os.path.join(args.output_dir , args.split ) if not os.path.exists(lowercase ): os.makedirs(lowercase ) else: a =os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. a =tokenize_function(lowercase ) a =dataset.map(lowercase , batched=lowercase , 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(lowercase ): # Concatenate all texts. a ={k: sum(examples[k] , [] ) for k in examples.keys()} a =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 🫀 a =(total_length // args.max_length) * args.max_length # Split by chunks of max_len. a ={ k: [t[i : i + args.max_length] for i in range(0 , lowercase , args.max_length )] for k, t in concatenated_examples.items() } return result a =dataset_tokenized.map(lowercase , batched=lowercase , batch_size=10_00 , num_proc=4 ) a =0 a =0 for shard in range(0 , len(lowercase ) , args.shard_size ): a =grouped_dataset[shard : shard + args.shard_size] a =len(dataset_snapshot['''input_ids'''] ) a =os.path.join(lowercase , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) a =get_serialized_examples(lowercase ) with tf.io.TFRecordWriter(lowercase ) as out_file: for i in range(len(lowercase ) ): a =serialized_examples[i] out_file.write(lowercase ) print('''Wrote file {} containing {} records'''.format(lowercase , lowercase ) ) 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=lowercase ) if __name__ == "__main__": lowerCamelCase_ : Dict = parse_args() main(args)
81
"""simple docstring""" from math import factorial def _A ( lowercase = 1_00 ): """simple docstring""" return sum(int(lowercase ) for x in str(factorial(lowercase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
81
1
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class __A ( unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =AutoImageProcessor.from_pretrained('''microsoft/dit-base-finetuned-rvlcdip''' ) a =AutoModelForImageClassification.from_pretrained('''microsoft/dit-base-finetuned-rvlcdip''' ) model.to(__A ) from datasets import load_dataset a =load_dataset('''nielsr/rvlcdip-demo''' ) a =dataset['''train'''][0]['''image'''].convert('''RGB''' ) a =image_processor(__A , return_tensors='''pt''' ).to(__A ) # forward pass with torch.no_grad(): a =model(**__A ) a =outputs.logits a =torch.Size((1, 16) ) self.assertEqual(logits.shape , __A ) a =torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=__A , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , __A , atol=1E-4 ) )
81
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = """▁""" lowerCamelCase_ : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : Any = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowerCamelCase_ : Tuple = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} 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 , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a =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 a ={'''<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 a =1 a =len(self.sp_model ) + self.fairseq_offset a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: a =self.__dict__.copy() a =None a =self.sp_model.serialized_model_proto() return state def __setstate__( self , __A ) -> List[Any]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =''''''.join(__A ).replace(__A , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =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: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase_ : Optional[Any] = { """configuration_data2vec_audio""": ["""DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecAudioConfig"""], """configuration_data2vec_text""": [ """DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecTextConfig""", """Data2VecTextOnnxConfig""", ], """configuration_data2vec_vision""": [ """DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Data2VecVisionConfig""", """Data2VecVisionOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[int] = [ """DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecAudioForAudioFrameClassification""", """Data2VecAudioForCTC""", """Data2VecAudioForSequenceClassification""", """Data2VecAudioForXVector""", """Data2VecAudioModel""", """Data2VecAudioPreTrainedModel""", ] lowerCamelCase_ : Dict = [ """DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecTextForCausalLM""", """Data2VecTextForMaskedLM""", """Data2VecTextForMultipleChoice""", """Data2VecTextForQuestionAnswering""", """Data2VecTextForSequenceClassification""", """Data2VecTextForTokenClassification""", """Data2VecTextModel""", """Data2VecTextPreTrainedModel""", ] lowerCamelCase_ : Union[str, Any] = [ """DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST""", """Data2VecVisionForImageClassification""", """Data2VecVisionForMaskedImageModeling""", """Data2VecVisionForSemanticSegmentation""", """Data2VecVisionModel""", """Data2VecVisionPreTrainedModel""", ] if is_tf_available(): lowerCamelCase_ : List[str] = [ """TFData2VecVisionForImageClassification""", """TFData2VecVisionForSemanticSegmentation""", """TFData2VecVisionModel""", """TFData2VecVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys lowerCamelCase_ : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : str = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : Tuple = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} 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 , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a ={'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} a =len(self.sp_model ) - 1 a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ) -> Any: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> int: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) return spm_id if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =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: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = (UnCLIPScheduler,) def SCREAMING_SNAKE_CASE ( self , **__A ) -> int: a ={ '''num_train_timesteps''': 1000, '''variance_type''': '''fixed_small_log''', '''clip_sample''': True, '''clip_sample_range''': 1.0, '''prediction_type''': '''epsilon''', } config.update(**__A ) return config def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=__A ) def SCREAMING_SNAKE_CASE ( self ) -> int: for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=__A , prev_timestep=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.scheduler_classes[0] a =self.get_scheduler_config(variance_type='''fixed_small_log''' ) a =scheduler_class(**__A ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0_0_0_0E-1_0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_549_625 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.9_994_987 ) ) < 1E-5 def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.scheduler_classes[0] a =self.get_scheduler_config(variance_type='''learned_range''' ) a =scheduler_class(**__A ) a =0.5 assert scheduler._get_variance(1 , predicted_variance=__A ) - -10.1_712_790 < 1E-5 assert scheduler._get_variance(487 , predicted_variance=__A ) - -5.7_998_052 < 1E-5 assert scheduler._get_variance(999 , predicted_variance=__A ) - -0.0_010_011 < 1E-5 def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.scheduler_classes[0] a =self.get_scheduler_config() a =scheduler_class(**__A ) a =scheduler.timesteps a =self.dummy_model() a =self.dummy_sample_deter a =torch.manual_seed(0 ) for i, t in enumerate(__A ): # 1. predict noise residual a =model(__A , __A ) # 2. predict previous mean of sample x_t-1 a =scheduler.step(__A , __A , __A , generator=__A ).prev_sample a =pred_prev_sample a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 252.2_682_495 ) < 1E-2 assert abs(result_mean.item() - 0.3_284_743 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self ) -> int: a =self.scheduler_classes[0] a =self.get_scheduler_config() a =scheduler_class(**__A ) scheduler.set_timesteps(25 ) a =scheduler.timesteps a =self.dummy_model() a =self.dummy_sample_deter a =torch.manual_seed(0 ) for i, t in enumerate(__A ): # 1. predict noise residual a =model(__A , __A ) if i + 1 == timesteps.shape[0]: a =None else: a =timesteps[i + 1] # 2. predict previous mean of sample x_t-1 a =scheduler.step( __A , __A , __A , prev_timestep=__A , generator=__A ).prev_sample a =pred_prev_sample a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 258.2_044_983 ) < 1E-2 assert abs(result_mean.item() - 0.3_362_038 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self ) -> Dict: pass def SCREAMING_SNAKE_CASE ( self ) -> str: pass
81
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : List[str] = { """configuration_x_clip""": [ """XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XCLIPConfig""", """XCLIPTextConfig""", """XCLIPVisionConfig""", ], """processing_x_clip""": ["""XCLIPProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Union[str, Any] = [ """XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """XCLIPModel""", """XCLIPPreTrainedModel""", """XCLIPTextModel""", """XCLIPVisionModel""", ] if TYPE_CHECKING: from .configuration_x_clip import ( XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig, ) from .processing_x_clip import XCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_x_clip import ( XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, XCLIPModel, XCLIPPreTrainedModel, XCLIPTextModel, XCLIPVisionModel, ) else: import sys lowerCamelCase_ : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = DistilBertTokenizer __lowerCAmelCase = DistilBertTokenizerFast __lowerCAmelCase = True @slow def SCREAMING_SNAKE_CASE ( self ) -> int: a =DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
81
1
"""simple docstring""" import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) def _A ( lowercase , lowercase ): """simple docstring""" def run_func(lowercase ): @wraps(lowercase ) def run_in_eager_mode(*lowercase , **lowercase ): return func(*lowercase , **lowercase ) @wraps(lowercase ) @tf.function(experimental_compile=lowercase ) def run_in_graph_mode(*lowercase , **lowercase ): return func(*lowercase , **lowercase ) if do_eager_mode is True: if use_xla is not False: raise ValueError( '''Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.''' ) return run_in_eager_mode else: return run_in_graph_mode return run_func def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =random.Random() a =[rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(lowercase , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = 42 __lowerCAmelCase = 42 __lowerCAmelCase = "TensorFlow" @property def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: return tf.__version__ def SCREAMING_SNAKE_CASE ( self , __A , __A , __A ) -> float: # initialize GPU on separate process a =self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) a =self._prepare_inference_func(__A , __A , __A ) return self._measure_speed(_inference ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A ) -> float: a =self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) a =self._prepare_train_func(__A , __A , __A ) return self._measure_speed(_train ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A ) -> [Memory, Optional[MemorySummary]]: # initialize GPU on separate process if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , __A ) a =self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) a =self._prepare_inference_func(__A , __A , __A ) return self._measure_memory(_inference ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A ) -> [Memory, Optional[MemorySummary]]: if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , __A ) a =self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) a =self._prepare_train_func(__A , __A , __A ) return self._measure_memory(_train ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A ) -> Callable[[], None]: a =self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError('''Mixed precision is currently not supported.''' ) a =( hasattr(__A , '''architectures''' ) and isinstance(config.architectures , __A ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: a ='''TF''' + config.architectures[0] # prepend 'TF' for tensorflow model a =__import__('''transformers''' , fromlist=[model_class] ) a =getattr(__A , __A ) a =model_cls(__A ) except ImportError: raise ImportError( f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.''' ) else: a =TF_MODEL_MAPPING[config.__class__](__A ) # encoder-decoder has vocab size saved differently a =config.vocab_size if hasattr(__A , '''vocab_size''' ) else config.encoder.vocab_size a =random_input_ids(__A , __A , __A ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(__A , decoder_input_ids=__A , training=__A ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(__A , training=__A ) a =encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def SCREAMING_SNAKE_CASE ( self , __A , __A , __A ) -> Callable[[], None]: a =self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError('''Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.''' ) if self.args.fpaa: raise NotImplementedError('''Mixed precision is currently not supported.''' ) a =( hasattr(__A , '''architectures''' ) and isinstance(config.architectures , __A ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: a ='''TF''' + config.architectures[0] # prepend 'TF' for tensorflow model a =__import__('''transformers''' , fromlist=[model_class] ) a =getattr(__A , __A ) a =model_cls(__A ) except ImportError: raise ImportError( f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to''' ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.''' ) else: a =TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__A ) # encoder-decoder has vocab size saved differently a =config.vocab_size if hasattr(__A , '''vocab_size''' ) else config.encoder.vocab_size a =random_input_ids(__A , __A , __A ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): a =model(__A , decoder_input_ids=__A , labels=__A , training=__A )[0] a =tf.gradients(__A , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): a =model(__A , labels=__A , training=__A )[0] a =tf.gradients(__A , model.trainable_variables ) return gradients a =encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def SCREAMING_SNAKE_CASE ( self , __A ) -> float: with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info('''Do inference on TPU. Running model 5 times to stabilize compilation''' ) timeit.repeat(__A , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average a =timeit.repeat( __A , repeat=self.args.repeat , number=10 , ) return min(__A ) / 10.0 except ResourceExhaustedError as e: self.print_fn(f'''Doesn\'t fit on GPU. {e}''' ) def SCREAMING_SNAKE_CASE ( self , __A ) -> [Memory, MemorySummary]: logger.info( '''Note that TensorFlow allocates more memory than ''' '''it might need to speed up computation. ''' '''The memory reported here corresponds to the memory ''' '''reported by `nvidia-smi`, which can vary depending ''' '''on total available memory on the GPU that is used.''' ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( '''`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory''' ''' consumption line by line.''' ) a =start_memory_tracing('''transformers''' ) if self.args.is_tpu: # tpu raise NotImplementedError( '''Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking''' ''' with `args.memory=False`''' ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( '''py3nvml not installed, we won\'t log GPU memory usage. ''' '''Install py3nvml (pip install py3nvml) to log information about GPU.''' ) a ='''N/A''' else: logger.info( '''Measuring total GPU usage on GPU device. Make sure to not have additional processes''' ''' running on the same GPU.''' ) # init nvml nvml.nvmlInit() func() a =nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) a =nvml.nvmlDeviceGetMemoryInfo(__A ) a =meminfo.used a =Memory(__A ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( '''When enabling line by line tracing, the max peak memory for CPU is inaccurate in''' ''' TensorFlow.''' ) a =None else: a =measure_peak_memory_cpu(__A ) a =Memory(__A ) if isinstance(__A , __A ) else memory_bytes if self.args.trace_memory_line_by_line: a =stop_memory_tracing(__A ) if memory is None: a =summary.total else: a =None return memory, summary except ResourceExhaustedError as e: self.print_fn(f'''Doesn\'t fit on GPU. {e}''' ) return "N/A", None
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCamelCase_ : Tuple = """ Examples: ```py >>> from PIL import Image >>> import torch >>> from diffusers import DiffusionPipeline >>> from diffusers.utils import export_to_gif, load_image >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") >>> repo = \"openai/shap-e-img2img\" >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16) >>> pipe = pipe.to(device) >>> guidance_scale = 3.0 >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\" >>> image = load_image(image_url).convert(\"RGB\") >>> images = pipe( ... image, ... guidance_scale=guidance_scale, ... num_inference_steps=64, ... frame_size=256, ... ).images >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\") ``` """ @dataclass class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = 42 class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A , __A , __A , __A , __A , ) -> Optional[Any]: super().__init__() self.register_modules( prior=__A , image_encoder=__A , image_processor=__A , scheduler=__A , renderer=__A , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A ) -> Any: if latents is None: a =randn_tensor(__A , generator=__A , device=__A , dtype=__A ) else: if latents.shape != shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) a =latents.to(__A ) a =latents * scheduler.init_noise_sigma return latents def SCREAMING_SNAKE_CASE ( self , __A=0 ) -> int: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a =torch.device(f'''cuda:{gpu_id}''' ) a =[self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__A , __A ) @property def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: if self.device != torch.device('''meta''' ) or not hasattr(self.image_encoder , '''_hf_hook''' ): return self.device for module in self.image_encoder.modules(): if ( hasattr(__A , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , ) -> Optional[int]: if isinstance(__A , __A ) and isinstance(image[0] , torch.Tensor ): a =torch.cat(__A , axis=0 ) if image[0].ndim == 4 else torch.stack(__A , axis=0 ) if not isinstance(__A , torch.Tensor ): a =self.image_processor(__A , return_tensors='''pt''' ).pixel_values[0].unsqueeze(0 ) a =image.to(dtype=self.image_encoder.dtype , device=__A ) a =self.image_encoder(__A )['''last_hidden_state'''] a =image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 a =image_embeds.repeat_interleave(__A , dim=0 ) if do_classifier_free_guidance: a =torch.zeros_like(__A ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes a =torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(__A ) def __call__( self , __A , __A = 1 , __A = 25 , __A = None , __A = None , __A = 4.0 , __A = 64 , __A = "pil" , __A = True , ) -> Tuple: if isinstance(__A , PIL.Image.Image ): a =1 elif isinstance(__A , torch.Tensor ): a =image.shape[0] elif isinstance(__A , __A ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): a =len(__A ) else: raise ValueError( f'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(__A )}''' ) a =self._execution_device a =batch_size * num_images_per_prompt a =guidance_scale > 1.0 a =self._encode_image(__A , __A , __A , __A ) # prior self.scheduler.set_timesteps(__A , device=__A ) a =self.scheduler.timesteps a =self.prior.config.num_embeddings a =self.prior.config.embedding_dim a =self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , __A , __A , __A , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim a =latents.reshape(latents.shape[0] , __A , __A ) for i, t in enumerate(self.progress_bar(__A ) ): # expand the latents if we are doing classifier free guidance a =torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a =self.scheduler.scale_model_input(__A , __A ) a =self.prior( __A , timestep=__A , proj_embedding=__A , ).predicted_image_embedding # remove the variance a , a =noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: a , a =noise_pred.chunk(2 ) a =noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) a =self.scheduler.step( __A , timestep=__A , sample=__A , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=__A ) a =[] for i, latent in enumerate(__A ): print() a =self.renderer.decode( latent[None, :] , __A , size=__A , ray_batch_size=4096 , n_coarse_samples=64 , n_fine_samples=128 , ) images.append(__A ) a =torch.stack(__A ) if output_type not in ["np", "pil"]: raise ValueError(f'''Only the output types `pil` and `np` are supported not output_type={output_type}''' ) a =images.cpu().numpy() if output_type == "pil": a =[self.numpy_to_pil(__A ) for image in images] # Offload last model to CPU if hasattr(self , '''final_offload_hook''' ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=__A )
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A ( unittest.TestCase ): """simple docstring""" def __init__( self , __A , __A=3 , __A=32 , __A=3 , __A=10 , __A=[10, 20, 30, 40] , __A=[1, 1, 2, 1] , __A=True , __A=True , __A="relu" , __A=3 , __A=None , ) -> Any: a =parent a =batch_size a =image_size a =num_channels a =embeddings_size a =hidden_sizes a =depths a =is_training a =use_labels a =hidden_act a =num_labels a =scope a =len(__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a =self.get_config() return config, pixel_values def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: 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 SCREAMING_SNAKE_CASE ( self , __A , __A ) -> Tuple: a =FlaxRegNetModel(config=__A ) a =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 SCREAMING_SNAKE_CASE ( self , __A , __A ) -> Any: a =self.num_labels a =FlaxRegNetForImageClassification(config=__A ) a =model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =self.prepare_config_and_inputs() a , a =config_and_inputs a ={'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self ) -> None: a =FlaxRegNetModelTester(self ) a =ConfigTester(self , config_class=__A , has_text_modality=__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: 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 SCREAMING_SNAKE_CASE ( self ) -> Any: return def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def SCREAMING_SNAKE_CASE ( self ) -> str: pass def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a , a =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a =model_class(__A ) a =inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a =[*signature.parameters.keys()] a =['''pixel_values'''] self.assertListEqual(arg_names[:1] , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: def check_hidden_states_output(__A , __A , __A ): a =model_class(__A ) a =model(**self._prepare_for_class(__A , __A ) ) a =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a =self.model_tester.num_stages self.assertEqual(len(__A ) , expected_num_stages + 1 ) a , a =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a =True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a =True check_hidden_states_output(__A , __A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a , a =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): a =self._prepare_for_class(__A , __A ) a =model_class(__A ) @jax.jit def model_jitted(__A , **__A ): return model(pixel_values=__A , **__A ) with self.subTest('''JIT Enabled''' ): a =model_jitted(**__A ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): a =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 _A ( ): """simple docstring""" a =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class __A ( unittest.TestCase ): """simple docstring""" @cached_property def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE ( self ) -> Any: a =FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) a =self.default_image_processor a =prepare_img() a =image_processor(images=__A , return_tensors='''np''' ) a =model(**__A ) # verify the logits a =(1, 1000) self.assertEqual(outputs.logits.shape , __A ) a =jnp.array([-0.4_180, -1.5_051, -3.4_836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , __A , atol=1E-4 ) )
81
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
1
"""simple docstring""" import os import pytest from attr import dataclass lowerCamelCase_ : Dict = """us-east-1""" # defaults region @dataclass class __A : """simple docstring""" __lowerCAmelCase = 42 __lowerCAmelCase = "arn:aws:iam::558105141721:role/sagemaker_execution_role" __lowerCAmelCase = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } __lowerCAmelCase = {**hyperparameters, "max_steps": 1000} @property def SCREAMING_SNAKE_CASE ( self ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def SCREAMING_SNAKE_CASE ( self ) -> str: return f'''{self.framework}-transfromers-test''' @property def SCREAMING_SNAKE_CASE ( self ) -> str: return f'''./tests/sagemaker/scripts/{self.framework}''' @property def SCREAMING_SNAKE_CASE ( self ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='''class''' ) def _A ( lowercase ): """simple docstring""" a =SageMakerTestEnvironment(framework=request.cls.framework )
81
"""simple docstring""" import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Any: 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 SCREAMING_SNAKE_CASE ( self ) -> str: self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_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]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =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 ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
1
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class __A ( unittest.TestCase, _SCREAMING_SNAKE_CASE ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =load_tool('''text-classification''' ) self.tool.setup() a =load_tool('''text-classification''' , remote=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =self.tool('''That\'s quite cool''' , ['''positive''', '''negative'''] ) self.assertEqual(__A , '''positive''' ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =self.remote_tool('''That\'s quite cool''' , ['''positive''', '''negative'''] ) self.assertEqual(__A , '''positive''' ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =self.tool(text='''That\'s quite cool''' , labels=['''positive''', '''negative'''] ) self.assertEqual(__A , '''positive''' ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.remote_tool(text='''That\'s quite cool''' , labels=['''positive''', '''negative'''] ) self.assertEqual(__A , '''positive''' )
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" while second != 0: a =first & second first ^= second a =c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Dict = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : List[Any] = int(input("""Enter the second number: """).strip()) print(F'{add(first, second) = }')
81
1
"""simple docstring""" from math import log from scipy.constants import Boltzmann, physical_constants lowerCamelCase_ : Dict = 3_0_0 # TEMPERATURE (unit = K) def _A ( lowercase , lowercase , lowercase , ): """simple docstring""" if donor_conc <= 0: raise ValueError('''Donor concentration should be positive''' ) elif acceptor_conc <= 0: raise ValueError('''Acceptor concentration should be positive''' ) elif intrinsic_conc <= 0: raise ValueError('''Intrinsic concentration should be positive''' ) elif donor_conc <= intrinsic_conc: raise ValueError( '''Donor concentration should be greater than intrinsic concentration''' ) elif acceptor_conc <= intrinsic_conc: raise ValueError( '''Acceptor concentration should be greater than intrinsic concentration''' ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2 ) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
81
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
1
"""simple docstring""" def _A ( lowercase ): """simple docstring""" if not isinstance(lowercase , lowercase ) or number < 0: raise ValueError('''Input must be a non-negative integer''' ) a =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
81
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCamelCase_ : str = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *__A , **__A ) -> None: warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , __A , ) super().__init__(*__A , **__A )
81
1
"""simple docstring""" from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( "The RoBERTa Model transformer with early exiting (DeeRoBERTa). ", _SCREAMING_SNAKE_CASE, ) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = RobertaConfig __lowerCAmelCase = "roberta" def __init__( self , __A ) -> List[Any]: super().__init__(__A ) a =RobertaEmbeddings(__A ) self.init_weights() @add_start_docstrings( "RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,\n also takes care of multi-layer training. ", _SCREAMING_SNAKE_CASE, ) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = RobertaConfig __lowerCAmelCase = "roberta" def __init__( self , __A ) -> Dict: super().__init__(__A ) a =config.num_labels a =config.num_hidden_layers a =DeeRobertaModel(__A ) a =nn.Dropout(config.hidden_dropout_prob ) a =nn.Linear(config.hidden_size , self.config.num_labels ) @add_start_docstrings_to_model_forward(__A ) def SCREAMING_SNAKE_CASE ( self , __A=None , __A=None , __A=None , __A=None , __A=None , __A=None , __A=None , __A=-1 , __A=False , ) -> Optional[int]: a =self.num_layers try: a =self.roberta( __A , attention_mask=__A , token_type_ids=__A , position_ids=__A , head_mask=__A , inputs_embeds=__A , ) a =outputs[1] a =self.dropout(__A ) a =self.classifier(__A ) a =(logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: a =e.message a =e.exit_layer a =outputs[0] if not self.training: a =entropy(__A ) a =[] a =[] if labels is not None: if self.num_labels == 1: # We are doing regression a =MSELoss() a =loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: a =CrossEntropyLoss() a =loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits a =[] for highway_exit in outputs[-1]: a =highway_exit[0] if not self.training: highway_logits_all.append(__A ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression a =MSELoss() a =loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: a =CrossEntropyLoss() a =loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(__A ) if train_highway: a =(sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: a =(loss,) + outputs if not self.training: a =outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: a =( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
1
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
81
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
1
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" a =len(lowercase ) a =[] for i in range(len(lowercase ) - pat_len + 1 ): a =True for j in range(lowercase ): if s[i + j] != pattern[j]: a =False break if match_found: position.append(lowercase ) return position if __name__ == "__main__": assert naive_pattern_search("""ABCDEFG""", """DE""") == [3] print(naive_pattern_search("""ABAAABCDBBABCDDEBCABC""", """ABC"""))
81
"""simple docstring""" lowerCamelCase_ : Any = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {"""configuration_encoder_decoder""": ["""EncoderDecoderConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""EncoderDecoderModel"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Tuple = ["""TFEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[int] = ["""FlaxEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys lowerCamelCase_ : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ lowerCamelCase_ : Optional[Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ lowerCamelCase_ : Optional[int] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Optional[Any]: if return_pvalue: a =pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
81
1
"""simple docstring""" import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging lowerCamelCase_ : Dict = logging.get_logger(__name__) lowerCamelCase_ : int = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt"""} # See all LED models at https://huggingface.co/models?filter=LED lowerCamelCase_ : Optional[Any] = { """vocab_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json""", }, """merges_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt""", }, """tokenizer_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json""", }, } lowerCamelCase_ : Optional[Any] = { """allenai/led-base-16384""": 1_6_3_8_4, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def _A ( ): """simple docstring""" a =( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) a =bs[:] a =0 for b in range(2**8 ): if b not in bs: bs.append(lowercase ) cs.append(2**8 + n ) n += 1 a =[chr(lowercase ) for n in cs] return dict(zip(lowercase , lowercase ) ) def _A ( lowercase ): """simple docstring""" a =set() a =word[0] for char in word[1:]: pairs.add((prev_char, char) ) a =char return pairs class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A , __A="replace" , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A=False , **__A , ) -> List[Any]: a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else unk_token a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( errors=__A , bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , **__A , ) with open(__A , encoding='''utf-8''' ) as vocab_handle: a =json.load(__A ) a ={v: k for k, v in self.encoder.items()} a =errors # how to handle errors in decoding a =bytes_to_unicode() a ={v: k for k, v in self.byte_encoder.items()} with open(__A , encoding='''utf-8''' ) as merges_handle: a =merges_handle.read().split('''\n''' )[1:-1] a =[tuple(merge.split() ) for merge in bpe_merges] a =dict(zip(__A , range(len(__A ) ) ) ) a ={} a =add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions a =re.compile(r'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.encoder ) def SCREAMING_SNAKE_CASE ( self ) -> str: return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: if token in self.cache: return self.cache[token] a =tuple(__A ) a =get_pairs(__A ) if not pairs: return token while True: a =min(__A , key=lambda __A : self.bpe_ranks.get(__A , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break a , a =bigram a =[] a =0 while i < len(__A ): try: a =word.index(__A , __A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) a =j if word[i] == first and i < len(__A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 a =tuple(__A ) a =new_word if len(__A ) == 1: break else: a =get_pairs(__A ) a =''' '''.join(__A ) a =word return word def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =[] for token in re.findall(self.pat , __A ): a =''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__A ).split(''' ''' ) ) return bpe_tokens def SCREAMING_SNAKE_CASE ( self , __A ) -> List[Any]: return self.encoder.get(__A , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[int]: return self.decoder.get(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Any: a =''''''.join(__A ) a =bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(__A , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__A , ensure_ascii=__A ) + '''\n''' ) a =0 with open(__A , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __A : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) a =token_index writer.write(''' '''.join(__A ) + '''\n''' ) index += 1 return vocab_file, merge_file def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE ( self , __A , __A=False , **__A ) -> str: a =kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__A ) > 0 and not text[0].isspace()): a =''' ''' + text return (text, kwargs) def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = PaddingStrategy.DO_NOT_PAD , __A = None , __A = None , ) -> dict: a =super()._pad( encoded_inputs=__A , max_length=__A , padding_strategy=__A , pad_to_multiple_of=__A , return_attention_mask=__A , ) # Load from model defaults if return_attention_mask is None: a ='''attention_mask''' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: a =encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. a =len(encoded_inputs['''global_attention_mask'''] ) != len(__A ) if needs_to_be_padded: a =len(__A ) - len(encoded_inputs['''global_attention_mask'''] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` a =( encoded_inputs['''global_attention_mask'''] + [-1] * difference ) elif self.padding_side == "left": a =[-1] * difference + encoded_inputs[ '''global_attention_mask''' ] else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return encoded_inputs
81
"""simple docstring""" lowerCamelCase_ : int = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Union[str, Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
1
"""simple docstring""" import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def _A ( lowercase ): """simple docstring""" a =np.inf def set_batch_size(lowercase ) -> None: nonlocal batch_size if isinstance(lowercase , lowercase ): a =min(lowercase , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(lowercase , lowercase ): a =min(lowercase , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(lowercase , lowercase ) and feature.dtype == "binary": a =min(lowercase , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(lowercase , lowercase ) return None if batch_size is np.inf else batch_size class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A , __A = None , __A = None , __A = None , __A = False , __A = False , __A = None , **__A , ) -> Optional[Any]: super().__init__( __A , split=__A , features=__A , cache_dir=__A , keep_in_memory=__A , streaming=__A , num_proc=__A , **__A , ) a =path_or_paths if isinstance(__A , __A ) else {self.split: path_or_paths} a =_PACKAGED_DATASETS_MODULES['''parquet'''][1] a =Parquet( cache_dir=__A , data_files=__A , features=__A , hash=__A , **__A , ) def SCREAMING_SNAKE_CASE ( self ) -> int: # Build iterable dataset if self.streaming: a =self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: a =None a =None a =None a =None self.builder.download_and_prepare( download_config=__A , download_mode=__A , verification_mode=__A , base_path=__A , num_proc=self.num_proc , ) a =self.builder.as_dataset( split=self.split , verification_mode=__A , in_memory=self.keep_in_memory ) return dataset class __A : """simple docstring""" def __init__( self , __A , __A , __A = None , **__A , ) -> Optional[int]: a =dataset a =path_or_buf a =batch_size or get_writer_batch_size(dataset.features ) a =parquet_writer_kwargs def SCREAMING_SNAKE_CASE ( self ) -> int: a =self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with open(self.path_or_buf , '''wb+''' ) as buffer: a =self._write(file_obj=__A , batch_size=__A , **self.parquet_writer_kwargs ) else: a =self._write(file_obj=self.path_or_buf , batch_size=__A , **self.parquet_writer_kwargs ) return written def SCREAMING_SNAKE_CASE ( self , __A , __A , **__A ) -> int: a =0 a =parquet_writer_kwargs.pop('''path_or_buf''' , __A ) a =self.dataset.features.arrow_schema a =pq.ParquetWriter(__A , schema=__A , **__A ) for offset in logging.tqdm( range(0 , len(self.dataset ) , __A ) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ): a =query_table( table=self.dataset._data , key=slice(__A , offset + batch_size ) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(__A ) written += batch.nbytes writer.close() return written
81
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
1
"""simple docstring""" from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class __A : """simple docstring""" __lowerCAmelCase = 42 __lowerCAmelCase = None __lowerCAmelCase = None def _A ( ): """simple docstring""" a =Node(1 ) a =Node(2 ) a =Node(3 ) a =Node(4 ) a =Node(5 ) return tree def _A ( lowercase ): """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _A ( lowercase ): """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _A ( lowercase ): """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _A ( lowercase ): """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def _A ( lowercase ): """simple docstring""" a =[] if root is None: return output a =deque([root] ) while process_queue: a =process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _A ( lowercase , lowercase ): """simple docstring""" a =[] def populate_output(lowercase , lowercase ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(lowercase , lowercase ) return output def _A ( lowercase , lowercase ): """simple docstring""" a =[] def populate_output(lowercase , lowercase ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(lowercase , lowercase ) return output def _A ( lowercase ): """simple docstring""" if root is None: return [] a =[] a =0 a =height(lowercase ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(lowercase , lowercase ) ) a =1 else: output.append(get_nodes_from_right_to_left(lowercase , lowercase ) ) a =0 return output def _A ( ): # Main function for testing. """simple docstring""" a =make_tree() print(f'''In-order Traversal: {inorder(lowercase )}''' ) print(f'''Pre-order Traversal: {preorder(lowercase )}''' ) print(f'''Post-order Traversal: {postorder(lowercase )}''' , '''\n''' ) print(f'''Height of Tree: {height(lowercase )}''' , '''\n''' ) print('''Complete Level Order Traversal: ''' ) print(level_order(lowercase ) , '''\n''' ) print('''Level-wise order Traversal: ''' ) for level in range(1 , height(lowercase ) + 1 ): print(f'''Level {level}:''' , get_nodes_from_left_to_right(lowercase , level=lowercase ) ) print('''\nZigZag order Traversal: ''' ) print(zigzag(lowercase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = (DDIMParallelScheduler,) __lowerCAmelCase = (("eta", 0.0), ("num_inference_steps", 50)) def SCREAMING_SNAKE_CASE ( self , **__A ) -> Optional[Any]: a ={ '''num_train_timesteps''': 1000, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**__A ) return config def SCREAMING_SNAKE_CASE ( self , **__A ) -> Tuple: a =self.scheduler_classes[0] a =self.get_scheduler_config(**__A ) a =scheduler_class(**__A ) a , a =10, 0.0 a =self.dummy_model() a =self.dummy_sample_deter scheduler.set_timesteps(__A ) for t in scheduler.timesteps: a =model(__A , __A ) a =scheduler.step(__A , __A , __A , __A ).prev_sample return sample def SCREAMING_SNAKE_CASE ( self ) -> str: for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=__A ) def SCREAMING_SNAKE_CASE ( self ) -> str: for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__A ) a =self.scheduler_classes[0] a =self.get_scheduler_config(steps_offset=1 ) a =scheduler_class(**__A ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def SCREAMING_SNAKE_CASE ( self ) -> Any: for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__A , beta_end=__A ) def SCREAMING_SNAKE_CASE ( self ) -> str: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Any: self.check_over_configs(thresholding=__A ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__A , prediction_type=__A , sample_max_value=__A , ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: for t in [1, 10, 49]: self.check_over_forward(time_step=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=__A , num_inference_steps=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__A , eta=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =self.scheduler_classes[0] a =self.get_scheduler_config() a =scheduler_class(**__A ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14_771 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32_460 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00_979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1E-5 def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.scheduler_classes[0] a =self.get_scheduler_config() a =scheduler_class(**__A ) a , a =10, 0.0 scheduler.set_timesteps(__A ) a =self.dummy_model() a =self.dummy_sample_deter a =self.dummy_sample_deter + 0.1 a =self.dummy_sample_deter - 0.1 a =samplea.shape[0] a =torch.stack([samplea, samplea, samplea] , dim=0 ) a =torch.arange(__A )[0:3, None].repeat(1 , __A ) a =model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) a =scheduler.batch_step_no_noise(__A , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __A ) a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1E-2 assert abs(result_mean.item() - 0.4_982 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.full_loop() a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 172.0_067 ) < 1E-2 assert abs(result_mean.item() - 0.223_967 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =self.full_loop(prediction_type='''v_prediction''' ) a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 52.5_302 ) < 1E-2 assert abs(result_mean.item() - 0.0_684 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self ) -> Any: # We specify different beta, so that the first alpha is 0.99 a =self.full_loop(set_alpha_to_one=__A , beta_start=0.01 ) a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 149.8_295 ) < 1E-2 assert abs(result_mean.item() - 0.1_951 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: # We specify different beta, so that the first alpha is 0.99 a =self.full_loop(set_alpha_to_one=__A , beta_start=0.01 ) a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 149.0_784 ) < 1E-2 assert abs(result_mean.item() - 0.1_941 ) < 1E-3
81
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy lowerCamelCase_ : Dict = logging.getLogger(__name__) lowerCamelCase_ : Tuple = """pytorch_model.bin""" @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}, ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "A csv or a json file containing the validation data."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The name of the task to train on."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) __lowerCAmelCase = dataclasses.field( default="accuracy", metadata={"help": "The evaluation metric used for the task."} ) __lowerCAmelCase = dataclasses.field( default="no", metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" }, ) __lowerCAmelCase = dataclasses.field( default=10, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." }, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}, ) __lowerCAmelCase = dataclasses.field( default=100, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Random seed for initialization."}, ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a =dataset.filter(lambda lowercase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a =int(eval_result * len(lowercase ) ) print(lowercase ) a =dataset.sort('''probability''' , reverse=lowercase ) a =dataset.select(range(lowercase ) ) a =dataset.remove_columns(['''label''', '''probability'''] ) a =dataset.rename_column('''prediction''' , '''label''' ) a =dataset.map(lambda lowercase : {"label": idalabel[example["label"]]} ) a =dataset.shuffle(seed=args.seed ) a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase , index=lowercase ) else: dataset.to_json(lowercase ) def _A ( lowercase , lowercase , lowercase , lowercase , **lowercase ): """simple docstring""" a =Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() a =STModelArguments(model_name_or_path=lowercase ) a =STDataArguments(train_file=lowercase , infer_file=lowercase ) a =STTrainingArguments(output_dir=lowercase ) a =argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase ).items(): setattr(lowercase , lowercase , lowercase ) for key, value in kwargs.items(): if hasattr(lowercase , lowercase ): setattr(lowercase , lowercase , lowercase ) # Sanity checks a ={} a =None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None a =args.train_file a =args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a =args.eval_file for key in data_files: a =data_files[key].split('''.''' )[-1] assert extension in ["csv", "json"], f'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: a =extension else: assert extension == args.data_file_extension, f'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), f'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info('''Creating the initial data directory for self-training...''' ) a =f'''{args.output_dir}/self-train_iter-{{}}'''.format a =data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) accelerator.wait_for_everyone() a =None a =None a =0 a =False # Show the progress bar a =tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): a =data_dir_format(lowercase ) assert os.path.exists(lowercase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a =os.path.join(lowercase , '''stage-1''' ) a ={ '''accelerator''': accelerator, '''model_name_or_path''': args.model_name_or_path, '''cache_dir''': args.cache_dir, '''do_train''': True, '''train_file''': data_files['''train'''] if iteration == 0 else data_files['''train_pseudo'''], '''do_eval''': True if args.eval_file is not None else False, '''eval_file''': data_files['''eval'''], '''do_predict''': True, '''infer_file''': data_files['''infer'''], '''task_name''': args.task_name, '''label_list''': args.label_list, '''output_dir''': current_output_dir, '''eval_metric''': args.eval_metric, '''evaluation_strategy''': args.evaluation_strategy, '''early_stopping_patience''': args.early_stopping_patience, '''early_stopping_threshold''': args.early_stopping_threshold, '''seed''': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(lowercase , lowercase ): arguments_dict.update({key: value} ) a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , lowercase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a =os.path.join(lowercase , '''best-checkpoint''' ) a =os.path.join(lowercase , '''stage-2''' ) # Update arguments_dict a =model_path a =data_files['''train'''] a =current_output_dir a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , lowercase ) a =iteration a =data_dir_format(iteration + 1 ) a =AutoConfig.from_pretrained(os.path.join(lowercase , '''best-checkpoint''' ) ) a =config.idalabel a =os.path.join(lowercase , '''eval_results_best-checkpoint.json''' ) a =os.path.join(lowercase , '''test_results_best-checkpoint.json''' ) assert os.path.exists(lowercase ) with open(lowercase , '''r''' ) as f: a =float(json.load(lowercase )[args.eval_metric] ) a =os.path.join(lowercase , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(lowercase ) # Loading the dataset from local csv or json files. a =load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )['''data'''] a =load_dataset('''csv''' , data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(lowercase , exist_ok=lowercase ) shutil.copy(lowercase , os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase ): shutil.copy(lowercase , os.path.join(lowercase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) accelerator.wait_for_everyone() a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a =eval_result if best_iteration is None: a =new_iteration a =new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a =new_iteration a =new_eval_result a =0 else: if new_eval_result == best_eval_result: a =new_iteration a =new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a =True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info('''Best iteration: %d''' , lowercase ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , ) else: # Assume that the last iteration is the best logger.info('''Best iteration: %d''' , args.max_selftrain_iterations - 1 ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , )
81
1
"""simple docstring""" from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class __A : """simple docstring""" pass
81
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
1
"""simple docstring""" def _A ( lowercase ): """simple docstring""" a =0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def _A ( lowercase = 1_00 ): """simple docstring""" a =1 a =2 for i in range(2 , max_n + 1 ): a =pre_numerator a =2 * i // 3 if i % 3 == 0 else 1 a =cur_numerator a =e_cont * pre_numerator + temp return sum_digits(lowercase ) if __name__ == "__main__": print(F'{solution() = }')
81
"""simple docstring""" from math import factorial def _A ( lowercase = 1_00 ): """simple docstring""" return sum(int(lowercase ) for x in str(factorial(lowercase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
81
1
"""simple docstring""" lowerCamelCase_ : int = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Union[str, Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = """▁""" lowerCamelCase_ : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : Any = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowerCamelCase_ : Tuple = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} 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 , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a =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 a ={'''<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 a =1 a =len(self.sp_model ) + self.fairseq_offset a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: a =self.__dict__.copy() a =None a =self.sp_model.serialized_model_proto() return state def __setstate__( self , __A ) -> List[Any]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =''''''.join(__A ).replace(__A , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =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: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : List[str] = { """vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_config_file""": """tokenizer_config.json""", } lowerCamelCase_ : Any = { """vocab_file""": {"""facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"""}, """merges_file""": {"""facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"""}, """tokenizer_config_file""": { """facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json""" }, } lowerCamelCase_ : Any = {"""facebook/blenderbot-3B""": 1_2_8} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _A ( ): """simple docstring""" a =( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) a =bs[:] a =0 for b in range(2**8 ): if b not in bs: bs.append(lowercase ) cs.append(2**8 + n ) n += 1 a =[chr(lowercase ) for n in cs] return dict(zip(lowercase , lowercase ) ) def _A ( lowercase ): """simple docstring""" a =set() a =word[0] for char in word[1:]: pairs.add((prev_char, char) ) a =char return pairs class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A , __A="replace" , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A=False , **__A , ) -> Union[str, Any]: a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else bos_token a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else eos_token a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else sep_token a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else cls_token a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else unk_token a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else pad_token # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token super().__init__( errors=__A , bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , **__A , ) with open(__A , encoding='''utf-8''' ) as vocab_handle: a =json.load(__A ) a ={v: k for k, v in self.encoder.items()} a =errors # how to handle errors in decoding a =bytes_to_unicode() a ={v: k for k, v in self.byte_encoder.items()} with open(__A , encoding='''utf-8''' ) as merges_handle: a =merges_handle.read().split('''\n''' )[1:-1] a =[tuple(merge.split() ) for merge in bpe_merges] a =dict(zip(__A , range(len(__A ) ) ) ) a ={} a =add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions a =re.compile(r'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: return len(self.encoder ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if token in self.cache: return self.cache[token] a =tuple(__A ) a =get_pairs(__A ) if not pairs: return token while True: a =min(__A , key=lambda __A : self.bpe_ranks.get(__A , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break a , a =bigram a =[] a =0 while i < len(__A ): try: a =word.index(__A , __A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) a =j if word[i] == first and i < len(__A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 a =tuple(__A ) a =new_word if len(__A ) == 1: break else: a =get_pairs(__A ) a =''' '''.join(__A ) a =word return word def SCREAMING_SNAKE_CASE ( self , __A ) -> int: a =[] for token in re.findall(self.pat , __A ): a =''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__A ).split(''' ''' ) ) return bpe_tokens def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: return self.encoder.get(__A , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.decoder.get(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: a =''''''.join(__A ) a =bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) a =os.path.join( __A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(__A , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__A , ensure_ascii=__A ) + '''\n''' ) a =0 with open(__A , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __A : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) a =token_index writer.write(''' '''.join(__A ) + '''\n''' ) index += 1 return vocab_file, merge_file def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE ( self , __A , __A=False , **__A ) -> Union[str, Any]: a =kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__A ) > 0 and not text[0].isspace()): a =''' ''' + text return (text, kwargs) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> str: return token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE ( self , __A ) -> List[int]: a =[] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(__A ) a =''' '''.join(__A ) a =self.encode(__A ) if len(__A ) > self.model_max_length: a =input_ids[-self.model_max_length :] logger.warning(f'''Trimmed input from conversation as it was longer than {self.model_max_length} tokens.''' ) return input_ids
81
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : str = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : Tuple = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} 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 , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a ={'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} a =len(self.sp_model ) - 1 a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ) -> Any: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> int: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) return spm_id if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =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: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
"""simple docstring""" import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase_ : Optional[int] = logging.get_logger(__name__) lowerCamelCase_ : List[Any] = [ ["""attention""", """attn"""], ["""encoder_attention""", """encoder_attn"""], ["""q_lin""", """q_proj"""], ["""k_lin""", """k_proj"""], ["""v_lin""", """v_proj"""], ["""out_lin""", """out_proj"""], ["""norm_embeddings""", """layernorm_embedding"""], ["""position_embeddings""", """embed_positions"""], ["""embeddings""", """embed_tokens"""], ["""ffn.lin""", """fc"""], ] def _A ( lowercase ): """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: a =k.replace(lowercase , lowercase ) if k.startswith('''encoder''' ): a =k.replace('''.attn''' , '''.self_attn''' ) a =k.replace('''norm1''' , '''self_attn_layer_norm''' ) a =k.replace('''norm2''' , '''final_layer_norm''' ) elif k.startswith('''decoder''' ): a =k.replace('''norm1''' , '''self_attn_layer_norm''' ) a =k.replace('''norm2''' , '''encoder_attn_layer_norm''' ) a =k.replace('''norm3''' , '''final_layer_norm''' ) return k def _A ( lowercase ): """simple docstring""" a =[ '''model.encoder.layernorm_embedding.weight''', '''model.encoder.layernorm_embedding.bias''', '''model.decoder.layernorm_embedding.weight''', '''model.decoder.layernorm_embedding.bias''', ] for k in keys: a =sd.pop(lowercase ) a =k.replace('''layernorm_embedding''' , '''layer_norm''' ) assert new_k not in sd a =v lowerCamelCase_ : List[str] = ["""START"""] @torch.no_grad() def _A ( lowercase , lowercase , lowercase ): """simple docstring""" a =torch.load(lowercase , map_location='''cpu''' ) a =model['''model'''] a =BlenderbotConfig.from_json_file(lowercase ) a =BlenderbotForConditionalGeneration(lowercase ) a =m.model.state_dict().keys() a =[] a ={} for k, v in sd.items(): if k in IGNORE_KEYS: continue a =rename_state_dict_key(lowercase ) if new_k not in valid_keys: failures.append([k, new_k] ) else: a =v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(lowercase ) m.model.load_state_dict(lowercase , strict=lowercase ) m.half() m.save_pretrained(lowercase ) if __name__ == "__main__": lowerCamelCase_ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("""--src_path""", type=str, help="""like blenderbot-model.bin""") parser.add_argument("""--save_dir""", default="""hf_blenderbot""", type=str, help="""Where to save converted model.""") parser.add_argument( """--hf_config_json""", default="""blenderbot-3b-config.json""", type=str, help="""Path to config to use""" ) lowerCamelCase_ : Dict = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
81
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class __A ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a ={ '''task_specific_params''': { '''summarization''': {'''length_penalty''': 1.0, '''max_length''': 128, '''min_length''': 12, '''num_beams''': 4}, '''summarization_cnn''': {'''length_penalty''': 2.0, '''max_length''': 142, '''min_length''': 56, '''num_beams''': 4}, '''summarization_xsum''': {'''length_penalty''': 1.0, '''max_length''': 62, '''min_length''': 11, '''num_beams''': 6}, } } a ={ '''task_specific_params.summarization.length_penalty''': 1.0, '''task_specific_params.summarization.max_length''': 128, '''task_specific_params.summarization.min_length''': 12, '''task_specific_params.summarization.num_beams''': 4, '''task_specific_params.summarization_cnn.length_penalty''': 2.0, '''task_specific_params.summarization_cnn.max_length''': 142, '''task_specific_params.summarization_cnn.min_length''': 56, '''task_specific_params.summarization_cnn.num_beams''': 4, '''task_specific_params.summarization_xsum.length_penalty''': 1.0, '''task_specific_params.summarization_xsum.max_length''': 62, '''task_specific_params.summarization_xsum.min_length''': 11, '''task_specific_params.summarization_xsum.num_beams''': 6, } self.assertEqual(flatten_dict(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(__A ) , x.transpose() ) ) a =np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =np.random.randn(3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(transpose(__A ) , transpose(__A ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , transpose(__A , axes=(1, 2, 0) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(transpose(__A ) , transpose(__A ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =tf.constant(__A ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , transpose(__A , axes=(1, 2, 0) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Any: a =np.random.randn(3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(transpose(__A ) , np.asarray(transpose(__A ) ) ) ) a =np.random.randn(3 , 4 , 5 ) a =jnp.array(__A ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , np.asarray(transpose(__A , axes=(1, 2, 0) ) ) ) ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , np.reshape(__A , (4, 3) ) ) ) a =np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , np.reshape(__A , (12, 5) ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> int: a =np.random.randn(3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , reshape(__A , (4, 3) ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , reshape(__A , (12, 5) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =np.random.randn(3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , reshape(__A , (4, 3) ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =tf.constant(__A ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , reshape(__A , (12, 5) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =np.random.randn(3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , np.asarray(reshape(__A , (4, 3) ) ) ) ) a =np.random.randn(3 , 4 , 5 ) a =jnp.array(__A ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , np.asarray(reshape(__A , (12, 5) ) ) ) ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(__A ) , np.squeeze(__A ) ) ) a =np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , np.squeeze(__A , axis=2 ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =np.random.randn(1 , 3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(squeeze(__A ) , squeeze(__A ).numpy() ) ) a =np.random.randn(1 , 4 , 1 , 5 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , squeeze(__A , axis=2 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =np.random.randn(1 , 3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(squeeze(__A ) , squeeze(__A ).numpy() ) ) a =np.random.randn(1 , 4 , 1 , 5 ) a =tf.constant(__A ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , squeeze(__A , axis=2 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =np.random.randn(1 , 3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(squeeze(__A ) , np.asarray(squeeze(__A ) ) ) ) a =np.random.randn(1 , 4 , 1 , 5 ) a =jnp.array(__A ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , np.asarray(squeeze(__A , axis=2 ) ) ) ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , np.expand_dims(__A , axis=1 ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , expand_dims(__A , axis=1 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> int: a =np.random.randn(3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , expand_dims(__A , axis=1 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =np.random.randn(3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , np.asarray(expand_dims(__A , axis=1 ) ) ) )
81
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = DistilBertTokenizer __lowerCAmelCase = DistilBertTokenizerFast __lowerCAmelCase = True @slow def SCREAMING_SNAKE_CASE ( self ) -> int: a =DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
81
1
"""simple docstring""" lowerCamelCase_ : Any = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor from ..utils import is_datasets_available from .base import PipelineTool if is_datasets_available(): from datasets import load_dataset class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "microsoft/speecht5_tts" __lowerCAmelCase = ( "This is a tool that reads an English text out loud. It takes an input named `text` which should contain the " "text to read (in English) and returns a waveform object containing the sound." ) __lowerCAmelCase = "text_reader" __lowerCAmelCase = SpeechTaProcessor __lowerCAmelCase = SpeechTaForTextToSpeech __lowerCAmelCase = SpeechTaHifiGan __lowerCAmelCase = ["text"] __lowerCAmelCase = ["audio"] def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if self.post_processor is None: a ='''microsoft/speecht5_hifigan''' super().setup() def SCREAMING_SNAKE_CASE ( self , __A , __A=None ) -> Optional[int]: a =self.pre_processor(text=__A , return_tensors='''pt''' , truncation=__A ) if speaker_embeddings is None: if not is_datasets_available(): raise ImportError('''Datasets needs to be installed if not passing speaker embeddings.''' ) a =load_dataset('''Matthijs/cmu-arctic-xvectors''' , split='''validation''' ) a =torch.tensor(embeddings_dataset[7305]['''xvector'''] ).unsqueeze(0 ) return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings} def SCREAMING_SNAKE_CASE ( self , __A ) -> List[Any]: with torch.no_grad(): return self.model.generate_speech(**__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> List[Any]: with torch.no_grad(): return self.post_processor(__A ).cpu().detach()
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
1
"""simple docstring""" def _A ( lowercase , lowercase = " " ): """simple docstring""" a =[] a =0 for index, char in enumerate(lowercase ): if char == separator: split_words.append(string[last_index:index] ) a =index + 1 elif index + 1 == len(lowercase ): split_words.append(string[last_index : index + 1] ) return split_words if __name__ == "__main__": from doctest import testmod testmod()
81
"""simple docstring""" import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Any: 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 SCREAMING_SNAKE_CASE ( self ) -> str: self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_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]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =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 ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer lowerCamelCase_ : Optional[int] = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} lowerCamelCase_ : Optional[int] = { """vocab_file""": {"""mobilebert-uncased""": """https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt"""}, """tokenizer_file""": { """mobilebert-uncased""": """https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json""" }, } lowerCamelCase_ : Union[str, Any] = {"""mobilebert-uncased""": 5_1_2} lowerCamelCase_ : Any = {} class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_INIT_CONFIGURATION __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = MobileBertTokenizer def __init__( self , __A=None , __A=None , __A=True , __A="[UNK]" , __A="[SEP]" , __A="[PAD]" , __A="[CLS]" , __A="[MASK]" , __A=True , __A=None , **__A , ) -> Union[str, Any]: 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 , ) a =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 ): a =getattr(__A , normalizer_state.pop('''type''' ) ) a =do_lower_case a =strip_accents a =tokenize_chinese_chars a =normalizer_class(**__A ) a =do_lower_case def SCREAMING_SNAKE_CASE ( self , __A , __A=None ) -> int: a =[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 SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: a =self._tokenizer.model.save(__A , name=__A ) return tuple(__A )
81
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCamelCase_ : List[Any] = { """configuration_owlvit""": [ """OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OwlViTConfig""", """OwlViTOnnxConfig""", """OwlViTTextConfig""", """OwlViTVisionConfig""", ], """processing_owlvit""": ["""OwlViTProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""OwlViTFeatureExtractor"""] lowerCamelCase_ : List[Any] = ["""OwlViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = [ """OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OwlViTModel""", """OwlViTPreTrainedModel""", """OwlViTTextModel""", """OwlViTVisionModel""", """OwlViTForObjectDetection""", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys lowerCamelCase_ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" while second != 0: a =first & second first ^= second a =c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Dict = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : List[Any] = int(input("""Enter the second number: """).strip()) print(F'{add(first, second) = }')
81
1
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["image_processor", "tokenizer"] __lowerCAmelCase = "AutoImageProcessor" __lowerCAmelCase = "AutoTokenizer" def __init__( self , __A , __A ) -> List[str]: super().__init__(__A , __A ) a =self.image_processor def __call__( self , __A=None , __A=None , __A=None , **__A ) -> Optional[int]: 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: a =self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: a =self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: a =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def SCREAMING_SNAKE_CASE ( self , *__A , **__A ) -> str: return self.tokenizer.batch_decode(*__A , **__A ) def SCREAMING_SNAKE_CASE ( self , *__A , **__A ) -> str: return self.tokenizer.decode(*__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: return ["input_ids", "attention_mask", "pixel_values"]
81
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
1
"""simple docstring""" import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def _A ( lowercase , lowercase , **lowercase ): """simple docstring""" a =AutoConfig.from_pretrained(lowercase , **lowercase ) a =AutoModelForSeqaSeqLM.from_config(lowercase ) model.save_pretrained(lowercase ) AutoTokenizer.from_pretrained(lowercase ).save_pretrained(lowercase ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
81
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCamelCase_ : str = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *__A , **__A ) -> None: warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , __A , ) super().__init__(*__A , **__A )
81
1
"""simple docstring""" def _A ( ): """simple docstring""" return 1 def _A ( lowercase ): """simple docstring""" return 0 if x < 0 else two_pence(x - 2 ) + one_pence() def _A ( lowercase ): """simple docstring""" return 0 if x < 0 else five_pence(x - 5 ) + two_pence(lowercase ) def _A ( lowercase ): """simple docstring""" return 0 if x < 0 else ten_pence(x - 10 ) + five_pence(lowercase ) def _A ( lowercase ): """simple docstring""" return 0 if x < 0 else twenty_pence(x - 20 ) + ten_pence(lowercase ) def _A ( lowercase ): """simple docstring""" return 0 if x < 0 else fifty_pence(x - 50 ) + twenty_pence(lowercase ) def _A ( lowercase ): """simple docstring""" return 0 if x < 0 else one_pound(x - 1_00 ) + fifty_pence(lowercase ) def _A ( lowercase ): """simple docstring""" return 0 if x < 0 else two_pound(x - 2_00 ) + one_pound(lowercase ) def _A ( lowercase = 2_00 ): """simple docstring""" return two_pound(lowercase ) if __name__ == "__main__": print(solution(int(input().strip())))
81
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
1
"""simple docstring""" from __future__ import annotations def _A ( lowercase , lowercase ): """simple docstring""" a =sorted(numsa + numsa ) a , a =divmod(len(lowercase ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Tuple = [float(x) for x in input("""Enter the elements of first array: """).split()] lowerCamelCase_ : Optional[Any] = [float(x) for x in input("""Enter the elements of second array: """).split()] print(F'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
81
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
1
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" if b == 0: return 1 if (b % 2) == 0: return actual_power(lowercase , int(b / 2 ) ) * actual_power(lowercase , int(b / 2 ) ) else: return a * actual_power(lowercase , int(b / 2 ) ) * actual_power(lowercase , int(b / 2 ) ) def _A ( lowercase , lowercase ): """simple docstring""" if b < 0: return 1 / actual_power(lowercase , lowercase ) return actual_power(lowercase , lowercase ) if __name__ == "__main__": print(power(-2, -3))
81
"""simple docstring""" lowerCamelCase_ : Any = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
81
1
"""simple docstring""" def _A ( lowercase ): """simple docstring""" if not isinstance(lowercase , lowercase ): a =f'''Input value of [number={number}] must be an integer''' raise TypeError(lowercase ) if number < 1: a =f'''Input value of [number={number}] must be > 0''' raise ValueError(lowercase ) a =1 for i in range(1 , lowercase ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
81
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ lowerCamelCase_ : Optional[Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ lowerCamelCase_ : Optional[int] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Optional[Any]: if return_pvalue: a =pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
81
1
"""simple docstring""" import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["image_processor", "tokenizer"] __lowerCAmelCase = "ViTImageProcessor" __lowerCAmelCase = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self , __A=None , __A=None , **__A ) -> List[Any]: a =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 , ) a =kwargs.pop('''feature_extractor''' ) a =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 , __A=None , __A=None , __A=None , __A=None , **__A ) -> Any: if text is None and visual_prompt is None and images is None: raise ValueError('''You have to specify either text, visual prompt or images.''' ) if text is not None and visual_prompt is not None: raise ValueError('''You have to specify exactly one type of prompt. Either text or visual prompt.''' ) if text is not None: a =self.tokenizer(__A , return_tensors=__A , **__A ) if visual_prompt is not None: a =self.image_processor(__A , return_tensors=__A , **__A ) if images is not None: a =self.image_processor(__A , return_tensors=__A , **__A ) if visual_prompt is not None and images is not None: a ={ '''pixel_values''': image_features.pixel_values, '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: a =image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: a ={ '''conditional_pixel_values''': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def SCREAMING_SNAKE_CASE ( self , *__A , **__A ) -> str: return self.tokenizer.batch_decode(*__A , **__A ) def SCREAMING_SNAKE_CASE ( self , *__A , **__A ) -> Tuple: return self.tokenizer.decode(*__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __A , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __A , ) return self.image_processor
81
"""simple docstring""" lowerCamelCase_ : int = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Union[str, Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : List[Any] = logging.get_logger(__name__) lowerCamelCase_ : Optional[int] = { """facebook/timesformer""": """https://huggingface.co/facebook/timesformer/resolve/main/config.json""", } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "timesformer" def __init__( self , __A=224 , __A=16 , __A=3 , __A=8 , __A=768 , __A=12 , __A=12 , __A=3072 , __A="gelu" , __A=0.0 , __A=0.0 , __A=0.02 , __A=1E-6 , __A=True , __A="divided_space_time" , __A=0 , **__A , ) -> Dict: super().__init__(**__A ) a =image_size a =patch_size a =num_channels a =num_frames a =hidden_size a =num_hidden_layers a =num_attention_heads a =intermediate_size a =hidden_act a =hidden_dropout_prob a =attention_probs_dropout_prob a =initializer_range a =layer_norm_eps a =qkv_bias a =attention_type a =drop_path_rate
81
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
1
"""simple docstring""" import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging lowerCamelCase_ : int = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , __A ) -> str: super().__init__() a =nn.ModuleList(__A ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A , __A , __A , __A = None , __A = None , __A = None , __A = None , __A = False , __A = True , ) -> Union[ControlNetOutput, Tuple]: for i, (image, scale, controlnet) in enumerate(zip(__A , __A , self.nets ) ): a , a =controlnet( __A , __A , __A , __A , __A , __A , __A , __A , __A , __A , __A , ) # merge samples if i == 0: a , a =down_samples, mid_sample else: a =[ samples_prev + samples_curr for samples_prev, samples_curr in zip(__A , __A ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def SCREAMING_SNAKE_CASE ( self , __A , __A = True , __A = None , __A = False , __A = None , ) -> List[Any]: a =0 a =save_directory for controlnet in self.nets: controlnet.save_pretrained( __A , is_main_process=__A , save_function=__A , safe_serialization=__A , variant=__A , ) idx += 1 a =model_path_to_save + f'''_{idx}''' @classmethod def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> int: a =0 a =[] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... a =pretrained_model_path while os.path.isdir(__A ): a =ControlNetModel.from_pretrained(__A , **__A ) controlnets.append(__A ) idx += 1 a =pretrained_model_path + f'''_{idx}''' logger.info(f'''{len(__A )} controlnets loaded from {pretrained_model_path}.''' ) if len(__A ) == 0: raise ValueError( f'''No ControlNets found under {os.path.dirname(__A )}. Expected at least {pretrained_model_path + "_0"}.''' ) return cls(__A )
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class __A ( metaclass=_SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["onnx"] def __init__( self , *__A , **__A ) -> Dict: requires_backends(self , ['''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> int: requires_backends(cls , ['''onnx'''] ) @classmethod def SCREAMING_SNAKE_CASE ( cls , *__A , **__A ) -> str: requires_backends(cls , ['''onnx'''] )
81
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy lowerCamelCase_ : Dict = logging.getLogger(__name__) lowerCamelCase_ : Tuple = """pytorch_model.bin""" @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}, ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "A csv or a json file containing the validation data."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The name of the task to train on."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) __lowerCAmelCase = dataclasses.field( default="accuracy", metadata={"help": "The evaluation metric used for the task."} ) __lowerCAmelCase = dataclasses.field( default="no", metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" }, ) __lowerCAmelCase = dataclasses.field( default=10, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." }, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}, ) __lowerCAmelCase = dataclasses.field( default=100, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Random seed for initialization."}, ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a =dataset.filter(lambda lowercase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a =int(eval_result * len(lowercase ) ) print(lowercase ) a =dataset.sort('''probability''' , reverse=lowercase ) a =dataset.select(range(lowercase ) ) a =dataset.remove_columns(['''label''', '''probability'''] ) a =dataset.rename_column('''prediction''' , '''label''' ) a =dataset.map(lambda lowercase : {"label": idalabel[example["label"]]} ) a =dataset.shuffle(seed=args.seed ) a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase , index=lowercase ) else: dataset.to_json(lowercase ) def _A ( lowercase , lowercase , lowercase , lowercase , **lowercase ): """simple docstring""" a =Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() a =STModelArguments(model_name_or_path=lowercase ) a =STDataArguments(train_file=lowercase , infer_file=lowercase ) a =STTrainingArguments(output_dir=lowercase ) a =argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase ).items(): setattr(lowercase , lowercase , lowercase ) for key, value in kwargs.items(): if hasattr(lowercase , lowercase ): setattr(lowercase , lowercase , lowercase ) # Sanity checks a ={} a =None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None a =args.train_file a =args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a =args.eval_file for key in data_files: a =data_files[key].split('''.''' )[-1] assert extension in ["csv", "json"], f'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: a =extension else: assert extension == args.data_file_extension, f'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), f'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info('''Creating the initial data directory for self-training...''' ) a =f'''{args.output_dir}/self-train_iter-{{}}'''.format a =data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) accelerator.wait_for_everyone() a =None a =None a =0 a =False # Show the progress bar a =tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): a =data_dir_format(lowercase ) assert os.path.exists(lowercase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a =os.path.join(lowercase , '''stage-1''' ) a ={ '''accelerator''': accelerator, '''model_name_or_path''': args.model_name_or_path, '''cache_dir''': args.cache_dir, '''do_train''': True, '''train_file''': data_files['''train'''] if iteration == 0 else data_files['''train_pseudo'''], '''do_eval''': True if args.eval_file is not None else False, '''eval_file''': data_files['''eval'''], '''do_predict''': True, '''infer_file''': data_files['''infer'''], '''task_name''': args.task_name, '''label_list''': args.label_list, '''output_dir''': current_output_dir, '''eval_metric''': args.eval_metric, '''evaluation_strategy''': args.evaluation_strategy, '''early_stopping_patience''': args.early_stopping_patience, '''early_stopping_threshold''': args.early_stopping_threshold, '''seed''': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(lowercase , lowercase ): arguments_dict.update({key: value} ) a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , lowercase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a =os.path.join(lowercase , '''best-checkpoint''' ) a =os.path.join(lowercase , '''stage-2''' ) # Update arguments_dict a =model_path a =data_files['''train'''] a =current_output_dir a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , lowercase ) a =iteration a =data_dir_format(iteration + 1 ) a =AutoConfig.from_pretrained(os.path.join(lowercase , '''best-checkpoint''' ) ) a =config.idalabel a =os.path.join(lowercase , '''eval_results_best-checkpoint.json''' ) a =os.path.join(lowercase , '''test_results_best-checkpoint.json''' ) assert os.path.exists(lowercase ) with open(lowercase , '''r''' ) as f: a =float(json.load(lowercase )[args.eval_metric] ) a =os.path.join(lowercase , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(lowercase ) # Loading the dataset from local csv or json files. a =load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )['''data'''] a =load_dataset('''csv''' , data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(lowercase , exist_ok=lowercase ) shutil.copy(lowercase , os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase ): shutil.copy(lowercase , os.path.join(lowercase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) accelerator.wait_for_everyone() a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a =eval_result if best_iteration is None: a =new_iteration a =new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a =new_iteration a =new_eval_result a =0 else: if new_eval_result == best_eval_result: a =new_iteration a =new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a =True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info('''Best iteration: %d''' , lowercase ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , ) else: # Assume that the last iteration is the best logger.info('''Best iteration: %d''' , args.max_selftrain_iterations - 1 ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , )
81
1
"""simple docstring""" import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def _A ( lowercase ): """simple docstring""" random.seed(lowercase ) np.random.seed(lowercase ) torch.manual_seed(lowercase ) torch.cuda.manual_seed_all(lowercase ) # ^^ safe to call this function even if cuda is not available class __A : """simple docstring""" def __init__( self , __A , __A = 0.9_999 , __A = 0.0 , __A = 0 , __A = False , __A = 1.0 , __A = 2 / 3 , __A = None , __A = None , **__A , ) -> Optional[int]: if isinstance(__A , torch.nn.Module ): a =( '''Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. ''' '''Please pass the parameters of the module instead.''' ) deprecate( '''passing a `torch.nn.Module` to `ExponentialMovingAverage`''' , '''1.0.0''' , __A , standard_warn=__A , ) a =parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility a =True if kwargs.get('''max_value''' , __A ) is not None: a ='''The `max_value` argument is deprecated. Please use `decay` instead.''' deprecate('''max_value''' , '''1.0.0''' , __A , standard_warn=__A ) a =kwargs['''max_value'''] if kwargs.get('''min_value''' , __A ) is not None: a ='''The `min_value` argument is deprecated. Please use `min_decay` instead.''' deprecate('''min_value''' , '''1.0.0''' , __A , standard_warn=__A ) a =kwargs['''min_value'''] a =list(__A ) a =[p.clone().detach() for p in parameters] if kwargs.get('''device''' , __A ) is not None: a ='''The `device` argument is deprecated. Please use `to` instead.''' deprecate('''device''' , '''1.0.0''' , __A , standard_warn=__A ) self.to(device=kwargs['''device'''] ) a =None a =decay a =min_decay a =update_after_step a =use_ema_warmup a =inv_gamma a =power a =0 a =None # set in `step()` a =model_cls a =model_config @classmethod def SCREAMING_SNAKE_CASE ( cls , __A , __A ) -> "EMAModel": a , a =model_cls.load_config(__A , return_unused_kwargs=__A ) a =model_cls.from_pretrained(__A ) a =cls(model.parameters() , model_cls=__A , model_config=model.config ) ema_model.load_state_dict(__A ) return ema_model def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: if self.model_cls is None: raise ValueError('''`save_pretrained` can only be used if `model_cls` was defined at __init__.''' ) if self.model_config is None: raise ValueError('''`save_pretrained` can only be used if `model_config` was defined at __init__.''' ) a =self.model_cls.from_config(self.model_config ) a =self.state_dict() state_dict.pop('''shadow_params''' , __A ) model.register_to_config(**__A ) self.copy_to(model.parameters() ) model.save_pretrained(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> float: a =max(0 , optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: a =1 - (1 + step / self.inv_gamma) ** -self.power else: a =(1 + step) / (10 + step) a =min(__A , self.decay ) # make sure decay is not smaller than min_decay a =max(__A , self.min_decay ) return cur_decay_value @torch.no_grad() def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: if isinstance(__A , torch.nn.Module ): a =( '''Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. ''' '''Please pass the parameters of the module instead.''' ) deprecate( '''passing a `torch.nn.Module` to `ExponentialMovingAverage.step`''' , '''1.0.0''' , __A , standard_warn=__A , ) a =parameters.parameters() a =list(__A ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. a =self.get_decay(self.optimization_step ) a =decay a =1 - decay a =contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params , __A ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): a =deepspeed.zero.GatheredParameters(__A , modifier_rank=__A ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> None: a =list(__A ) for s_param, param in zip(self.shadow_params , __A ): param.data.copy_(s_param.to(param.device ).data ) def SCREAMING_SNAKE_CASE ( self , __A=None , __A=None ) -> None: a =[ p.to(device=__A , dtype=__A ) if p.is_floating_point() else p.to(device=__A ) for p in self.shadow_params ] def SCREAMING_SNAKE_CASE ( self ) -> dict: return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def SCREAMING_SNAKE_CASE ( self , __A ) -> None: a =[param.detach().cpu().clone() for param in parameters] def SCREAMING_SNAKE_CASE ( self , __A ) -> None: if self.temp_stored_params is None: raise RuntimeError('''This ExponentialMovingAverage has no `store()`ed weights ''' '''to `restore()`''' ) for c_param, param in zip(self.temp_stored_params , __A ): param.data.copy_(c_param.data ) # Better memory-wise. a =None def SCREAMING_SNAKE_CASE ( self , __A ) -> None: a =copy.deepcopy(__A ) a =state_dict.get('''decay''' , self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError('''Decay must be between 0 and 1''' ) a =state_dict.get('''min_decay''' , self.min_decay ) if not isinstance(self.min_decay , __A ): raise ValueError('''Invalid min_decay''' ) a =state_dict.get('''optimization_step''' , self.optimization_step ) if not isinstance(self.optimization_step , __A ): raise ValueError('''Invalid optimization_step''' ) a =state_dict.get('''update_after_step''' , self.update_after_step ) if not isinstance(self.update_after_step , __A ): raise ValueError('''Invalid update_after_step''' ) a =state_dict.get('''use_ema_warmup''' , self.use_ema_warmup ) if not isinstance(self.use_ema_warmup , __A ): raise ValueError('''Invalid use_ema_warmup''' ) a =state_dict.get('''inv_gamma''' , self.inv_gamma ) if not isinstance(self.inv_gamma , (float, int) ): raise ValueError('''Invalid inv_gamma''' ) a =state_dict.get('''power''' , self.power ) if not isinstance(self.power , (float, int) ): raise ValueError('''Invalid power''' ) a =state_dict.get('''shadow_params''' , __A ) if shadow_params is not None: a =shadow_params if not isinstance(self.shadow_params , __A ): raise ValueError('''shadow_params must be a list''' ) if not all(isinstance(__A , torch.Tensor ) for p in self.shadow_params ): raise ValueError('''shadow_params must all be Tensors''' )
81
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ : str = logging.get_logger(__name__) lowerCamelCase_ : Dict = { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json""", # See all REALM models at https://huggingface.co/models?filter=realm } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "realm" def __init__( self , __A=3_0522 , __A=768 , __A=128 , __A=12 , __A=12 , __A=8 , __A=3072 , __A="gelu_new" , __A=0.1 , __A=0.1 , __A=512 , __A=2 , __A=0.02 , __A=1E-1_2 , __A=256 , __A=10 , __A=1E-3 , __A=5 , __A=320 , __A=1335_3718 , __A=5000 , __A=1 , __A=0 , __A=2 , **__A , ) -> str: super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A ) # Common config a =vocab_size a =max_position_embeddings a =hidden_size a =retriever_proj_size a =num_hidden_layers a =num_attention_heads a =num_candidates a =intermediate_size a =hidden_act a =hidden_dropout_prob a =attention_probs_dropout_prob a =initializer_range a =type_vocab_size a =layer_norm_eps # Reader config a =span_hidden_size a =max_span_width a =reader_layer_norm_eps a =reader_beam_size a =reader_seq_len # Retrieval config a =num_block_records a =searcher_beam_size
81
"""simple docstring""" from math import factorial def _A ( lowercase = 1_00 ): """simple docstring""" return sum(int(lowercase ) for x in str(factorial(lowercase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
81
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class __A ( unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE ( self ) -> Tuple: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a =AutoConfig.from_pretrained(__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =TFAutoModel.from_pretrained(__A , from_pt=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =AutoModel.from_pretrained(__A , from_tf=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Tuple: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a =AutoConfig.from_pretrained(__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =TFAutoModelForPreTraining.from_pretrained(__A , from_pt=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =AutoModelForPreTraining.from_pretrained(__A , from_tf=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> int: for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a =AutoConfig.from_pretrained(__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =TFAutoModelForCausalLM.from_pretrained(__A , from_pt=__A ) a , a =TFAutoModelForCausalLM.from_pretrained( __A , output_loading_info=__A , from_pt=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =AutoModelForCausalLM.from_pretrained(__A , from_tf=__A ) a , a =AutoModelForCausalLM.from_pretrained( __A , output_loading_info=__A , from_tf=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> str: for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a =AutoConfig.from_pretrained(__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =TFAutoModelWithLMHead.from_pretrained(__A , from_pt=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =AutoModelWithLMHead.from_pretrained(__A , from_tf=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a =AutoConfig.from_pretrained(__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =TFAutoModelForMaskedLM.from_pretrained(__A , from_pt=__A ) a , a =TFAutoModelForMaskedLM.from_pretrained( __A , output_loading_info=__A , from_pt=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =AutoModelForMaskedLM.from_pretrained(__A , from_tf=__A ) a , a =AutoModelForMaskedLM.from_pretrained( __A , output_loading_info=__A , from_tf=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a =AutoConfig.from_pretrained(__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =TFAutoModelForSeqaSeqLM.from_pretrained(__A , from_pt=__A ) a , a =TFAutoModelForSeqaSeqLM.from_pretrained( __A , output_loading_info=__A , from_pt=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =AutoModelForSeqaSeqLM.from_pretrained(__A , from_tf=__A ) a , a =AutoModelForSeqaSeqLM.from_pretrained( __A , output_loading_info=__A , from_tf=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Tuple: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a =AutoConfig.from_pretrained(__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =TFAutoModelForSequenceClassification.from_pretrained(__A , from_pt=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =AutoModelForSequenceClassification.from_pretrained(__A , from_tf=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) @slow def SCREAMING_SNAKE_CASE ( self ) -> str: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a =AutoConfig.from_pretrained(__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =TFAutoModelForQuestionAnswering.from_pretrained(__A , from_pt=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) a =AutoModelForQuestionAnswering.from_pretrained(__A , from_tf=__A ) self.assertIsNotNone(__A ) self.assertIsInstance(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =TFAutoModelWithLMHead.from_pretrained(__A , from_pt=__A ) self.assertIsInstance(__A , __A ) self.assertEqual(model.num_parameters() , 1_4410 ) self.assertEqual(model.num_parameters(only_trainable=__A ) , 1_4410 ) a =AutoModelWithLMHead.from_pretrained(__A , from_tf=__A ) self.assertIsInstance(__A , __A ) self.assertEqual(model.num_parameters() , 1_4410 ) self.assertEqual(model.num_parameters(only_trainable=__A ) , 1_4410 ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =TFAutoModelWithLMHead.from_pretrained(__A , from_pt=__A ) self.assertIsInstance(__A , __A ) self.assertEqual(model.num_parameters() , 1_4410 ) self.assertEqual(model.num_parameters(only_trainable=__A ) , 1_4410 ) a =AutoModelWithLMHead.from_pretrained(__A , from_tf=__A ) self.assertIsInstance(__A , __A ) self.assertEqual(model.num_parameters() , 1_4410 ) self.assertEqual(model.num_parameters(only_trainable=__A ) , 1_4410 )
81
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = """▁""" lowerCamelCase_ : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : Any = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowerCamelCase_ : Tuple = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} 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 , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a =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 a ={'''<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 a =1 a =len(self.sp_model ) + self.fairseq_offset a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: a =self.__dict__.copy() a =None a =self.sp_model.serialized_model_proto() return state def __setstate__( self , __A ) -> List[Any]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =''''''.join(__A ).replace(__A , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =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: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
1
import datasets from .evaluate import evaluate UpperCAmelCase__ = "\\n@inproceedings{Rajpurkar2016SQuAD10,\n title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n booktitle={EMNLP},\n year={2016}\n}\n" UpperCAmelCase__ = "\nThis metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n" UpperCAmelCase__ = "\nComputes SQuAD scores (F1 and EM).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - 'id': id of the question-answer pair as given in the references (see below)\n - 'prediction_text': the text of the answer\n references: List of question-answers dictionaries with the following key-values:\n - 'id': id of the question-answer pair (see above),\n - 'answers': a Dict in the SQuAD dataset format\n {\n 'text': list of possible texts for the answer, as a list of strings\n 'answer_start': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n 'exact_match': Exact match (the normalized answer exactly match the gold answer)\n 'f1': The F-score of predicted tokens versus the gold answer\nExamples:\n\n >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22'}]\n >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]\n >>> squad_metric = datasets.load_metric(\"squad\")\n >>> results = squad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 100.0, 'f1': 100.0}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase_ ( datasets.Metric ): '''simple docstring''' def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': {'''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.Value('''string''' )}, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://rajpurkar.github.io/SQuAD-explorer/'''] , reference_urls=['''https://rajpurkar.github.io/SQuAD-explorer/'''] , ) def __lowerCAmelCase ( self : str , __UpperCAmelCase : int , __UpperCAmelCase : List[Any] ) ->Optional[int]: """simple docstring""" a = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} a = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] a = evaluate(dataset=__UpperCAmelCase , predictions=__UpperCAmelCase ) return score
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : str = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : Tuple = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} 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 , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a ={'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} a =len(self.sp_model ) - 1 a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ) -> Any: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> int: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) return spm_id if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =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: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
0
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class __A ( unittest.TestCase ): def _lowercase (self : Dict ): UpperCAmelCase_ = "laion/clap-htsat-unfused" UpperCAmelCase_ = tempfile.mkdtemp() def _lowercase (self : Dict , **__a : List[Any] ): return RobertaTokenizer.from_pretrained(self.checkpoint , **__a ) def _lowercase (self : str , **__a : Union[str, Any] ): return ClapFeatureExtractor.from_pretrained(self.checkpoint , **__a ) def _lowercase (self : str ): shutil.rmtree(self.tmpdirname ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.get_tokenizer() UpperCAmelCase_ = self.get_feature_extractor() UpperCAmelCase_ = ClapProcessor(tokenizer=__a , feature_extractor=__a ) processor.save_pretrained(self.tmpdirname ) UpperCAmelCase_ = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) UpperCAmelCase_ = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) UpperCAmelCase_ = self.get_feature_extractor(do_normalize=__a , padding_value=1.0 ) UpperCAmelCase_ = ClapProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __a ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __a ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.get_feature_extractor() UpperCAmelCase_ = self.get_tokenizer() UpperCAmelCase_ = ClapProcessor(tokenizer=__a , feature_extractor=__a ) UpperCAmelCase_ = floats_list((3, 1000) ) UpperCAmelCase_ = feature_extractor(__a , return_tensors="np" ) UpperCAmelCase_ = processor(audios=__a , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.get_feature_extractor() UpperCAmelCase_ = self.get_tokenizer() UpperCAmelCase_ = ClapProcessor(tokenizer=__a , feature_extractor=__a ) UpperCAmelCase_ = "This is a test string" UpperCAmelCase_ = processor(text=__a ) UpperCAmelCase_ = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _lowercase (self : int ): UpperCAmelCase_ = self.get_feature_extractor() UpperCAmelCase_ = self.get_tokenizer() UpperCAmelCase_ = ClapProcessor(tokenizer=__a , feature_extractor=__a ) UpperCAmelCase_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCAmelCase_ = processor.batch_decode(__a ) UpperCAmelCase_ = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_feature_extractor() UpperCAmelCase_ = self.get_tokenizer() UpperCAmelCase_ = ClapProcessor(tokenizer=__a , feature_extractor=__a ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , )
1
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase : Union[str, Any] = { 'configuration_xlm_roberta_xl': [ 'XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMRobertaXLConfig', 'XLMRobertaXLOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : int = [ 'XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLMRobertaXLForCausalLM', 'XLMRobertaXLForMaskedLM', 'XLMRobertaXLForMultipleChoice', 'XLMRobertaXLForQuestionAnswering', 'XLMRobertaXLForSequenceClassification', 'XLMRobertaXLForTokenClassification', 'XLMRobertaXLModel', 'XLMRobertaXLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
2
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = DistilBertTokenizer __lowerCAmelCase = DistilBertTokenizerFast __lowerCAmelCase = True @slow def SCREAMING_SNAKE_CASE ( self ) -> int: a =DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
81
0
'''simple docstring''' import requests lowercase : List[str] = 'YOUR API KEY' def lowerCAmelCase_ ( snake_case__ , snake_case__ = giphy_api_key ): '''simple docstring''' A : str = '''+'''.join(query.split() ) A : Optional[Any] = F'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}' A : Any = requests.get(snake_case__ ).json()['''data'''] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
3
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
0
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class UpperCAmelCase_ ( unittest.TestCase ): def __init__( self : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Union[str, Any]=3 , UpperCAmelCase__ : Any=3_0 , UpperCAmelCase__ : str=4_0_0 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=1 / 2_5_5 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : List[Any]=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Any=[0.5, 0.5, 0.5] , UpperCAmelCase__ : Optional[int]=True , ) -> Any: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p lowerCAmelCase = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = num_channels lowerCAmelCase = min_resolution lowerCAmelCase = max_resolution lowerCAmelCase = do_resize lowerCAmelCase = size lowerCAmelCase = do_rescale lowerCAmelCase = rescale_factor lowerCAmelCase = do_normalize lowerCAmelCase = image_mean lowerCAmelCase = image_std lowerCAmelCase = do_pad def __UpperCAmelCase ( self : int ) -> Dict: return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __UpperCAmelCase ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict=False ) -> str: if not batched: lowerCAmelCase = image_inputs[0] if isinstance(UpperCAmelCase__ , Image.Image ): lowerCAmelCase , lowerCAmelCase = image.size else: lowerCAmelCase , lowerCAmelCase = image.shape[1], image.shape[2] if w < h: lowerCAmelCase = int(self.size['shortest_edge'] * h / w ) lowerCAmelCase = self.size['shortest_edge'] elif w > h: lowerCAmelCase = self.size['shortest_edge'] lowerCAmelCase = int(self.size['shortest_edge'] * w / h ) else: lowerCAmelCase = self.size['shortest_edge'] lowerCAmelCase = self.size['shortest_edge'] else: lowerCAmelCase = [] for image in image_inputs: lowerCAmelCase , lowerCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowerCAmelCase = max(UpperCAmelCase__ , key=lambda UpperCAmelCase__ : item[0] )[0] lowerCAmelCase = max(UpperCAmelCase__ , key=lambda UpperCAmelCase__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class UpperCAmelCase_ ( __lowercase , unittest.TestCase ): lowerCamelCase : List[str] = DetrImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self : Tuple ) -> List[Any]: lowerCAmelCase = DetrImageProcessingTester(self ) @property def __UpperCAmelCase ( self : Optional[int] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self : str ) -> str: lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase__ , 'image_mean' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'image_std' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'do_normalize' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'do_rescale' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'rescale_factor' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'do_resize' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'size' ) ) self.assertTrue(hasattr(UpperCAmelCase__ , 'do_pad' ) ) def __UpperCAmelCase ( self : Optional[int] ) -> List[str]: lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , UpperCAmelCase__ ) lowerCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=UpperCAmelCase__ ) self.assertEqual(image_processor.size , {'shortest_edge': 4_2, 'longest_edge': 8_4} ) self.assertEqual(image_processor.do_pad , UpperCAmelCase__ ) def __UpperCAmelCase ( self : Union[str, Any] ) -> Any: pass def __UpperCAmelCase ( self : Dict ) -> str: # Initialize image_processing lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image ) # Test not batched input lowerCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ , batched=UpperCAmelCase__ ) lowerCAmelCase = image_processing(UpperCAmelCase__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self : int ) -> Tuple: # Initialize image_processing lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray ) # Test not batched input lowerCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase = image_processing(UpperCAmelCase__ , return_tensors='pt' ).pixel_values lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ , batched=UpperCAmelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self : List[Any] ) -> Any: # Initialize image_processing lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , torch.Tensor ) # Test not batched input lowerCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCAmelCase = image_processing(UpperCAmelCase__ , return_tensors='pt' ).pixel_values lowerCAmelCase , lowerCAmelCase = self.image_processor_tester.get_expected_values(UpperCAmelCase__ , batched=UpperCAmelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __UpperCAmelCase ( self : Optional[Any] ) -> Any: # prepare image and target lowerCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: lowerCAmelCase = json.loads(f.read() ) lowerCAmelCase = {'image_id': 3_9_7_6_9, 'annotations': target} # encode them lowerCAmelCase = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' ) lowerCAmelCase = image_processing(images=UpperCAmelCase__ , annotations=UpperCAmelCase__ , return_tensors='pt' ) # verify pixel values lowerCAmelCase = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['pixel_values'].shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , UpperCAmelCase__ , atol=1E-4 ) ) # verify area lowerCAmelCase = torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , UpperCAmelCase__ ) ) # verify boxes lowerCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , UpperCAmelCase__ , atol=1E-3 ) ) # verify image_id lowerCAmelCase = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , UpperCAmelCase__ ) ) # verify is_crowd lowerCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , UpperCAmelCase__ ) ) # verify class_labels lowerCAmelCase = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , UpperCAmelCase__ ) ) # verify orig_size lowerCAmelCase = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , UpperCAmelCase__ ) ) # verify size lowerCAmelCase = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , UpperCAmelCase__ ) ) @slow def __UpperCAmelCase ( self : str ) -> str: # prepare image, target and masks_path lowerCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: lowerCAmelCase = json.loads(f.read() ) lowerCAmelCase = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target} lowerCAmelCase = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them lowerCAmelCase = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' ) lowerCAmelCase = image_processing(images=UpperCAmelCase__ , annotations=UpperCAmelCase__ , masks_path=UpperCAmelCase__ , return_tensors='pt' ) # verify pixel values lowerCAmelCase = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['pixel_values'].shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , UpperCAmelCase__ , atol=1E-4 ) ) # verify area lowerCAmelCase = torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , UpperCAmelCase__ ) ) # verify boxes lowerCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , UpperCAmelCase__ , atol=1E-3 ) ) # verify image_id lowerCAmelCase = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , UpperCAmelCase__ ) ) # verify is_crowd lowerCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , UpperCAmelCase__ ) ) # verify class_labels lowerCAmelCase = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , UpperCAmelCase__ ) ) # verify masks lowerCAmelCase = 8_2_2_8_7_3 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , UpperCAmelCase__ ) # verify orig_size lowerCAmelCase = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , UpperCAmelCase__ ) ) # verify size lowerCAmelCase = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , UpperCAmelCase__ ) )
4
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
0
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys UpperCAmelCase__ = subprocess.check_output('''git merge-base main HEAD'''.split()).decode('''utf-8''') UpperCAmelCase__ = subprocess.check_output(f'''git diff --name-only {fork_point_sha}'''.split()).decode('''utf-8''').split() UpperCAmelCase__ = '''|'''.join(sys.argv[1:]) UpperCAmelCase__ = re.compile(Rf'''^({joined_dirs}).*?\.py$''') UpperCAmelCase__ = [x for x in modified_files if regex.match(x)] print(''' '''.join(relevant_modified_files), end='''''')
5
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
0
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def __lowerCAmelCase ( ) -> Optional[Any]: __a = ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=a__ , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=a__ , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=a__ ) return parser.parse_args() def __lowerCAmelCase ( ) -> Optional[Any]: __a = parse_args() # Import training_script as a module. __a = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) __a = script_fpath.stem __a = importlib.import_module(a__ ) # Patch sys.argv __a = [args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
6
"""simple docstring""" import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Any: 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 SCREAMING_SNAKE_CASE ( self ) -> str: self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_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]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =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 ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
0
lowercase_ = "Alexander Joslin" import operator as op from .stack import Stack def _snake_case( SCREAMING_SNAKE_CASE__ : str ) -> int: '''simple docstring''' A__ = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} A__ = Stack() A__ = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(SCREAMING_SNAKE_CASE__ ) ) elif i in operators: # RULE 2 operator_stack.push(SCREAMING_SNAKE_CASE__ ) elif i == ")": # RULE 4 A__ = operator_stack.peek() operator_stack.pop() A__ = operand_stack.peek() operand_stack.pop() A__ = operand_stack.peek() operand_stack.pop() A__ = operators[opr](SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) operand_stack.push(SCREAMING_SNAKE_CASE__ ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": lowercase_ = "(5 + ((4 * 2) * (2 + 3)))" # answer = 45 print(f"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
7
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = {'''vocab_file''': '''sentencepiece.bpe.model'''} lowerCAmelCase_ = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', } } lowerCAmelCase_ = { '''camembert-base''': 5_12, } lowerCAmelCase_ = '''▁''' class snake_case_ ( __A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE : str = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE : str = ["input_ids", "attention_mask"] def __init__( self : Optional[Any] , _UpperCamelCase : Tuple , _UpperCamelCase : Dict="<s>" , _UpperCamelCase : str="</s>" , _UpperCamelCase : Dict="</s>" , _UpperCamelCase : List[Any]="<s>" , _UpperCamelCase : Optional[Any]="<unk>" , _UpperCamelCase : List[str]="<pad>" , _UpperCamelCase : Dict="<mask>" , _UpperCamelCase : List[str]=["<s>NOTUSED", "</s>NOTUSED"] , _UpperCamelCase : Optional[Dict[str, Any]] = None , **_UpperCamelCase : Dict , ) ->None: # Mask token behave like a normal word, i.e. include the space before it snake_case_ = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else mask_token snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_UpperCamelCase , eos_token=_UpperCamelCase , unk_token=_UpperCamelCase , sep_token=_UpperCamelCase , cls_token=_UpperCamelCase , pad_token=_UpperCamelCase , mask_token=_UpperCamelCase , additional_special_tokens=_UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_UpperCamelCase , ) snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_UpperCamelCase ) ) snake_case_ = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> snake_case_ = {'''<s>NOTUSED''': 0, '''<pad>''': 1, '''</s>NOTUSED''': 2, '''<unk>''': 3} snake_case_ = len(self.fairseq_tokens_to_ids ) snake_case_ = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) snake_case_ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def snake_case__( self : Dict , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None ) ->List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case_ = [self.cls_token_id] snake_case_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def snake_case__( self : str , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None , _UpperCamelCase : bool = False ) ->List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCamelCase , token_ids_a=_UpperCamelCase , already_has_special_tokens=_UpperCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCamelCase )) + [1] return [1] + ([0] * len(_UpperCamelCase )) + [1, 1] + ([0] * len(_UpperCamelCase )) + [1] def snake_case__( self : Any , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None ) ->List[int]: snake_case_ = [self.sep_token_id] 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] @property def snake_case__( self : Any ) ->Union[str, Any]: return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def snake_case__( self : Any ) ->List[Any]: snake_case_ = {self.convert_ids_to_tokens(_UpperCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def snake_case__( self : Tuple , _UpperCamelCase : str ) ->List[str]: return self.sp_model.encode(_UpperCamelCase , out_type=_UpperCamelCase ) def snake_case__( self : List[str] , _UpperCamelCase : int ) ->Union[str, Any]: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(_UpperCamelCase ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(_UpperCamelCase ) def snake_case__( self : List[Any] , _UpperCamelCase : Tuple ) ->Any: 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 : Any , _UpperCamelCase : str ) ->Any: snake_case_ = [] snake_case_ = '''''' snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_UpperCamelCase ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(_UpperCamelCase ) snake_case_ = False out_string += self.sp_model.decode(_UpperCamelCase ) return out_string.strip() def __getstate__( self : List[Any] ) ->str: snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : int , _UpperCamelCase : str ) ->str: snake_case_ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def snake_case__( self : Dict , _UpperCamelCase : str , _UpperCamelCase : Optional[str] = None ) ->Tuple[str]: if not os.path.isdir(_UpperCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return snake_case_ = os.path.join( _UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _UpperCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCamelCase , '''wb''' ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(_UpperCamelCase ) return (out_vocab_file,)
8
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" while second != 0: a =first & second first ^= second a =c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Dict = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : List[Any] = int(input("""Enter the second number: """).strip()) print(F'{add(first, second) = }')
81
0
__lowerCAmelCase : Optional[int] ='\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' __lowerCAmelCase : Tuple =[{'type': 'code', 'content': INSTALL_CONTENT}] __lowerCAmelCase : int ={ '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
9
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
0
import argparse import math import os import torch from neural_compressor.utils.pytorch import load from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Optional[Any] =argparse.ArgumentParser() parser.add_argument( "-m" , "--pretrained_model_name_or_path" , type=__a , default=__a , required=__a , help="Path to pretrained model or model identifier from huggingface.co/models." , ) parser.add_argument( "-c" , "--caption" , type=__a , default="robotic cat with wings" , help="Text used to generate images." , ) parser.add_argument( "-n" , "--images_num" , type=__a , default=4 , help="How much images to generate." , ) parser.add_argument( "-s" , "--seed" , type=__a , default=42 , help="Seed for random process." , ) parser.add_argument( "-ci" , "--cuda_id" , type=__a , default=0 , help="cuda_id." , ) lowerCamelCase__: Union[str, Any] =parser.parse_args() return args def lowerCAmelCase_ ( __a , __a , __a ) -> Tuple: """simple docstring""" if not len(__a ) == rows * cols: raise ValueError("The specified number of rows and columns are not correct." ) lowerCamelCase__ , lowerCamelCase__: Optional[int] =imgs[0].size lowerCamelCase__: Tuple =Image.new("RGB" , size=(cols * w, rows * h) ) lowerCamelCase__ , lowerCamelCase__: Tuple =grid.size for i, img in enumerate(__a ): grid.paste(__a , box=(i % cols * w, i // cols * h) ) return grid def lowerCAmelCase_ ( __a , __a="robotic cat with wings" , __a=7.5 , __a=50 , __a=1 , __a=42 , ) -> str: """simple docstring""" lowerCamelCase__: List[str] =torch.Generator(pipeline.device ).manual_seed(__a ) lowerCamelCase__: List[Any] =pipeline( __a , guidance_scale=__a , num_inference_steps=__a , generator=__a , num_images_per_prompt=__a , ).images lowerCamelCase__: List[str] =int(math.sqrt(__a ) ) lowerCamelCase__: Dict =image_grid(__a , rows=_rows , cols=num_images_per_prompt // _rows ) return grid, images __A = parse_args() # Load models and create wrapper for stable diffusion __A = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer") __A = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder") __A = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae") __A = UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet") __A = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer ) __A = lambda images, clip_input: (images, False) if os.path.exists(os.path.join(args.pretrained_model_name_or_path, "best_model.pt")): __A = load(args.pretrained_model_name_or_path, model=unet) unet.eval() setattr(pipeline, "unet", unet) else: __A = unet.to(torch.device("cuda", args.cuda_id)) __A = pipeline.to(unet.device) __A , __A = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed) grid.save(os.path.join(args.pretrained_model_name_or_path, "{}.png".format("_".join(args.caption.split())))) __A = os.path.join(args.pretrained_model_name_or_path, "_".join(args.caption.split())) os.makedirs(dirname, exist_ok=True) for idx, image in enumerate(images): image.save(os.path.join(dirname, "{}.png".format(idx + 1)))
10
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCamelCase_ : str = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *__A , **__A ) -> None: warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , __A , ) super().__init__(*__A , **__A )
81
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowerCAmelCase__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['GPTSw3Tokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
11
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ = { '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: UpperCAmelCase_ = ['WhisperTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ 'WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST', 'WhisperForConditionalGeneration', 'WhisperModel', 'WhisperPreTrainedModel', 'WhisperForAudioClassification', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ 'TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFWhisperForConditionalGeneration', 'TFWhisperModel', 'TFWhisperPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ '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 UpperCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
12
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
0
import os import pytest from transformers.dynamic_module_utils import get_imports lowerCAmelCase : str = """ import os """ lowerCAmelCase : Optional[Any] = """ def foo(): import os return False """ lowerCAmelCase : str = """ def foo(): def bar(): if True: import os return False return bar() """ lowerCAmelCase : Any = """ import os try: import bar except ImportError: raise ValueError() """ lowerCAmelCase : int = """ import os def foo(): try: import bar except ImportError: raise ValueError() """ lowerCAmelCase : Tuple = """ import os try: import bar except (ImportError, AttributeError): raise ValueError() """ lowerCAmelCase : Optional[Any] = """ import os try: import bar except ImportError as e: raise ValueError() """ lowerCAmelCase : List[str] = """ import os try: import bar except: raise ValueError() """ lowerCAmelCase : List[Any] = """ import os try: import bar import baz except ImportError: raise ValueError() """ lowerCAmelCase : Optional[Any] = """ import os try: import bar import baz except ImportError: x = 1 raise ValueError() """ lowerCAmelCase : Any = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize("case" , _UpperCAmelCase ) def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = os.path.join(_UpperCAmelCase , "test_file.py" ) with open(_UpperCAmelCase , "w" ) as _tmp_file: _tmp_file.write(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Any = get_imports(_UpperCAmelCase ) assert parsed_imports == ["os"]
13
"""simple docstring""" lowerCamelCase_ : Any = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
81
0
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 ( ConditionalDetrConfig, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase : str = logging.get_logger(__name__) # here we list all keys to be renamed (original name on the left, our name on the right) _lowerCamelCase : List[str] = [] for i in range(6): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F'''transformer.encoder.layers.{i}.self_attn.out_proj.weight''', F'''encoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append( (F'''transformer.encoder.layers.{i}.self_attn.out_proj.bias''', F'''encoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''encoder.layers.{i}.fc1.weight''')) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''encoder.layers.{i}.fc1.bias''')) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''encoder.layers.{i}.fc2.weight''')) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''encoder.layers.{i}.fc2.bias''')) rename_keys.append( (F'''transformer.encoder.layers.{i}.norm1.weight''', F'''encoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''encoder.layers.{i}.self_attn_layer_norm.bias''')) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''encoder.layers.{i}.final_layer_norm.weight''')) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''encoder.layers.{i}.final_layer_norm.bias''')) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( (F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''decoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''decoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append( ( F'''transformer.decoder.layers.{i}.cross_attn.out_proj.weight''', F'''decoder.layers.{i}.encoder_attn.out_proj.weight''', ) ) rename_keys.append( ( F'''transformer.decoder.layers.{i}.cross_attn.out_proj.bias''', F'''decoder.layers.{i}.encoder_attn.out_proj.bias''', ) ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''decoder.layers.{i}.fc1.weight''')) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''decoder.layers.{i}.fc1.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''decoder.layers.{i}.fc2.weight''')) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''decoder.layers.{i}.fc2.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm1.weight''', F'''decoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''decoder.layers.{i}.self_attn_layer_norm.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm2.weight''', F'''decoder.layers.{i}.encoder_attn_layer_norm.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm2.bias''', F'''decoder.layers.{i}.encoder_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''decoder.layers.{i}.final_layer_norm.weight''')) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''decoder.layers.{i}.final_layer_norm.bias''')) # q, k, v projections in self/cross-attention in decoder for conditional DETR rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_qcontent_proj.weight''', F'''decoder.layers.{i}.sa_qcontent_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_kcontent_proj.weight''', F'''decoder.layers.{i}.sa_kcontent_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_qpos_proj.weight''', F'''decoder.layers.{i}.sa_qpos_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_kpos_proj.weight''', F'''decoder.layers.{i}.sa_kpos_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_v_proj.weight''', F'''decoder.layers.{i}.sa_v_proj.weight''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qcontent_proj.weight''', F'''decoder.layers.{i}.ca_qcontent_proj.weight''') ) # rename_keys.append((f"transformer.decoder.layers.{i}.ca_qpos_proj.weight", f"decoder.layers.{i}.ca_qpos_proj.weight")) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_kcontent_proj.weight''', F'''decoder.layers.{i}.ca_kcontent_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_kpos_proj.weight''', F'''decoder.layers.{i}.ca_kpos_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.ca_v_proj.weight''', F'''decoder.layers.{i}.ca_v_proj.weight''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qpos_sine_proj.weight''', F'''decoder.layers.{i}.ca_qpos_sine_proj.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_qcontent_proj.bias''', F'''decoder.layers.{i}.sa_qcontent_proj.bias''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.sa_kcontent_proj.bias''', F'''decoder.layers.{i}.sa_kcontent_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_qpos_proj.bias''', F'''decoder.layers.{i}.sa_qpos_proj.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_kpos_proj.bias''', F'''decoder.layers.{i}.sa_kpos_proj.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.sa_v_proj.bias''', F'''decoder.layers.{i}.sa_v_proj.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qcontent_proj.bias''', F'''decoder.layers.{i}.ca_qcontent_proj.bias''') ) # rename_keys.append((f"transformer.decoder.layers.{i}.ca_qpos_proj.bias", f"decoder.layers.{i}.ca_qpos_proj.bias")) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_kcontent_proj.bias''', F'''decoder.layers.{i}.ca_kcontent_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.ca_kpos_proj.bias''', F'''decoder.layers.{i}.ca_kpos_proj.bias''')) rename_keys.append((F'''transformer.decoder.layers.{i}.ca_v_proj.bias''', F'''decoder.layers.{i}.ca_v_proj.bias''')) rename_keys.append( (F'''transformer.decoder.layers.{i}.ca_qpos_sine_proj.bias''', F'''decoder.layers.{i}.ca_qpos_sine_proj.bias''') ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads # for conditional DETR, also convert reference point head and query scale MLP rename_keys.extend( [ ("""input_proj.weight""", """input_projection.weight"""), ("""input_proj.bias""", """input_projection.bias"""), ("""query_embed.weight""", """query_position_embeddings.weight"""), ("""transformer.decoder.norm.weight""", """decoder.layernorm.weight"""), ("""transformer.decoder.norm.bias""", """decoder.layernorm.bias"""), ("""class_embed.weight""", """class_labels_classifier.weight"""), ("""class_embed.bias""", """class_labels_classifier.bias"""), ("""bbox_embed.layers.0.weight""", """bbox_predictor.layers.0.weight"""), ("""bbox_embed.layers.0.bias""", """bbox_predictor.layers.0.bias"""), ("""bbox_embed.layers.1.weight""", """bbox_predictor.layers.1.weight"""), ("""bbox_embed.layers.1.bias""", """bbox_predictor.layers.1.bias"""), ("""bbox_embed.layers.2.weight""", """bbox_predictor.layers.2.weight"""), ("""bbox_embed.layers.2.bias""", """bbox_predictor.layers.2.bias"""), ("""transformer.decoder.ref_point_head.layers.0.weight""", """decoder.ref_point_head.layers.0.weight"""), ("""transformer.decoder.ref_point_head.layers.0.bias""", """decoder.ref_point_head.layers.0.bias"""), ("""transformer.decoder.ref_point_head.layers.1.weight""", """decoder.ref_point_head.layers.1.weight"""), ("""transformer.decoder.ref_point_head.layers.1.bias""", """decoder.ref_point_head.layers.1.bias"""), ("""transformer.decoder.query_scale.layers.0.weight""", """decoder.query_scale.layers.0.weight"""), ("""transformer.decoder.query_scale.layers.0.bias""", """decoder.query_scale.layers.0.bias"""), ("""transformer.decoder.query_scale.layers.1.weight""", """decoder.query_scale.layers.1.weight"""), ("""transformer.decoder.query_scale.layers.1.bias""", """decoder.query_scale.layers.1.bias"""), ("""transformer.decoder.layers.0.ca_qpos_proj.weight""", """decoder.layers.0.ca_qpos_proj.weight"""), ("""transformer.decoder.layers.0.ca_qpos_proj.bias""", """decoder.layers.0.ca_qpos_proj.bias"""), ] ) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Optional[Any]: """simple docstring""" A__ = state_dict.pop(lowercase_ ) A__ = val def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[str]: """simple docstring""" A__ = OrderedDict() for key, value in state_dict.items(): if "backbone.0.body" in key: A__ = key.replace('''backbone.0.body''' , '''backbone.conv_encoder.model''' ) A__ = value else: A__ = value return new_state_dict def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=False ) -> Dict: """simple docstring""" A__ = '''''' if is_panoptic: A__ = '''conditional_detr.''' # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) A__ = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight""" ) A__ = state_dict.pop(f"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict A__ = in_proj_weight[:256, :] A__ = in_proj_bias[:256] A__ = in_proj_weight[256:512, :] A__ = in_proj_bias[256:512] A__ = in_proj_weight[-256:, :] A__ = in_proj_bias[-256:] def SCREAMING_SNAKE_CASE ( ) -> List[Any]: """simple docstring""" A__ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A__ = Image.open(requests.get(lowercase_ , stream=lowercase_ ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Tuple: """simple docstring""" A__ = ConditionalDetrConfig() # set backbone and dilation attributes if "resnet101" in model_name: A__ = '''resnet101''' if "dc5" in model_name: A__ = True A__ = '''panoptic''' in model_name if is_panoptic: A__ = 250 else: A__ = 91 A__ = '''huggingface/label-files''' A__ = '''coco-detection-id2label.json''' A__ = json.load(open(hf_hub_download(lowercase_ , lowercase_ , repo_type='''dataset''' ) , '''r''' ) ) A__ = {int(lowercase_ ): v for k, v in idalabel.items()} A__ = idalabel A__ = {v: k for k, v in idalabel.items()} # load image processor A__ = '''coco_panoptic''' if is_panoptic else '''coco_detection''' A__ = ConditionalDetrImageProcessor(format=lowercase_ ) # prepare image A__ = prepare_img() A__ = image_processor(images=lowercase_ , return_tensors='''pt''' ) A__ = encoding['''pixel_values'''] logger.info(f"""Converting model {model_name}...""" ) # load original model from torch hub A__ = torch.hub.load('''DeppMeng/ConditionalDETR''' , lowercase_ , pretrained=lowercase_ ).eval() A__ = conditional_detr.state_dict() # rename keys for src, dest in rename_keys: if is_panoptic: A__ = '''conditional_detr.''' + src rename_key(lowercase_ , lowercase_ , lowercase_ ) A__ = rename_backbone_keys(lowercase_ ) # query, key and value matrices need special treatment read_in_q_k_v(lowercase_ , is_panoptic=lowercase_ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them A__ = '''conditional_detr.model.''' if is_panoptic else '''model.''' for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith('''conditional_detr''' ) and not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ) ): A__ = state_dict.pop(lowercase_ ) A__ = val elif "class_labels_classifier" in key or "bbox_predictor" in key: A__ = state_dict.pop(lowercase_ ) A__ = val elif key.startswith('''bbox_attention''' ) or key.startswith('''mask_head''' ): continue else: A__ = state_dict.pop(lowercase_ ) A__ = val else: if not key.startswith('''class_labels_classifier''' ) and not key.startswith('''bbox_predictor''' ): A__ = state_dict.pop(lowercase_ ) A__ = val # finally, create HuggingFace model and load state dict A__ = ConditionalDetrForSegmentation(lowercase_ ) if is_panoptic else ConditionalDetrForObjectDetection(lowercase_ ) model.load_state_dict(lowercase_ ) model.eval() model.push_to_hub(repo_id=lowercase_ , organization='''DepuMeng''' , commit_message='''Add model''' ) # verify our conversion A__ = conditional_detr(lowercase_ ) A__ = model(lowercase_ ) assert torch.allclose(outputs.logits , original_outputs['''pred_logits'''] , atol=1E-4 ) assert torch.allclose(outputs.pred_boxes , original_outputs['''pred_boxes'''] , atol=1E-4 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs['''pred_masks'''] , atol=1E-4 ) # Save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) model.save_pretrained(lowercase_ ) image_processor.save_pretrained(lowercase_ ) if __name__ == "__main__": _lowerCamelCase : Dict = argparse.ArgumentParser() parser.add_argument( """--model_name""", default="""conditional_detr_resnet50""", type=str, help="""Name of the CONDITIONAL_DETR model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the folder to output PyTorch model.""" ) _lowerCamelCase : Optional[Any] = parser.parse_args() convert_conditional_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path)
14
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ lowerCamelCase_ : Optional[Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ lowerCamelCase_ : Optional[int] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Optional[Any]: if return_pvalue: a =pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
81
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_tokenizers @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self : Dict ): __A = XLMRobertaModel.from_pretrained("xlm-roberta-base" ) __A = torch.tensor([[0, 5_81, 1_02_69, 83, 9_99_42, 1_36, 6_07_42, 23, 70, 8_05_83, 1_82_76, 2]] ) # The dog is cute and lives in the garden house __A = torch.Size((1, 12, 7_68) ) # batch_size, sequence_length, embedding_vector_dim __A = torch.tensor( [[-0.01_01, 0.12_18, -0.08_03, 0.08_01, 0.13_27, 0.07_76, -0.12_15, 0.23_83, 0.33_38, 0.31_06, 0.03_00, 0.02_52]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): __A = model(A )["last_hidden_state"].detach() self.assertEqual(output.shape ,A ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] ,A ,atol=1E-3 ) ) @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = XLMRobertaModel.from_pretrained("xlm-roberta-large" ) __A = torch.tensor([[0, 5_81, 1_02_69, 83, 9_99_42, 1_36, 6_07_42, 23, 70, 8_05_83, 1_82_76, 2]] ) # The dog is cute and lives in the garden house __A = torch.Size((1, 12, 10_24) ) # batch_size, sequence_length, embedding_vector_dim __A = torch.tensor( [[-0.06_99, -0.03_18, 0.07_05, -0.12_41, 0.09_99, -0.05_20, 0.10_04, -0.18_38, -0.47_04, 0.14_37, 0.08_21, 0.01_26]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): __A = model(A )["last_hidden_state"].detach() self.assertEqual(output.shape ,A ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] ,A ,atol=1E-3 ) )
15
"""simple docstring""" lowerCamelCase_ : int = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Union[str, Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase_ = logging.get_logger(__name__) class __A ( A_ ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = ["pixel_values"] def __init__( self : Optional[int] ,_snake_case : bool = True ,_snake_case : Dict[str, int] = None ,_snake_case : int = 0.9 ,_snake_case : PILImageResampling = PILImageResampling.BICUBIC ,_snake_case : bool = True ,_snake_case : Dict[str, int] = None ,_snake_case : Union[int, float] = 1 / 255 ,_snake_case : bool = True ,_snake_case : bool = True ,_snake_case : Optional[Union[float, List[float]]] = None ,_snake_case : Optional[Union[float, List[float]]] = None ,**_snake_case : int ,) -> None: """simple docstring""" super().__init__(**_snake_case ) lowercase__ : List[Any] = size if size is not None else {'''shortest_edge''': 224} lowercase__ : Optional[Any] = get_size_dict(_snake_case ,default_to_square=_snake_case ) lowercase__ : Dict = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} lowercase__ : Dict = get_size_dict(_snake_case ,param_name='''crop_size''' ) lowercase__ : int = do_resize lowercase__ : Optional[Any] = size lowercase__ : Tuple = crop_pct lowercase__ : int = resample lowercase__ : Dict = do_center_crop lowercase__ : int = crop_size lowercase__ : List[Any] = do_rescale lowercase__ : int = rescale_factor lowercase__ : List[Any] = do_normalize lowercase__ : str = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowercase__ : str = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCAmelCase ( self : Optional[Any] ,_snake_case : np.ndarray ,_snake_case : Dict[str, int] ,_snake_case : Optional[float] = None ,_snake_case : PILImageResampling = PILImageResampling.BICUBIC ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : Optional[Any] ,) -> np.ndarray: """simple docstring""" lowercase__ : Optional[int] = get_size_dict(_snake_case ,default_to_square=_snake_case ) if "shortest_edge" not in size and ("height" not in size or "width" not in size): raise ValueError(f"""size must contain 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) if crop_pct is not None: if "shortest_edge" in size: lowercase__ : Dict = int(size['''shortest_edge'''] / crop_pct ) elif "height" in size and "width" in size: if size["height"] == size["width"]: lowercase__ : Tuple = int(size['''height'''] / crop_pct ) else: lowercase__ : List[str] = (int(size['''height'''] / crop_pct ), int(size['''width'''] / crop_pct )) else: raise ValueError('''Invalid size for resize: {}'''.format(_snake_case ) ) lowercase__ : List[Any] = get_resize_output_image_size(_snake_case ,size=_snake_case ,default_to_square=_snake_case ) else: if "shortest_edge" in size: lowercase__ : Tuple = get_resize_output_image_size(_snake_case ,size=size['''shortest_edge'''] ,default_to_square=_snake_case ) elif "height" in size and "width" in size: lowercase__ : Optional[Any] = (size['''height'''], size['''width''']) else: raise ValueError('''Invalid size for resize: {}'''.format(_snake_case ) ) return resize(_snake_case ,size=_snake_case ,resample=_snake_case ,data_format=_snake_case ,**_snake_case ) def UpperCAmelCase ( self : Optional[Any] ,_snake_case : np.ndarray ,_snake_case : Dict[str, int] ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : List[Any] ,) -> np.ndarray: """simple docstring""" lowercase__ : Union[str, Any] = get_size_dict(_snake_case ) if "height" not in size or "width" not in size: raise ValueError(f"""size must contain 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(_snake_case ,size=(size['''height'''], size['''width''']) ,data_format=_snake_case ,**_snake_case ) def UpperCAmelCase ( self : int ,_snake_case : np.ndarray ,_snake_case : Union[int, float] ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : str ,) -> Union[str, Any]: """simple docstring""" return rescale(_snake_case ,scale=_snake_case ,data_format=_snake_case ,**_snake_case ) def UpperCAmelCase ( self : Optional[Any] ,_snake_case : np.ndarray ,_snake_case : Union[float, List[float]] ,_snake_case : Union[float, List[float]] ,_snake_case : Optional[Union[str, ChannelDimension]] = None ,**_snake_case : Optional[Any] ,) -> np.ndarray: """simple docstring""" return normalize(_snake_case ,mean=_snake_case ,std=_snake_case ,data_format=_snake_case ,**_snake_case ) def UpperCAmelCase ( self : Union[str, Any] ,_snake_case : ImageInput ,_snake_case : bool = None ,_snake_case : Dict[str, int] = None ,_snake_case : int = None ,_snake_case : PILImageResampling = None ,_snake_case : bool = None ,_snake_case : Dict[str, int] = None ,_snake_case : bool = None ,_snake_case : float = None ,_snake_case : bool = None ,_snake_case : Optional[Union[float, List[float]]] = None ,_snake_case : Optional[Union[float, List[float]]] = None ,_snake_case : Optional[Union[str, TensorType]] = None ,_snake_case : ChannelDimension = ChannelDimension.FIRST ,**_snake_case : List[Any] ,) -> PIL.Image.Image: """simple docstring""" lowercase__ : List[Any] = do_resize if do_resize is not None else self.do_resize lowercase__ : int = crop_pct if crop_pct is not None else self.crop_pct lowercase__ : List[Any] = resample if resample is not None else self.resample lowercase__ : int = do_center_crop if do_center_crop is not None else self.do_center_crop lowercase__ : str = do_rescale if do_rescale is not None else self.do_rescale lowercase__ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase__ : Dict = do_normalize if do_normalize is not None else self.do_normalize lowercase__ : Union[str, Any] = image_mean if image_mean is not None else self.image_mean lowercase__ : List[str] = image_std if image_std is not None else self.image_std lowercase__ : Optional[Any] = size if size is not None else self.size lowercase__ : Optional[Any] = get_size_dict(_snake_case ,default_to_square=_snake_case ) lowercase__ : Dict = crop_size if crop_size is not None else self.crop_size lowercase__ : List[Any] = get_size_dict(_snake_case ,param_name='''crop_size''' ) lowercase__ : Dict = make_list_of_images(_snake_case ) if not valid_images(_snake_case ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_pct is None: raise ValueError('''Crop_pct must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. lowercase__ : int = [to_numpy_array(_snake_case ) for image in images] if do_resize: lowercase__ : Optional[Any] = [self.resize(image=_snake_case ,size=_snake_case ,crop_pct=_snake_case ,resample=_snake_case ) for image in images] if do_center_crop: lowercase__ : List[Any] = [self.center_crop(image=_snake_case ,size=_snake_case ) for image in images] if do_rescale: lowercase__ : List[Any] = [self.rescale(image=_snake_case ,scale=_snake_case ) for image in images] if do_normalize: lowercase__ : Union[str, Any] = [self.normalize(image=_snake_case ,mean=_snake_case ,std=_snake_case ) for image in images] lowercase__ : List[Any] = [to_channel_dimension_format(_snake_case ,_snake_case ) for image in images] lowercase__ : Optional[int] = {'''pixel_values''': images} return BatchFeature(data=_snake_case ,tensor_type=_snake_case )
16
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
0
"""simple docstring""" import cmath import math def _A ( UpperCamelCase_ : float, UpperCamelCase_ : float, UpperCamelCase_ : float, UpperCamelCase_ : float) -> complex: '''simple docstring''' __lowercase = math.radians(UpperCamelCase_) __lowercase = math.radians(UpperCamelCase_) # Convert voltage and current to rectangular form __lowercase = cmath.rect(UpperCamelCase_, UpperCamelCase_) __lowercase = cmath.rect(UpperCamelCase_, UpperCamelCase_) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
17
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer __lowerCamelCase : Optional[Any] = logging.get_logger(__name__) __lowerCamelCase : Dict = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} __lowerCamelCase : int = { '''vocab_file''': { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt''' ), } } __lowerCamelCase : Any = { '''junnyu/roformer_chinese_small''': 15_36, '''junnyu/roformer_chinese_base''': 15_36, '''junnyu/roformer_chinese_char_small''': 5_12, '''junnyu/roformer_chinese_char_base''': 5_12, '''junnyu/roformer_small_discriminator''': 1_28, '''junnyu/roformer_small_generator''': 1_28, } __lowerCamelCase : Union[str, Any] = { '''junnyu/roformer_chinese_small''': {'''do_lower_case''': True}, '''junnyu/roformer_chinese_base''': {'''do_lower_case''': True}, '''junnyu/roformer_chinese_char_small''': {'''do_lower_case''': True}, '''junnyu/roformer_chinese_char_base''': {'''do_lower_case''': True}, '''junnyu/roformer_small_discriminator''': {'''do_lower_case''': True}, '''junnyu/roformer_small_generator''': {'''do_lower_case''': True}, } class a__ ( A__ ): A = VOCAB_FILES_NAMES A = PRETRAINED_VOCAB_FILES_MAP A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A = PRETRAINED_INIT_CONFIGURATION A = RoFormerTokenizer def __init__( self : List[str],_A : int=None,_A : int=None,_A : int=True,_A : List[Any]="[UNK]",_A : Tuple="[SEP]",_A : List[Any]="[PAD]",_A : Optional[int]="[CLS]",_A : Optional[Any]="[MASK]",_A : Optional[int]=True,_A : List[str]=None,**_A : List[Any],): """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_ : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase",_A ) != do_lower_case or pre_tok_state.get("strip_accents",_A ) != strip_accents ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = getattr(_A,pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE_ : Any = do_lower_case SCREAMING_SNAKE_CASE_ : List[str] = strip_accents SCREAMING_SNAKE_CASE_ : str = pre_tok_class(**_A ) SCREAMING_SNAKE_CASE_ : List[str] = do_lower_case def __getstate__( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = self.__dict__.copy() SCREAMING_SNAKE_CASE_ : Optional[Any] = BertPreTokenizer() return state def __setstate__( self : List[Any],_A : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = d SCREAMING_SNAKE_CASE_ : List[str] = self.__dict__["_tokenizer"].get_vocab() SCREAMING_SNAKE_CASE_ : Any = PreTokenizer.custom(JiebaPreTokenizer(_A ) ) def __UpperCamelCase ( self : Union[str, Any],_A : List[Any],_A : str=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __UpperCamelCase ( self : str,_A : List[int],_A : Optional[List[int]] = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE_ : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCamelCase ( self : int,_A : str,_A : Optional[str] = None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self._tokenizer.model.save(_A,name=_A ) return tuple(_A ) def __UpperCamelCase ( self : int,_A : Optional[int],_A : List[Any]=None,_A : Tuple=None,_A : str=False,**_A : List[Any],): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = BertPreTokenizer() return super().save_pretrained(_A,_A,_A,_A,**_A )
18
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy lowerCamelCase_ : Dict = logging.getLogger(__name__) lowerCamelCase_ : Tuple = """pytorch_model.bin""" @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}, ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the training data."} ) __lowerCAmelCase = dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "A csv or a json file containing the validation data."} ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The name of the task to train on."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "The list of labels for the task."} ) @dataclasses.dataclass class __A : """simple docstring""" __lowerCAmelCase = dataclasses.field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ) __lowerCAmelCase = dataclasses.field( default="accuracy", metadata={"help": "The evaluation metric used for the task."} ) __lowerCAmelCase = dataclasses.field( default="no", metadata={ "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]" }, ) __lowerCAmelCase = dataclasses.field( default=10, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={ "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions." }, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}, ) __lowerCAmelCase = dataclasses.field( default=0.0, metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}, ) __lowerCAmelCase = dataclasses.field( default=100, metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}, ) __lowerCAmelCase = dataclasses.field( default=_SCREAMING_SNAKE_CASE, metadata={"help": "Random seed for initialization."}, ) def _A ( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ): """simple docstring""" a =datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a =dataset.filter(lambda lowercase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a =int(eval_result * len(lowercase ) ) print(lowercase ) a =dataset.sort('''probability''' , reverse=lowercase ) a =dataset.select(range(lowercase ) ) a =dataset.remove_columns(['''label''', '''probability'''] ) a =dataset.rename_column('''prediction''' , '''label''' ) a =dataset.map(lambda lowercase : {"label": idalabel[example["label"]]} ) a =dataset.shuffle(seed=args.seed ) a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase , index=lowercase ) else: dataset.to_json(lowercase ) def _A ( lowercase , lowercase , lowercase , lowercase , **lowercase ): """simple docstring""" a =Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() a =STModelArguments(model_name_or_path=lowercase ) a =STDataArguments(train_file=lowercase , infer_file=lowercase ) a =STTrainingArguments(output_dir=lowercase ) a =argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase ).items(): setattr(lowercase , lowercase , lowercase ) for key, value in kwargs.items(): if hasattr(lowercase , lowercase ): setattr(lowercase , lowercase , lowercase ) # Sanity checks a ={} a =None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None a =args.train_file a =args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a =args.eval_file for key in data_files: a =data_files[key].split('''.''' )[-1] assert extension in ["csv", "json"], f'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: a =extension else: assert extension == args.data_file_extension, f'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), f'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info('''Creating the initial data directory for self-training...''' ) a =f'''{args.output_dir}/self-train_iter-{{}}'''.format a =data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase ) os.makedirs(lowercase , exist_ok=lowercase ) accelerator.wait_for_everyone() a =None a =None a =0 a =False # Show the progress bar a =tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): a =data_dir_format(lowercase ) assert os.path.exists(lowercase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a =os.path.join(lowercase , '''stage-1''' ) a ={ '''accelerator''': accelerator, '''model_name_or_path''': args.model_name_or_path, '''cache_dir''': args.cache_dir, '''do_train''': True, '''train_file''': data_files['''train'''] if iteration == 0 else data_files['''train_pseudo'''], '''do_eval''': True if args.eval_file is not None else False, '''eval_file''': data_files['''eval'''], '''do_predict''': True, '''infer_file''': data_files['''infer'''], '''task_name''': args.task_name, '''label_list''': args.label_list, '''output_dir''': current_output_dir, '''eval_metric''': args.eval_metric, '''evaluation_strategy''': args.evaluation_strategy, '''early_stopping_patience''': args.early_stopping_patience, '''early_stopping_threshold''': args.early_stopping_threshold, '''seed''': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(lowercase , lowercase ): arguments_dict.update({key: value} ) a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 1 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 1.''' , lowercase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a =os.path.join(lowercase , '''best-checkpoint''' ) a =os.path.join(lowercase , '''stage-2''' ) # Update arguments_dict a =model_path a =data_files['''train'''] a =current_output_dir a =os.path.join(lowercase , '''best-checkpoint''' , lowercase ) if os.path.exists(lowercase ): logger.info( '''Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.''' , lowercase , lowercase , ) else: logger.info('''***** Running self-training: iteration: %d, stage: 2 *****''' , lowercase ) finetune(**lowercase ) accelerator.wait_for_everyone() assert os.path.exists(lowercase ) logger.info('''Self-training job completed: iteration: %d, stage: 2.''' , lowercase ) a =iteration a =data_dir_format(iteration + 1 ) a =AutoConfig.from_pretrained(os.path.join(lowercase , '''best-checkpoint''' ) ) a =config.idalabel a =os.path.join(lowercase , '''eval_results_best-checkpoint.json''' ) a =os.path.join(lowercase , '''test_results_best-checkpoint.json''' ) assert os.path.exists(lowercase ) with open(lowercase , '''r''' ) as f: a =float(json.load(lowercase )[args.eval_metric] ) a =os.path.join(lowercase , '''infer_output_best-checkpoint.csv''' ) assert os.path.exists(lowercase ) # Loading the dataset from local csv or json files. a =load_dataset(args.data_file_extension , data_files={'''data''': data_files['''infer''']} )['''data'''] a =load_dataset('''csv''' , data_files={'''data''': infer_output_file} )['''data'''] if accelerator.is_main_process: os.makedirs(lowercase , exist_ok=lowercase ) shutil.copy(lowercase , os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase ): shutil.copy(lowercase , os.path.join(lowercase , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) accelerator.wait_for_everyone() a =os.path.join(lowercase , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a =eval_result if best_iteration is None: a =new_iteration a =new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a =new_iteration a =new_eval_result a =0 else: if new_eval_result == best_eval_result: a =new_iteration a =new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a =True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info('''Best iteration: %d''' , lowercase ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , ) else: # Assume that the last iteration is the best logger.info('''Best iteration: %d''' , args.max_selftrain_iterations - 1 ) logger.info('''Best evaluation result: %s = %f''' , args.eval_metric , lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase , '''eval_results_best-iteration.json''' ) , )
81
0
import gc import unittest import numpy as np import torch from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _SCREAMING_SNAKE_CASE ( snake_case_ , unittest.TestCase ): lowerCAmelCase__ = DanceDiffusionPipeline lowerCAmelCase__ = UNCONDITIONAL_AUDIO_GENERATION_PARAMS lowerCAmelCase__ = PipelineTesterMixin.required_optional_params - { 'callback', 'latents', 'callback_steps', 'output_type', 'num_images_per_prompt', } lowerCAmelCase__ = UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS lowerCAmelCase__ = False lowerCAmelCase__ = False def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: torch.manual_seed(0 ) lowerCamelCase_ = UNetaDModel( block_out_channels=(32, 32, 64) , extra_in_channels=16 , sample_size=512 , sample_rate=16000 , in_channels=2 , out_channels=2 , flip_sin_to_cos=lowercase , use_timestep_embedding=lowercase , time_embedding_type="fourier" , mid_block_type="UNetMidBlock1D" , down_block_types=("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") , up_block_types=("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") , ) lowerCamelCase_ = IPNDMScheduler() lowerCamelCase_ = { "unet": unet, "scheduler": scheduler, } return components def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase=0 ) -> Tuple: if str(lowercase ).startswith("mps" ): lowerCamelCase_ = torch.manual_seed(lowercase ) else: lowerCamelCase_ = torch.Generator(device=lowercase ).manual_seed(lowercase ) lowerCamelCase_ = { "batch_size": 1, "generator": generator, "num_inference_steps": 4, } return inputs def SCREAMING_SNAKE_CASE_( self ) -> str: lowerCamelCase_ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = DanceDiffusionPipeline(**lowercase ) lowerCamelCase_ = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) lowerCamelCase_ = self.get_dummy_inputs(lowercase ) lowerCamelCase_ = pipe(**lowercase ) lowerCamelCase_ = output.audios lowerCamelCase_ = audio[0, -3:, -3:] assert audio.shape == (1, 2, components["unet"].sample_size) lowerCamelCase_ = np.array([-0.7_2_6_5, 1.0_0_0_0, -0.8_3_8_8, 0.1_1_7_5, 0.9_4_9_8, -1.0_0_0_0] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def SCREAMING_SNAKE_CASE_( self ) -> Dict: return super().test_save_load_local() @skip_mps def SCREAMING_SNAKE_CASE_( self ) -> int: return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) @skip_mps def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: return super().test_save_load_optional_components() @skip_mps def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: return super().test_attention_slicing_forward_pass() def SCREAMING_SNAKE_CASE_( self ) -> Optional[Any]: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_( self ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_( self ) -> Any: lowerCamelCase_ = torch_device lowerCamelCase_ = DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k" ) lowerCamelCase_ = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) lowerCamelCase_ = torch.manual_seed(0 ) lowerCamelCase_ = pipe(generator=lowercase , num_inference_steps=100 , audio_length_in_s=4.0_9_6 ) lowerCamelCase_ = output.audios lowerCamelCase_ = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) lowerCamelCase_ = np.array([-0.0_1_9_2, -0.0_2_3_1, -0.0_3_1_8, -0.0_0_5_9, 0.0_0_0_2, -0.0_0_2_0] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: lowerCamelCase_ = torch_device lowerCamelCase_ = DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k" , torch_dtype=torch.floataa ) lowerCamelCase_ = pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) lowerCamelCase_ = torch.manual_seed(0 ) lowerCamelCase_ = pipe(generator=lowercase , num_inference_steps=100 , audio_length_in_s=4.0_9_6 ) lowerCamelCase_ = output.audios lowerCamelCase_ = audio[0, -3:, -3:] assert audio.shape == (1, 2, pipe.unet.sample_size) lowerCamelCase_ = np.array([-0.0_3_6_7, -0.0_4_8_8, -0.0_7_7_1, -0.0_5_2_5, -0.0_4_4_4, -0.0_3_4_1] ) assert np.abs(audio_slice.flatten() - expected_slice ).max() < 1e-2
19
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
0
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class __snake_case ( unittest.TestCase ): def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[str] = tempfile.mkdtemp() lowercase : int = BlipImageProcessor() lowercase : List[str] = GPTaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-GPT2Model""" ) lowercase : Optional[int] = BlipaProcessor(snake_case ,snake_case ) processor.save_pretrained(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self ,**snake_case ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname ,**snake_case ).tokenizer def _SCREAMING_SNAKE_CASE ( self ,**snake_case ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname ,**snake_case ).image_processor def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = [np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )] lowercase : Dict = [Image.fromarray(np.moveaxis(snake_case ,0 ,-1 ) ) for x in image_inputs] return image_inputs def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = BlipaProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowercase : List[Any] = self.get_tokenizer(bos_token="""(BOS)""" ,eos_token="""(EOS)""" ) lowercase : Optional[Any] = self.get_image_processor(do_normalize=snake_case ,padding_value=1.0 ) lowercase : Dict = BlipaProcessor.from_pretrained( self.tmpdirname ,bos_token="""(BOS)""" ,eos_token="""(EOS)""" ,do_normalize=snake_case ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,snake_case ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[str] = self.get_image_processor() lowercase : Tuple = self.get_tokenizer() lowercase : int = BlipaProcessor(tokenizer=snake_case ,image_processor=snake_case ) lowercase : Union[str, Any] = self.prepare_image_inputs() lowercase : Optional[int] = image_processor(snake_case ,return_tensors="""np""" ) lowercase : Optional[int] = processor(images=snake_case ,return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1e-2 ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[int] = self.get_image_processor() lowercase : str = self.get_tokenizer() lowercase : Optional[int] = BlipaProcessor(tokenizer=snake_case ,image_processor=snake_case ) lowercase : Dict = """lower newer""" lowercase : Optional[int] = processor(text=snake_case ) lowercase : List[str] = tokenizer(snake_case ,return_token_type_ids=snake_case ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[str] = self.get_image_processor() lowercase : List[str] = self.get_tokenizer() lowercase : Union[str, Any] = BlipaProcessor(tokenizer=snake_case ,image_processor=snake_case ) lowercase : Optional[Any] = """lower newer""" lowercase : Optional[Any] = self.prepare_image_inputs() lowercase : List[Any] = processor(text=snake_case ,images=snake_case ) self.assertListEqual(list(inputs.keys() ) ,["""pixel_values""", """input_ids""", """attention_mask"""] ) # test if it raises when no input is passed with pytest.raises(snake_case ): processor() def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Union[str, Any] = self.get_image_processor() lowercase : str = self.get_tokenizer() lowercase : Optional[int] = BlipaProcessor(tokenizer=snake_case ,image_processor=snake_case ) lowercase : Tuple = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowercase : List[str] = processor.batch_decode(snake_case ) lowercase : List[Any] = tokenizer.batch_decode(snake_case ) self.assertListEqual(snake_case ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = self.get_image_processor() lowercase : List[str] = self.get_tokenizer() lowercase : List[Any] = BlipaProcessor(tokenizer=snake_case ,image_processor=snake_case ) lowercase : str = """lower newer""" lowercase : Tuple = self.prepare_image_inputs() lowercase : Optional[int] = processor(text=snake_case ,images=snake_case ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) ,["""pixel_values""", """input_ids""", """attention_mask"""] )
20
"""simple docstring""" from math import factorial def _A ( lowercase = 1_00 ): """simple docstring""" return sum(int(lowercase ) for x in str(factorial(lowercase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
81
0
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def UpperCamelCase_( lowerCamelCase_ ) -> int: _lowercase : Optional[Any] = prime_factors(lowerCamelCase_ ) if is_square_free(lowerCamelCase_ ): return -1 if len(lowerCamelCase_ ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
21
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Optional[Any] = """▁""" lowerCamelCase_ : Union[str, Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : Any = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowerCamelCase_ : Tuple = { """xlm-roberta-base""": 5_1_2, """xlm-roberta-large""": 5_1_2, """xlm-roberta-large-finetuned-conll02-dutch""": 5_1_2, """xlm-roberta-large-finetuned-conll02-spanish""": 5_1_2, """xlm-roberta-large-finetuned-conll03-english""": 5_1_2, """xlm-roberta-large-finetuned-conll03-german""": 5_1_2, } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} 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 , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a =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 a ={'''<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 a =1 a =len(self.sp_model ) + self.fairseq_offset a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: a =self.__dict__.copy() a =None a =self.sp_model.serialized_model_proto() return state def __setstate__( self , __A ) -> List[Any]: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ) -> List[str]: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =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 SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: a =''''''.join(__A ).replace(__A , ''' ''' ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =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: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor __SCREAMING_SNAKE_CASE :Dict = logging.get_logger(__name__) class A_ ( lowerCAmelCase_ ): def __init__( self : Dict , *snake_case_ : int , **snake_case_ : Optional[Any] ): warnings.warn( "The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use BeitImageProcessor instead." , snake_case_ , ) super().__init__(*snake_case_ , **snake_case_ )
22
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Tuple = {"""vocab_file""": """sentencepiece.bpe.model"""} lowerCamelCase_ : str = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } lowerCamelCase_ : Optional[int] = { """moussaKam/mbarthez""": 1_0_2_4, """moussaKam/barthez""": 1_0_2_4, """moussaKam/barthez-orangesum-title""": 1_0_2_4, } lowerCamelCase_ : Tuple = """▁""" class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["input_ids", "attention_mask"] def __init__( self , __A , __A="<s>" , __A="</s>" , __A="</s>" , __A="<s>" , __A="<unk>" , __A="<pad>" , __A="<mask>" , __A = None , **__A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it a =AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token a ={} 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 , sp_model_kwargs=self.sp_model_kwargs , **__A , ) a =vocab_file a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) a ={'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} a =len(self.sp_model ) - 1 a ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a =[self.cls_token_id] a =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) if token_ids_a is None: return [1] + ([0] * len(__A )) + [1] return [1] + ([0] * len(__A )) + [1, 1] + ([0] * len(__A )) + [1] def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> List[int]: a =[self.sep_token_id] a =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ) -> Any: return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ) -> int: a ={self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] a =self.sp_model.PieceToId(__A ) return spm_id if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE ( self , __A ) -> Optional[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Tuple: a =[] a ='''''' a =False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__A ) + token a =True a =[] else: current_sub_tokens.append(__A ) a =False out_string += self.sp_model.decode(__A ) return out_string.strip() def __getstate__( self ) -> Tuple: a =self.__dict__.copy() a =None return state def __setstate__( self , __A ) -> Tuple: a =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a ={} a =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None ) -> Tuple[str]: if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return a =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: a =self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,)
81
0
'''simple docstring''' UpperCamelCase__: Tuple = 8.314462 # Unit - J mol-1 K-1 def snake_case_ ( _lowerCAmelCase : float , _lowerCAmelCase : float , _lowerCAmelCase : float ) -> float: if moles < 0 or kelvin < 0 or volume < 0: raise ValueError('''Invalid inputs. Enter positive value.''' ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def snake_case_ ( _lowerCAmelCase : float , _lowerCAmelCase : float , _lowerCAmelCase : float ) -> float: if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError('''Invalid inputs. Enter positive value.''' ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
23
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCamelCase_ : Tuple = logging.get_logger(__name__) lowerCamelCase_ : str = OrderedDict( [ ("""align""", """EfficientNetImageProcessor"""), ("""beit""", """BeitImageProcessor"""), ("""bit""", """BitImageProcessor"""), ("""blip""", """BlipImageProcessor"""), ("""blip-2""", """BlipImageProcessor"""), ("""bridgetower""", """BridgeTowerImageProcessor"""), ("""chinese_clip""", """ChineseCLIPImageProcessor"""), ("""clip""", """CLIPImageProcessor"""), ("""clipseg""", """ViTImageProcessor"""), ("""conditional_detr""", """ConditionalDetrImageProcessor"""), ("""convnext""", """ConvNextImageProcessor"""), ("""convnextv2""", """ConvNextImageProcessor"""), ("""cvt""", """ConvNextImageProcessor"""), ("""data2vec-vision""", """BeitImageProcessor"""), ("""deformable_detr""", """DeformableDetrImageProcessor"""), ("""deit""", """DeiTImageProcessor"""), ("""deta""", """DetaImageProcessor"""), ("""detr""", """DetrImageProcessor"""), ("""dinat""", """ViTImageProcessor"""), ("""donut-swin""", """DonutImageProcessor"""), ("""dpt""", """DPTImageProcessor"""), ("""efficientformer""", """EfficientFormerImageProcessor"""), ("""efficientnet""", """EfficientNetImageProcessor"""), ("""flava""", """FlavaImageProcessor"""), ("""focalnet""", """BitImageProcessor"""), ("""git""", """CLIPImageProcessor"""), ("""glpn""", """GLPNImageProcessor"""), ("""groupvit""", """CLIPImageProcessor"""), ("""imagegpt""", """ImageGPTImageProcessor"""), ("""instructblip""", """BlipImageProcessor"""), ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""), ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""), ("""levit""", """LevitImageProcessor"""), ("""mask2former""", """Mask2FormerImageProcessor"""), ("""maskformer""", """MaskFormerImageProcessor"""), ("""mgp-str""", """ViTImageProcessor"""), ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""), ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevit""", """MobileViTImageProcessor"""), ("""mobilevitv2""", """MobileViTImageProcessor"""), ("""nat""", """ViTImageProcessor"""), ("""oneformer""", """OneFormerImageProcessor"""), ("""owlvit""", """OwlViTImageProcessor"""), ("""perceiver""", """PerceiverImageProcessor"""), ("""pix2struct""", """Pix2StructImageProcessor"""), ("""poolformer""", """PoolFormerImageProcessor"""), ("""regnet""", """ConvNextImageProcessor"""), ("""resnet""", """ConvNextImageProcessor"""), ("""sam""", """SamImageProcessor"""), ("""segformer""", """SegformerImageProcessor"""), ("""swiftformer""", """ViTImageProcessor"""), ("""swin""", """ViTImageProcessor"""), ("""swin2sr""", """Swin2SRImageProcessor"""), ("""swinv2""", """ViTImageProcessor"""), ("""table-transformer""", """DetrImageProcessor"""), ("""timesformer""", """VideoMAEImageProcessor"""), ("""tvlt""", """TvltImageProcessor"""), ("""upernet""", """SegformerImageProcessor"""), ("""van""", """ConvNextImageProcessor"""), ("""videomae""", """VideoMAEImageProcessor"""), ("""vilt""", """ViltImageProcessor"""), ("""vit""", """ViTImageProcessor"""), ("""vit_hybrid""", """ViTHybridImageProcessor"""), ("""vit_mae""", """ViTImageProcessor"""), ("""vit_msn""", """ViTImageProcessor"""), ("""xclip""", """CLIPImageProcessor"""), ("""yolos""", """YolosImageProcessor"""), ] ) lowerCamelCase_ : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def _A ( lowercase ): """simple docstring""" for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: a =model_type_to_module_name(lowercase ) a =importlib.import_module(f'''.{module_name}''' , '''transformers.models''' ) try: return getattr(lowercase , lowercase ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowercase , '''__name__''' , lowercase ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. a =importlib.import_module('''transformers''' ) if hasattr(lowercase , lowercase ): return getattr(lowercase , lowercase ) return None def _A ( lowercase , lowercase = None , lowercase = False , lowercase = False , lowercase = None , lowercase = None , lowercase = None , lowercase = False , **lowercase , ): """simple docstring""" a =get_file_from_repo( lowercase , lowercase , cache_dir=lowercase , force_download=lowercase , resume_download=lowercase , proxies=lowercase , use_auth_token=lowercase , revision=lowercase , local_files_only=lowercase , ) if resolved_config_file is None: logger.info( '''Could not locate the image processor configuration file, will try to use the model config instead.''' ) return {} with open(lowercase , encoding='''utf-8''' ) as reader: return json.load(lowercase ) class __A : """simple docstring""" def __init__( self ) -> Optional[Any]: raise EnvironmentError( '''AutoImageProcessor is designed to be instantiated ''' '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.''' ) @classmethod @replace_list_option_in_docstrings(__A ) def SCREAMING_SNAKE_CASE ( cls , __A , **__A ) -> Dict: a =kwargs.pop('''config''' , __A ) a =kwargs.pop('''trust_remote_code''' , __A ) a =True a , a =ImageProcessingMixin.get_image_processor_dict(__A , **__A ) a =config_dict.get('''image_processor_type''' , __A ) a =None if "AutoImageProcessor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoImageProcessor'''] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: a =config_dict.pop('''feature_extractor_type''' , __A ) if feature_extractor_class is not None: logger.warning( '''Could not find image processor class in the image processor config or the model config. Loading''' ''' based on pattern matching with the model\'s feature extractor configuration.''' ) a =feature_extractor_class.replace('''FeatureExtractor''' , '''ImageProcessor''' ) if "AutoFeatureExtractor" in config_dict.get('''auto_map''' , {} ): a =config_dict['''auto_map''']['''AutoFeatureExtractor'''] a =feature_extractor_auto_map.replace('''FeatureExtractor''' , '''ImageProcessor''' ) logger.warning( '''Could not find image processor auto map in the image processor config or the model config.''' ''' Loading based on pattern matching with the model\'s feature extractor configuration.''' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(__A , __A ): a =AutoConfig.from_pretrained(__A , **__A ) # It could be in `config.image_processor_type`` a =getattr(__A , '''image_processor_type''' , __A ) if hasattr(__A , '''auto_map''' ) and "AutoImageProcessor" in config.auto_map: a =config.auto_map['''AutoImageProcessor'''] if image_processor_class is not None: a =image_processor_class_from_name(__A ) a =image_processor_auto_map is not None a =image_processor_class is not None or type(__A ) in IMAGE_PROCESSOR_MAPPING a =resolve_trust_remote_code( __A , __A , __A , __A ) if has_remote_code and trust_remote_code: a =get_class_from_dynamic_module( __A , __A , **__A ) a =kwargs.pop('''code_revision''' , __A ) if os.path.isdir(__A ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(__A , **__A ) elif image_processor_class is not None: return image_processor_class.from_dict(__A , **__A ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(__A ) in IMAGE_PROCESSOR_MAPPING: a =IMAGE_PROCESSOR_MAPPING[type(__A )] return image_processor_class.from_dict(__A , **__A ) raise ValueError( f'''Unrecognized image processor in {pretrained_model_name_or_path}. Should have a ''' f'''`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following ''' f'''`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}''' ) @staticmethod def SCREAMING_SNAKE_CASE ( __A , __A ) -> Any: IMAGE_PROCESSOR_MAPPING.register(__A , __A )
81
0
def lowerCamelCase__ ( snake_case_ : list ) -> list: if len(snake_case_ ) <= 1: return lst __snake_case = 1 while i < len(snake_case_ ): if lst[i - 1] <= lst[i]: i += 1 else: __snake_case , __snake_case = lst[i], lst[i - 1] i -= 1 if i == 0: __snake_case = 1 return lst if __name__ == "__main__": snake_case_ = input('Enter numbers separated by a comma:\n').strip() snake_case_ = [int(item) for item in user_input.split(',')] print(gnome_sort(unsorted))
24
"""simple docstring""" from transformers import DistilBertTokenizer, DistilBertTokenizerFast from transformers.testing_utils import require_tokenizers, slow from ..bert.test_tokenization_bert import BertTokenizationTest @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = DistilBertTokenizer __lowerCAmelCase = DistilBertTokenizerFast __lowerCAmelCase = True @slow def SCREAMING_SNAKE_CASE ( self ) -> int: a =DistilBertTokenizer.from_pretrained('''distilbert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ]
81
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ : str = { 'configuration_xlm_roberta': [ 'XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMRobertaConfig', 'XLMRobertaOnnxConfig', ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = ['XLMRobertaTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = ['XLMRobertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = [ 'XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLMRobertaForCausalLM', 'XLMRobertaForMaskedLM', 'XLMRobertaForMultipleChoice', 'XLMRobertaForQuestionAnswering', 'XLMRobertaForSequenceClassification', 'XLMRobertaForTokenClassification', 'XLMRobertaModel', 'XLMRobertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = [ 'TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLMRobertaForCausalLM', 'TFXLMRobertaForMaskedLM', 'TFXLMRobertaForMultipleChoice', 'TFXLMRobertaForQuestionAnswering', 'TFXLMRobertaForSequenceClassification', 'TFXLMRobertaForTokenClassification', 'TFXLMRobertaModel', 'TFXLMRobertaPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = [ 'FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'FlaxXLMRobertaForMaskedLM', 'FlaxXLMRobertaForCausalLM', 'FlaxXLMRobertaForMultipleChoice', 'FlaxXLMRobertaForQuestionAnswering', 'FlaxXLMRobertaForSequenceClassification', 'FlaxXLMRobertaForTokenClassification', 'FlaxXLMRobertaModel', 'FlaxXLMRobertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys UpperCAmelCase__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
25
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""], """processing_speech_to_text""": ["""Speech2TextProcessor"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""Speech2TextTokenizer"""] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Optional[Any] = ["""Speech2TextFeatureExtractor"""] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFSpeech2TextForConditionalGeneration""", """TFSpeech2TextModel""", """TFSpeech2TextPreTrainedModel""", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = [ """SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Speech2TextForConditionalGeneration""", """Speech2TextModel""", """Speech2TextPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
0
def lowerCAmelCase_ ( snake_case_ ): return "".join([hex(snake_case_ )[2:].zfill(2 ).upper() for byte in list(snake_case_ )] ) def lowerCAmelCase_ ( snake_case_ ): # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(snake_case_ ) % 2) != 0: raise ValueError( """Base16 encoded data is invalid: Data does not have an even number of hex digits.""" ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(snake_case_ ) <= set("""0123456789ABCDEF""" ): raise ValueError( """Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters.""" ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1],16 ) for i in range(0,len(snake_case_ ),2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
26
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ : Union[str, Any] = { """configuration_table_transformer""": [ """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TableTransformerConfig""", """TableTransformerOnnxConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[Any] = [ """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TableTransformerForObjectDetection""", """TableTransformerModel""", """TableTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig, TableTransformerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) else: import sys lowerCamelCase_ : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
0
'''simple docstring''' 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, ) __lowercase : Union[str, Any] = '\\n Text data.\n Second line of data.' __lowercase : Optional[int] = 'file' @pytest.fixture(scope='session' ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): __a : Optional[int] = tmp_path_factory.mktemp('data' ) / (FILE_PATH + '.zstd') __a : Optional[int] = bytes(_SCREAMING_SNAKE_CASE , 'utf-8' ) with zstd.open(_SCREAMING_SNAKE_CASE , 'wb' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): with open(os.path.join(tmpfs.local_root_dir , _SCREAMING_SNAKE_CASE ) , 'w' ) as f: f.write(_SCREAMING_SNAKE_CASE ) return FILE_PATH @pytest.mark.parametrize('compression_format' , ['gzip', 'xz', 'zstd'] ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Optional[int] = {'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_path} __a : Optional[int] = input_paths[compression_format] __a : Any = tmp_path / 'cache' __a : int = DownloadConfig(cache_dir=_SCREAMING_SNAKE_CASE , extract_compressed_file=_SCREAMING_SNAKE_CASE ) __a : str = cached_path(_SCREAMING_SNAKE_CASE , download_config=_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE ) as f: __a : int = f.read() with open(_SCREAMING_SNAKE_CASE ) as f: __a : Union[str, Any] = 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 lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[Any] ): __a : Optional[int] = 'custom_cache' __a : str = 'custom_extracted_dir' __a : Optional[int] = tmp_path / 'custom_extracted_path' if default_extracted: __a : str = ('downloads' if default_cache_dir else custom_cache_dir, 'extracted') else: monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_DIR' , _SCREAMING_SNAKE_CASE ) monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(_SCREAMING_SNAKE_CASE ) ) __a : Union[str, Any] = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) __a : Optional[int] = xz_file __a : Dict = ( DownloadConfig(extract_compressed_file=_SCREAMING_SNAKE_CASE ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_SCREAMING_SNAKE_CASE ) ) __a : int = cached_path(_SCREAMING_SNAKE_CASE , download_config=_SCREAMING_SNAKE_CASE ) assert Path(_SCREAMING_SNAKE_CASE ).parent.parts[-2:] == expected def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[str] ): # absolute path __a : List[str] = str(Path(_SCREAMING_SNAKE_CASE ).resolve() ) assert cached_path(_SCREAMING_SNAKE_CASE ) == text_file # relative path __a : List[Any] = str(Path(_SCREAMING_SNAKE_CASE ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(_SCREAMING_SNAKE_CASE ) == text_file def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[int] ): # absolute path __a : Any = str(tmp_path.resolve() / '__missing_file__.txt' ) with pytest.raises(_SCREAMING_SNAKE_CASE ): cached_path(_SCREAMING_SNAKE_CASE ) # relative path __a : Tuple = './__missing_file__.txt' with pytest.raises(_SCREAMING_SNAKE_CASE ): cached_path(_SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] ): __a : Tuple = get_from_cache(F"""tmp://{tmpfs_file}""" ) with open(_SCREAMING_SNAKE_CASE ) as f: __a : str = f.read() assert output_file_content == FILE_CONTENT @patch('datasets.config.HF_DATASETS_OFFLINE' , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (): with pytest.raises(_SCREAMING_SNAKE_CASE ): cached_path('https://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Any ): __a : Tuple = tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(_SCREAMING_SNAKE_CASE ): http_get('https://huggingface.co' , temp_file=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE ): http_head('https://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a : Optional[Any] = tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(_SCREAMING_SNAKE_CASE ): ftp_get('ftp://huggingface.co' , temp_file=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE ): ftp_head('ftp://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Dict ): __a : Union[str, Any] = tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(_SCREAMING_SNAKE_CASE ): fsspec_get('s3://huggingface.co' , temp_file=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE ): fsspec_head('s3://huggingface.co' )
27
"""simple docstring""" from __future__ import annotations import math def _A ( lowercase ): """simple docstring""" if num <= 0: a =f'''{num}: Invalid input, please enter a positive integer.''' raise ValueError(lowercase ) a =[True] * (num + 1) a =[] a =2 a =int(math.sqrt(lowercase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowercase ) # Set multiples of start be False for i in range(start * start , num + 1 , lowercase ): if sieve[i] is True: a =False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowercase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
81
0
'''simple docstring''' from math import sqrt def __lowerCamelCase ( A__ ) -> int: """simple docstring""" UpperCamelCase = 0 for i in range(1 , int(sqrt(A__ ) + 1 ) ): if n % i == 0 and i != sqrt(A__ ): total += i + n // i elif i == sqrt(A__ ): total += i return total - n def __lowerCamelCase ( A__ = 10_000 ) -> int: """simple docstring""" UpperCamelCase = sum( i for i in range(1 , A__ ) if sum_of_divisors(sum_of_divisors(A__ ) ) == i and sum_of_divisors(A__ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
28
"""simple docstring""" import os import unittest from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, BertTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = BertTokenizer __lowerCAmelCase = BertTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True __lowerCAmelCase = filter_non_english def SCREAMING_SNAKE_CASE ( self ) -> List[str]: super().setUp() a =[ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Union[str, Any]: a ='''UNwant\u00E9d,running''' a ='''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.tokenizer_class(self.vocab_file ) a =tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [9, 6, 7, 12, 10, 11] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: if not self.test_rust_tokenizer: return a =self.get_tokenizer() a =self.get_rust_tokenizer() a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) # With lower casing a =self.get_tokenizer(do_lower_case=__A ) a =self.get_rust_tokenizer(do_lower_case=__A ) a ='''UNwant\u00E9d,running''' a =tokenizer.tokenize(__A ) a =rust_tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) a =tokenizer.encode(__A , add_special_tokens=__A ) a =rust_tokenizer.encode(__A , add_special_tokens=__A ) self.assertListEqual(__A , __A ) a =self.get_rust_tokenizer() a =tokenizer.encode(__A ) a =rust_tokenizer.encode(__A ) self.assertListEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Any: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =BasicTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =BasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =BasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =BasicTokenizer(do_lower_case=__A , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =BasicTokenizer() a ='''a\n\'ll !!to?\'d of, can\'t.''' a =['''a''', '''\'''', '''ll''', '''!''', '''!''', '''to''', '''?''', '''\'''', '''d''', '''of''', ''',''', '''can''', '''\'''', '''t''', '''.'''] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a ={} for i, token in enumerate(__A ): a =i a =WordpieceTokenizer(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 SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Any: 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 SCREAMING_SNAKE_CASE ( self ) -> str: self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =self.get_tokenizer() a =self.get_rust_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]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.tokenizer_class.from_pretrained('''bert-base-uncased''' ) a =tokenizer.encode('''sequence builders''' , add_special_tokens=__A ) a =tokenizer.encode('''multi-sequence build''' , add_special_tokens=__A ) a =tokenizer.build_inputs_with_special_tokens(__A ) a =tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def SCREAMING_SNAKE_CASE ( self ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a =tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) a =tokenizer_r.do_lower_case if hasattr(__A , '''do_lower_case''' ) else False a =( [ ((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 SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =['''的''', '''人''', '''有'''] a =''''''.join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a =True a =self.tokenizer_class.from_pretrained(__A , **__A ) a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =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 ) a =False a =self.rust_tokenizer_class.from_pretrained(__A , **__A ) a =self.tokenizer_class.from_pretrained(__A , **__A ) a =tokenizer_r.encode(__A , add_special_tokens=__A ) a =tokenizer_p.encode(__A , add_special_tokens=__A ) a =tokenizer_r.convert_ids_to_tokens(__A ) a =tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". a =[ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A )
81
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import importlib.metadata import json import os from dataclasses import dataclass from typing import Any, Dict, Union from packaging import version from ..utils import is_torch_available, logging if is_torch_available(): import torch __UpperCAmelCase = logging.get_logger(__name__) @dataclass class lowerCamelCase : '''simple docstring''' def __init__( self , _UpperCamelCase=False , _UpperCamelCase=False , _UpperCamelCase=6.0 , _UpperCamelCase=None , _UpperCamelCase=False , _UpperCamelCase=False , _UpperCamelCase=None , _UpperCamelCase="fp4" , _UpperCamelCase=False , **_UpperCamelCase , ) -> Optional[int]: UpperCAmelCase_ : Union[str, Any] = load_in_abit UpperCAmelCase_ : Any = load_in_abit UpperCAmelCase_ : List[Any] = llm_inta_threshold UpperCAmelCase_ : Tuple = llm_inta_skip_modules UpperCAmelCase_ : Tuple = llm_inta_enable_fpaa_cpu_offload UpperCAmelCase_ : Optional[Any] = llm_inta_has_fpaa_weight UpperCAmelCase_ : Union[str, Any] = bnb_abit_quant_type UpperCAmelCase_ : Dict = bnb_abit_use_double_quant if bnb_abit_compute_dtype is None: UpperCAmelCase_ : int = torch.floataa elif isinstance(_UpperCamelCase , _UpperCamelCase ): UpperCAmelCase_ : str = getattr(_UpperCamelCase , _UpperCamelCase ) elif isinstance(_UpperCamelCase , torch.dtype ): UpperCAmelCase_ : Optional[Any] = bnb_abit_compute_dtype else: raise ValueError('bnb_4bit_compute_dtype must be a string or a torch.dtype' ) self.post_init() def __UpperCAmelCase ( self ) -> int: if not isinstance(self.llm_inta_threshold , _UpperCamelCase ): raise ValueError('llm_int8_threshold must be a float' ) if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules , _UpperCamelCase ): raise ValueError('llm_int8_skip_modules must be a list of strings' ) if not isinstance(self.llm_inta_enable_fpaa_cpu_offload , _UpperCamelCase ): raise ValueError('llm_int8_enable_fp32_cpu_offload must be a boolean' ) if not isinstance(self.llm_inta_has_fpaa_weight , _UpperCamelCase ): raise ValueError('llm_int8_has_fp16_weight must be a boolean' ) if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype , torch.dtype ): raise ValueError('bnb_4bit_compute_dtype must be torch.dtype' ) if not isinstance(self.bnb_abit_quant_type , _UpperCamelCase ): raise ValueError('bnb_4bit_quant_type must be a string' ) if not isinstance(self.bnb_abit_use_double_quant , _UpperCamelCase ): raise ValueError('bnb_4bit_use_double_quant must be a boolean' ) if self.load_in_abit and not version.parse(importlib.metadata.version('bitsandbytes' ) ) >= version.parse( '0.39.0' ): raise ValueError( '4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version' ) def __UpperCAmelCase ( self ) -> str: return self.load_in_abit or self.load_in_abit def __UpperCAmelCase ( self ) -> List[str]: if self.load_in_abit: return "llm_int8" elif self.load_in_abit and self.bnb_abit_quant_type == "fp4": return "fp4" elif self.load_in_abit and self.bnb_abit_quant_type == "nf4": return "nf4" else: return None @classmethod def __UpperCAmelCase ( cls , _UpperCamelCase , _UpperCamelCase , **_UpperCamelCase ) -> Tuple: UpperCAmelCase_ : str = cls(**_UpperCamelCase ) UpperCAmelCase_ : Dict = [] for key, value in kwargs.items(): if hasattr(_UpperCamelCase , _UpperCamelCase ): setattr(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) to_remove.append(_UpperCamelCase ) for key in to_remove: kwargs.pop(_UpperCamelCase , _UpperCamelCase ) if return_unused_kwargs: return config, kwargs else: return config def __UpperCAmelCase ( self , _UpperCamelCase ) -> int: with open(_UpperCamelCase , 'w' , encoding='utf-8' ) as writer: UpperCAmelCase_ : Union[str, Any] = self.to_dict() UpperCAmelCase_ : Optional[Any] = json.dumps(_UpperCamelCase , indent=2 , sort_keys=_UpperCamelCase ) + '\n' writer.write(_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Dict[str, Any]: UpperCAmelCase_ : Optional[Any] = copy.deepcopy(self.__dict__ ) UpperCAmelCase_ : Any = str(output['bnb_4bit_compute_dtype'] ).split('.' )[1] return output def __repr__( self ) -> Optional[Any]: return f"{self.__class__.__name__} {self.to_json_string()}" def __UpperCAmelCase ( self , _UpperCamelCase = True ) -> str: if use_diff is True: UpperCAmelCase_ : Tuple = self.to_diff_dict() else: UpperCAmelCase_ : Dict = self.to_dict() return json.dumps(_UpperCamelCase , indent=2 , sort_keys=_UpperCamelCase ) + "\n" def __UpperCAmelCase ( self ) -> Dict[str, Any]: UpperCAmelCase_ : str = self.to_dict() # get the default config dict UpperCAmelCase_ : Optional[Any] = BitsAndBytesConfig().to_dict() UpperCAmelCase_ : Optional[int] = {} # only serialize values that differ from the default config for key, value in config_dict.items(): if value != default_config_dict[key]: UpperCAmelCase_ : List[str] = value return serializable_config_dict
29
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Union[str, Any] = logging.get_logger(__name__) lowerCamelCase_ : Any = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = "conditional_detr" __lowerCAmelCase = ["past_key_values"] __lowerCAmelCase = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , __A=True , __A=None , __A=3 , __A=300 , __A=6 , __A=2048 , __A=8 , __A=6 , __A=2048 , __A=8 , __A=0.0 , __A=0.0 , __A=True , __A="relu" , __A=256 , __A=0.1 , __A=0.0 , __A=0.0 , __A=0.02 , __A=1.0 , __A=False , __A="sine" , __A="resnet50" , __A=True , __A=False , __A=2 , __A=5 , __A=2 , __A=1 , __A=1 , __A=2 , __A=5 , __A=2 , __A=0.25 , **__A , ) -> List[Any]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) a =CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__A , __A ): a =backbone_config.get('''model_type''' ) a =CONFIG_MAPPING[backbone_model_type] a =config_class.from_dict(__A ) a =use_timm_backbone a =backbone_config a =num_channels a =num_queries a =d_model a =encoder_ffn_dim a =encoder_layers a =encoder_attention_heads a =decoder_ffn_dim a =decoder_layers a =decoder_attention_heads a =dropout a =attention_dropout a =activation_dropout a =activation_function a =init_std a =init_xavier_std a =encoder_layerdrop a =decoder_layerdrop a =encoder_layers a =auxiliary_loss a =position_embedding_type a =backbone a =use_pretrained_backbone a =dilation # Hungarian matcher a =class_cost a =bbox_cost a =giou_cost # Loss coefficients a =mask_loss_coefficient a =dice_loss_coefficient a =cls_loss_coefficient a =bbox_loss_coefficient a =giou_loss_coefficient a =focal_alpha super().__init__(is_encoder_decoder=__A , **__A ) @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: a =self.backbone_config.to_dict() a =self.__class__.model_type return output class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self ) -> float: return 1E-5 @property def SCREAMING_SNAKE_CASE ( self ) -> int: return 12
81
0
import sys __a = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def a ( snake_case__: str = N ): '''simple docstring''' lowercase_ = -sys.maxsize - 1 for i in range(len(snake_case__ ) - 12 ): lowercase_ = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: lowercase_ = product return largest_product if __name__ == "__main__": print(f"{solution() = }")
30
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" while second != 0: a =first & second first ^= second a =c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ : Dict = int(input("""Enter the first number: """).strip()) lowerCamelCase_ : List[Any] = int(input("""Enter the second number: """).strip()) print(F'{add(first, second) = }')
81
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[int] = { """configuration_swinv2""": ["""SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Swinv2Config"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ """SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST""", """Swinv2ForImageClassification""", """Swinv2ForMaskedImageModeling""", """Swinv2Model""", """Swinv2PreTrainedModel""", ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
31
"""simple docstring""" import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" a =ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=lowercase , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=lowercase , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=lowercase ) return parser.parse_args() def _A ( ): """simple docstring""" a =parse_args() # Import training_script as a module. a =Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a =script_fpath.stem a =importlib.import_module(lowercase ) # Patch sys.argv a =[args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
81
0
import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> Union[str, Any]: """simple docstring""" a_ : Dict = SwinConfig(image_size=1_92 ) if "base" in model_name: a_ : List[str] = 6 a_ : int = 1_28 a_ : Tuple = (2, 2, 18, 2) a_ : Optional[int] = (4, 8, 16, 32) elif "large" in model_name: a_ : List[str] = 12 a_ : Union[str, Any] = 1_92 a_ : Union[str, Any] = (2, 2, 18, 2) a_ : str = (6, 12, 24, 48) else: raise ValueError('Model not supported, only supports base and large variants' ) a_ : List[str] = window_size a_ : Any = embed_dim a_ : Optional[int] = depths a_ : List[Any] = num_heads return config def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> Optional[int]: """simple docstring""" if "encoder.mask_token" in name: a_ : Dict = name.replace('encoder.mask_token' , 'embeddings.mask_token' ) if "encoder.patch_embed.proj" in name: a_ : int = name.replace('encoder.patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "encoder.patch_embed.norm" in name: a_ : Tuple = name.replace('encoder.patch_embed.norm' , 'embeddings.norm' ) if "attn.proj" in name: a_ : int = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: a_ : Union[str, Any] = name.replace('attn' , 'attention.self' ) if "norm1" in name: a_ : Dict = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: a_ : int = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: a_ : Tuple = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: a_ : Dict = name.replace('mlp.fc2' , 'output.dense' ) if name == "encoder.norm.weight": a_ : Optional[int] = 'layernorm.weight' if name == "encoder.norm.bias": a_ : Union[str, Any] = 'layernorm.bias' if "decoder" in name: pass else: a_ : List[str] = 'swin.' + name return name def SCREAMING_SNAKE_CASE_ ( __A : Optional[Any] , __A : Tuple ) -> List[str]: """simple docstring""" for key in orig_state_dict.copy().keys(): a_ : List[str] = orig_state_dict.pop(__A ) if "attn_mask" in key: pass elif "qkv" in key: a_ : int = key.split('.' ) a_ : Dict = int(key_split[2] ) a_ : Union[str, Any] = int(key_split[4] ) a_ : Dict = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a_ : int = val[:dim, :] a_ : Optional[Any] = val[ dim : dim * 2, : ] a_ : List[str] = val[-dim:, :] else: a_ : Union[str, Any] = val[ :dim ] a_ : Dict = val[ dim : dim * 2 ] a_ : Tuple = val[ -dim: ] else: a_ : int = val return orig_state_dict def SCREAMING_SNAKE_CASE_ ( __A : str , __A : Any , __A : str , __A : Optional[int] ) -> Union[str, Any]: """simple docstring""" a_ : str = torch.load(__A , map_location='cpu' )['model'] a_ : Union[str, Any] = get_swin_config(__A ) a_ : List[str] = SwinForMaskedImageModeling(__A ) model.eval() a_ : Dict = convert_state_dict(__A , __A ) model.load_state_dict(__A ) a_ : List[Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' a_ : List[str] = ViTImageProcessor(size={'height': 1_92, 'width': 1_92} ) a_ : Optional[Any] = Image.open(requests.get(__A , stream=__A ).raw ) a_ : List[str] = image_processor(images=__A , return_tensors='pt' ) with torch.no_grad(): a_ : str = model(**__A ).logits print(outputs.keys() ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__A ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__A ) if push_to_hub: print(F"""Pushing model and image processor for {model_name} to hub""" ) model.push_to_hub(F"""microsoft/{model_name}""" ) image_processor.push_to_hub(F"""microsoft/{model_name}""" ) if __name__ == "__main__": UpperCAmelCase_ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='swin-base-simmim-window6-192', type=str, choices=['swin-base-simmim-window6-192', 'swin-large-simmim-window12-192'], help='Name of the Swin SimMIM model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default='/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth', 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 output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) UpperCAmelCase_ : List[Any] = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
32
"""simple docstring""" import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCamelCase_ : str = logging.get_logger(__name__) class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self , *__A , **__A ) -> None: warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' , __A , ) super().__init__(*__A , **__A )
81
0
"""simple docstring""" import math class _UpperCAmelCase : def __init__( self : Union[str, Any] , A : Optional[int]=0 ) -> Union[str, Any]: # a graph with Node 0,1,...,N-1 lowercase_ : Any = n lowercase_ : Any = [ [math.inf for j in range(0 , A )] for i in range(0 , A ) ] # adjacency matrix for weight lowercase_ : List[Any] = [ [math.inf for j in range(0 , A )] for i in range(0 , A ) ] # dp[i][j] stores minimum distance from i to j def A ( self : List[str] , A : Dict , A : str , A : Optional[Any] ) -> Any: lowercase_ : Any = w def A ( self : Optional[Any] ) -> Tuple: for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): lowercase_ : str = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def A ( self : Any , A : Tuple , A : Dict ) -> str: return self.dp[u][v] if __name__ == "__main__": __A : str = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
33
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" return number | (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number & ~(1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return number ^ (1 << position) def _A ( lowercase , lowercase ): """simple docstring""" return ((number >> position) & 1) == 1 def _A ( lowercase , lowercase ): """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
81
0
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class _a ( __a ): @staticmethod @abstractmethod def A ( lowercase : ArgumentParser ): '''simple docstring''' raise NotImplementedError() @abstractmethod def A ( self : Optional[Any] ): '''simple docstring''' raise NotImplementedError()
34
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() __a = logging.get_logger(__name__) def __snake_case( _lowerCAmelCase , _lowerCAmelCase=False ) -> str: snake_case__ : Union[str, Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"deit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"blocks.{i}.norm1.bias", f"deit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"deit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"deit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"blocks.{i}.norm2.weight", f"deit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"blocks.{i}.norm2.bias", f"deit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"deit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"deit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"deit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"deit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" snake_case__ : List[Any] = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=False ) -> Union[str, Any]: for i in range(config.num_hidden_layers ): if base_model: snake_case__ : Tuple = """""" else: snake_case__ : Dict = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case__ : Optional[Any] = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) snake_case__ : Tuple = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Any = in_proj_weight[ : config.hidden_size, : ] snake_case__ : Optional[int] = in_proj_bias[: config.hidden_size] snake_case__ : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case__ : str = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] snake_case__ : Tuple = in_proj_bias[-config.hidden_size :] def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> int: snake_case__ : str = dct.pop(_lowerCAmelCase ) snake_case__ : Tuple = val def __snake_case( ) -> Tuple: snake_case__ : Union[str, Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case__ : Optional[int] = Image.open(requests.get(_lowerCAmelCase , stream=_lowerCAmelCase ).raw ) return im @torch.no_grad() def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> str: snake_case__ : Optional[int] = DeiTConfig() # all deit models have fine-tuned heads snake_case__ : Union[str, Any] = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size snake_case__ : int = 1_000 snake_case__ : Any = """huggingface/label-files""" snake_case__ : Optional[Any] = """imagenet-1k-id2label.json""" snake_case__ : Tuple = json.load(open(hf_hub_download(_lowerCAmelCase , _lowerCAmelCase , repo_type="""dataset""" ) , """r""" ) ) snake_case__ : List[Any] = {int(_lowerCAmelCase ): v for k, v in idalabel.items()} snake_case__ : List[Any] = idalabel snake_case__ : List[str] = {v: k for k, v in idalabel.items()} snake_case__ : Tuple = int(deit_name[-6:-4] ) snake_case__ : Optional[Any] = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): snake_case__ : Tuple = 192 snake_case__ : Union[str, Any] = 768 snake_case__ : Tuple = 12 snake_case__ : Union[str, Any] = 3 elif deit_name[9:].startswith("""small""" ): snake_case__ : str = 384 snake_case__ : Any = 1_536 snake_case__ : str = 12 snake_case__ : int = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): snake_case__ : Union[str, Any] = 1_024 snake_case__ : Any = 4_096 snake_case__ : List[Any] = 24 snake_case__ : Tuple = 16 # load original model from timm snake_case__ : List[Any] = timm.create_model(_lowerCAmelCase , pretrained=_lowerCAmelCase ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case__ : Optional[Any] = timm_model.state_dict() snake_case__ : Optional[int] = create_rename_keys(_lowerCAmelCase , _lowerCAmelCase ) for src, dest in rename_keys: rename_key(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) read_in_q_k_v(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # load HuggingFace model snake_case__ : Optional[Any] = DeiTForImageClassificationWithTeacher(_lowerCAmelCase ).eval() model.load_state_dict(_lowerCAmelCase ) # Check outputs on an image, prepared by DeiTImageProcessor snake_case__ : List[Any] = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 snake_case__ : Optional[Any] = DeiTImageProcessor(size=_lowerCAmelCase , crop_size=config.image_size ) snake_case__ : str = image_processor(images=prepare_img() , return_tensors="""pt""" ) snake_case__ : Optional[Any] = encoding["""pixel_values"""] snake_case__ : Tuple = model(_lowerCAmelCase ) snake_case__ : Optional[int] = timm_model(_lowerCAmelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_lowerCAmelCase , outputs.logits , atol=1e-3 ) Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) print(f"Saving model {deit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_lowerCAmelCase ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": __a = argparse.ArgumentParser() # Required parameters parser.add_argument( "--deit_name", default="vit_deit_base_distilled_patch16_224", type=str, help="Name of the DeiT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) __a = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
35
"""simple docstring""" lowerCamelCase_ : Any = [ """DownloadConfig""", """DownloadManager""", """DownloadMode""", """StreamingDownloadManager""", ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
81
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): '''simple docstring''' _lowerCAmelCase : int = pipeline( task="zero-shot-audio-classification", model="hf-internal-testing/tiny-clap-htsat-unfused") _lowerCAmelCase : Tuple = load_dataset("ashraq/esc50") _lowerCAmelCase : List[str] = dataset["train"]["audio"][-1]["array"] _lowerCAmelCase : Dict = audio_classifier(__a, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]) self.assertEqual( nested_simplify(__a), [{"score": 0.501, "label": "Sound of a dog"}, {"score": 0.499, "label": "Sound of vaccum cleaner"}], ) @unittest.skip("No models are available in TF") def snake_case__ ( self): '''simple docstring''' pass @slow @require_torch def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Tuple = pipeline( task="zero-shot-audio-classification", model="laion/clap-htsat-unfused", ) # This is an audio of a dog _lowerCAmelCase : Any = load_dataset("ashraq/esc50") _lowerCAmelCase : Tuple = dataset["train"]["audio"][-1]["array"] _lowerCAmelCase : Tuple = audio_classifier(__a, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]) self.assertEqual( nested_simplify(__a), [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ) _lowerCAmelCase : Optional[int] = audio_classifier([audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]) self.assertEqual( nested_simplify(__a), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) _lowerCAmelCase : Optional[Any] = audio_classifier( [audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"], batch_size=5) self.assertEqual( nested_simplify(__a), [ [ {"score": 0.999, "label": "Sound of a dog"}, {"score": 0.001, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) @unittest.skip("No models are available in TF") def snake_case__ ( self): '''simple docstring''' pass
36
"""simple docstring""" from scipy.stats import pearsonr import datasets lowerCamelCase_ : Optional[int] = """ Pearson correlation coefficient and p-value for testing non-correlation. The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. """ lowerCamelCase_ : Optional[Any] = """ Args: predictions (`list` of `int`): Predicted class labels, as returned by a model. references (`list` of `int`): Ground truth labels. return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`. Returns: pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation. p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities. Examples: Example 1-A simple example using only predictions and references. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5]) >>> print(round(results['pearsonr'], 2)) -0.74 Example 2-The same as Example 1, but that also returns the `p-value`. >>> pearsonr_metric = datasets.load_metric(\"pearsonr\") >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True) >>> print(sorted(list(results.keys()))) ['p-value', 'pearsonr'] >>> print(round(results['pearsonr'], 2)) -0.74 >>> print(round(results['p-value'], 2)) 0.15 """ lowerCamelCase_ : Optional[int] = """ @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, Ilhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Antonio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''float''' ), '''references''': datasets.Value('''float''' ), } ) , reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'''] , ) def SCREAMING_SNAKE_CASE ( self , __A , __A , __A=False ) -> Optional[Any]: if return_pvalue: a =pearsonr(__A , __A ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__A , __A )[0] )}
81
0
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" return round(float(moles / volume ) * nfactor ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" return round(float((moles * 0.0821 * temperature) / (volume) ) ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): """simple docstring""" return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
37
"""simple docstring""" lowerCamelCase_ : int = """ # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCamelCase_ : Dict = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCamelCase_ : Union[str, Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
81
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging UpperCAmelCase_ : Tuple = logging.get_logger(__name__) if is_vision_available(): import PIL class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : Dict = ["""pixel_values"""] def __init__( self : List[str] , __lowerCamelCase : bool = True , __lowerCamelCase : Dict[str, int] = None , __lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , __lowerCamelCase : bool = True , __lowerCamelCase : Dict[str, int] = None , __lowerCamelCase : bool = True , __lowerCamelCase : Union[int, float] = 1 / 255 , __lowerCamelCase : bool = True , __lowerCamelCase : Optional[Union[float, List[float]]] = None , __lowerCamelCase : Optional[Union[float, List[float]]] = None , __lowerCamelCase : bool = True , **__lowerCamelCase : Optional[int] , ): super().__init__(**__lowerCamelCase ) UpperCamelCase :Tuple = size if size is not None else {"""shortest_edge""": 224} UpperCamelCase :Any = get_size_dict(__lowerCamelCase , default_to_square=__lowerCamelCase ) UpperCamelCase :Any = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} UpperCamelCase :int = get_size_dict(__lowerCamelCase , default_to_square=__lowerCamelCase , param_name="""crop_size""" ) UpperCamelCase :Tuple = do_resize UpperCamelCase :Optional[int] = size UpperCamelCase :List[Any] = resample UpperCamelCase :Union[str, Any] = do_center_crop UpperCamelCase :Tuple = crop_size UpperCamelCase :Union[str, Any] = do_rescale UpperCamelCase :Dict = rescale_factor UpperCamelCase :Optional[Any] = do_normalize UpperCamelCase :Any = image_mean if image_mean is not None else OPENAI_CLIP_MEAN UpperCamelCase :str = image_std if image_std is not None else OPENAI_CLIP_STD UpperCamelCase :str = do_convert_rgb def _A ( self : Dict , __lowerCamelCase : np.ndarray , __lowerCamelCase : Dict[str, int] , __lowerCamelCase : PILImageResampling = PILImageResampling.BICUBIC , __lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **__lowerCamelCase : Optional[int] , ): UpperCamelCase :Tuple = get_size_dict(__lowerCamelCase , default_to_square=__lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) UpperCamelCase :int = get_resize_output_image_size(__lowerCamelCase , size=size["""shortest_edge"""] , default_to_square=__lowerCamelCase ) return resize(__lowerCamelCase , size=__lowerCamelCase , resample=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : np.ndarray , __lowerCamelCase : Dict[str, int] , __lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **__lowerCamelCase : Tuple , ): UpperCamelCase :str = get_size_dict(__lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(__lowerCamelCase , size=(size["""height"""], size["""width"""]) , data_format=__lowerCamelCase , **__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : np.ndarray , __lowerCamelCase : Union[int, float] , __lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **__lowerCamelCase : Optional[int] , ): return rescale(__lowerCamelCase , scale=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) def _A ( self : Optional[int] , __lowerCamelCase : np.ndarray , __lowerCamelCase : Union[float, List[float]] , __lowerCamelCase : Union[float, List[float]] , __lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **__lowerCamelCase : str , ): return normalize(__lowerCamelCase , mean=__lowerCamelCase , std=__lowerCamelCase , data_format=__lowerCamelCase , **__lowerCamelCase ) def _A ( self : List[Any] , __lowerCamelCase : ImageInput , __lowerCamelCase : bool = None , __lowerCamelCase : Dict[str, int] = None , __lowerCamelCase : PILImageResampling = None , __lowerCamelCase : bool = None , __lowerCamelCase : int = None , __lowerCamelCase : bool = None , __lowerCamelCase : float = None , __lowerCamelCase : bool = None , __lowerCamelCase : Optional[Union[float, List[float]]] = None , __lowerCamelCase : Optional[Union[float, List[float]]] = None , __lowerCamelCase : bool = None , __lowerCamelCase : Optional[Union[str, TensorType]] = None , __lowerCamelCase : Optional[ChannelDimension] = ChannelDimension.FIRST , **__lowerCamelCase : List[str] , ): UpperCamelCase :Dict = do_resize if do_resize is not None else self.do_resize UpperCamelCase :List[str] = size if size is not None else self.size UpperCamelCase :str = get_size_dict(__lowerCamelCase , param_name="""size""" , default_to_square=__lowerCamelCase ) UpperCamelCase :Optional[Any] = resample if resample is not None else self.resample UpperCamelCase :List[str] = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase :List[str] = crop_size if crop_size is not None else self.crop_size UpperCamelCase :str = get_size_dict(__lowerCamelCase , param_name="""crop_size""" , default_to_square=__lowerCamelCase ) UpperCamelCase :Tuple = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase :Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase :int = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase :List[str] = image_mean if image_mean is not None else self.image_mean UpperCamelCase :Optional[Any] = image_std if image_std is not None else self.image_std UpperCamelCase :List[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase :Dict = make_list_of_images(__lowerCamelCase ) if not valid_images(__lowerCamelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase :Optional[int] = [convert_to_rgb(__lowerCamelCase ) for image in images] # All transformations expect numpy arrays. UpperCamelCase :Dict = [to_numpy_array(__lowerCamelCase ) for image in images] if do_resize: UpperCamelCase :Tuple = [self.resize(image=__lowerCamelCase , size=__lowerCamelCase , resample=__lowerCamelCase ) for image in images] if do_center_crop: UpperCamelCase :str = [self.center_crop(image=__lowerCamelCase , size=__lowerCamelCase ) for image in images] if do_rescale: UpperCamelCase :List[str] = [self.rescale(image=__lowerCamelCase , scale=__lowerCamelCase ) for image in images] if do_normalize: UpperCamelCase :str = [self.normalize(image=__lowerCamelCase , mean=__lowerCamelCase , std=__lowerCamelCase ) for image in images] UpperCamelCase :Optional[Any] = [to_channel_dimension_format(__lowerCamelCase , __lowerCamelCase ) for image in images] UpperCamelCase :str = {"""pixel_values""": images} return BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase )
38
"""simple docstring""" def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =set() # Replace all the whitespace in our sentence a =input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowercase ) == 26 def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" a =[False] * 26 for char in input_str: if char.islower(): a =True elif char.isupper(): a =True return all(lowercase ) def _A ( lowercase = "The quick brown fox jumps over the lazy dog" , ): """simple docstring""" return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _A ( ): """simple docstring""" from timeit import timeit a ='''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowercase ) ) print(timeit('''is_pangram_faster()''' , setup=lowercase ) ) print(timeit('''is_pangram_fastest()''' , setup=lowercase ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
0
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMInverseScheduler, DDIMScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, StableDiffusionDiffEditPipeline, UNetaDConditionModel, ) from diffusers.utils import load_image, slow from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __lowerCamelCase ( snake_case__ , snake_case__ , unittest.TestCase): """simple docstring""" UpperCamelCase__ = StableDiffusionDiffEditPipeline UpperCamelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"} UpperCamelCase__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"} UpperCamelCase__ = frozenset( []) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess UpperCamelCase__ = frozenset([]) def UpperCamelCase ( self ): """simple docstring""" torch.manual_seed(0 ) _UpperCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=UpperCAmelCase , ) _UpperCAmelCase = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=UpperCAmelCase , set_alpha_to_one=UpperCAmelCase , ) _UpperCAmelCase = DDIMInverseScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , clip_sample=UpperCAmelCase , set_alpha_to_zero=UpperCAmelCase , ) torch.manual_seed(0 ) _UpperCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) _UpperCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) _UpperCAmelCase = CLIPTextModel(UpperCAmelCase ) _UpperCAmelCase = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) _UpperCAmelCase = { 'unet': unet, 'scheduler': scheduler, 'inverse_scheduler': inverse_scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase=0 ): """simple docstring""" _UpperCAmelCase = floats_tensor((1, 16, 16) , rng=random.Random(UpperCAmelCase ) ).to(UpperCAmelCase ) _UpperCAmelCase = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(UpperCAmelCase ) ).to(UpperCAmelCase ) if str(UpperCAmelCase ).startswith('mps' ): _UpperCAmelCase = torch.manual_seed(UpperCAmelCase ) else: _UpperCAmelCase = torch.Generator(device=UpperCAmelCase ).manual_seed(UpperCAmelCase ) _UpperCAmelCase = { 'prompt': 'a dog and a newt', 'mask_image': mask, 'image_latents': latents, 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase=0 ): """simple docstring""" _UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase ) ).to(UpperCAmelCase ) _UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] _UpperCAmelCase = Image.fromarray(np.uinta(UpperCAmelCase ) ).convert('RGB' ) if str(UpperCAmelCase ).startswith('mps' ): _UpperCAmelCase = torch.manual_seed(UpperCAmelCase ) else: _UpperCAmelCase = torch.Generator(device=UpperCAmelCase ).manual_seed(UpperCAmelCase ) _UpperCAmelCase = { 'image': image, 'source_prompt': 'a cat and a frog', 'target_prompt': 'a dog and a newt', 'generator': generator, 'num_inference_steps': 2, 'num_maps_per_mask': 2, 'mask_encode_strength': 1.0, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase=0 ): """simple docstring""" _UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase ) ).to(UpperCAmelCase ) _UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] _UpperCAmelCase = Image.fromarray(np.uinta(UpperCAmelCase ) ).convert('RGB' ) if str(UpperCAmelCase ).startswith('mps' ): _UpperCAmelCase = torch.manual_seed(UpperCAmelCase ) else: _UpperCAmelCase = torch.Generator(device=UpperCAmelCase ).manual_seed(UpperCAmelCase ) _UpperCAmelCase = { 'image': image, 'prompt': 'a cat and a frog', 'generator': generator, 'num_inference_steps': 2, 'inpaint_strength': 1.0, 'guidance_scale': 6.0, 'decode_latents': True, 'output_type': 'numpy', } return inputs def UpperCamelCase ( self ): """simple docstring""" if not hasattr(self.pipeline_class , '_optional_components' ): return _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = self.pipeline_class(**UpperCAmelCase ) pipe.to(UpperCAmelCase ) pipe.set_progress_bar_config(disable=UpperCAmelCase ) # set all optional components to None and update pipeline config accordingly for optional_component in pipe._optional_components: setattr(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} ) _UpperCAmelCase = self.get_dummy_inputs(UpperCAmelCase ) _UpperCAmelCase = pipe(**UpperCAmelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(UpperCAmelCase ) _UpperCAmelCase = self.pipeline_class.from_pretrained(UpperCAmelCase ) pipe_loaded.to(UpperCAmelCase ) pipe_loaded.set_progress_bar_config(disable=UpperCAmelCase ) for optional_component in pipe._optional_components: self.assertTrue( getattr(UpperCAmelCase , UpperCAmelCase ) is None , F"""`{optional_component}` did not stay set to None after loading.""" , ) _UpperCAmelCase = self.get_dummy_inputs(UpperCAmelCase ) _UpperCAmelCase = pipe_loaded(**UpperCAmelCase )[0] _UpperCAmelCase = np.abs(output - output_loaded ).max() self.assertLess(UpperCAmelCase , 1e-4 ) def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = 'cpu' _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = self.pipeline_class(**UpperCAmelCase ) pipe.to(UpperCAmelCase ) pipe.set_progress_bar_config(disable=UpperCAmelCase ) _UpperCAmelCase = self.get_dummy_mask_inputs(UpperCAmelCase ) _UpperCAmelCase = pipe.generate_mask(**UpperCAmelCase ) _UpperCAmelCase = mask[0, -3:, -3:] self.assertEqual(mask.shape , (1, 16, 16) ) _UpperCAmelCase = np.array([0] * 9 ) _UpperCAmelCase = np.abs(mask_slice.flatten() - expected_slice ).max() self.assertLessEqual(UpperCAmelCase , 1e-3 ) self.assertEqual(mask[0, -3, -4] , 0 ) def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = 'cpu' _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = self.pipeline_class(**UpperCAmelCase ) pipe.to(UpperCAmelCase ) pipe.set_progress_bar_config(disable=UpperCAmelCase ) _UpperCAmelCase = self.get_dummy_inversion_inputs(UpperCAmelCase ) _UpperCAmelCase = pipe.invert(**UpperCAmelCase ).images _UpperCAmelCase = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) _UpperCAmelCase = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) _UpperCAmelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(UpperCAmelCase , 1e-3 ) def UpperCamelCase ( self ): """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=5e-3 ) def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = 'cpu' _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = {'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'} _UpperCAmelCase = DPMSolverMultistepScheduler(**UpperCAmelCase ) _UpperCAmelCase = DPMSolverMultistepInverseScheduler(**UpperCAmelCase ) _UpperCAmelCase = self.pipeline_class(**UpperCAmelCase ) pipe.to(UpperCAmelCase ) pipe.set_progress_bar_config(disable=UpperCAmelCase ) _UpperCAmelCase = self.get_dummy_inversion_inputs(UpperCAmelCase ) _UpperCAmelCase = pipe.invert(**UpperCAmelCase ).images _UpperCAmelCase = image[0, -1, -3:, -3:] self.assertEqual(image.shape , (2, 32, 32, 3) ) _UpperCAmelCase = np.array( [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99] , ) _UpperCAmelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(UpperCAmelCase , 1e-3 ) @require_torch_gpu @slow class __lowerCamelCase ( unittest.TestCase): """simple docstring""" def UpperCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @classmethod def UpperCamelCase ( cls ): """simple docstring""" _UpperCAmelCase = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png' ) _UpperCAmelCase = raw_image.convert('RGB' ).resize((768, 768) ) _UpperCAmelCase = raw_image def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = torch.manual_seed(0 ) _UpperCAmelCase = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=UpperCAmelCase , torch_dtype=torch.floataa ) _UpperCAmelCase = DDIMScheduler.from_config(pipe.scheduler.config ) _UpperCAmelCase = DDIMInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCAmelCase ) _UpperCAmelCase = 'a bowl of fruit' _UpperCAmelCase = 'a bowl of pears' _UpperCAmelCase = pipe.generate_mask( image=self.raw_image , source_prompt=UpperCAmelCase , target_prompt=UpperCAmelCase , generator=UpperCAmelCase , ) _UpperCAmelCase = pipe.invert( prompt=UpperCAmelCase , image=self.raw_image , inpaint_strength=0.7 , generator=UpperCAmelCase ).latents _UpperCAmelCase = pipe( prompt=UpperCAmelCase , mask_image=UpperCAmelCase , image_latents=UpperCAmelCase , generator=UpperCAmelCase , negative_prompt=UpperCAmelCase , inpaint_strength=0.7 , output_type='numpy' , ).images[0] _UpperCAmelCase = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png' ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5e-1 def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = torch.manual_seed(0 ) _UpperCAmelCase = StableDiffusionDiffEditPipeline.from_pretrained( 'stabilityai/stable-diffusion-2-1' , safety_checker=UpperCAmelCase , torch_dtype=torch.floataa ) _UpperCAmelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) _UpperCAmelCase = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCAmelCase ) _UpperCAmelCase = 'a bowl of fruit' _UpperCAmelCase = 'a bowl of pears' _UpperCAmelCase = pipe.generate_mask( image=self.raw_image , source_prompt=UpperCAmelCase , target_prompt=UpperCAmelCase , generator=UpperCAmelCase , ) _UpperCAmelCase = pipe.invert( prompt=UpperCAmelCase , image=self.raw_image , inpaint_strength=0.7 , generator=UpperCAmelCase , num_inference_steps=25 , ).latents _UpperCAmelCase = pipe( prompt=UpperCAmelCase , mask_image=UpperCAmelCase , image_latents=UpperCAmelCase , generator=UpperCAmelCase , negative_prompt=UpperCAmelCase , inpaint_strength=0.7 , num_inference_steps=25 , output_type='numpy' , ).images[0] _UpperCAmelCase = ( np.array( load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/diffedit/pears.png' ).resize((768, 768) ) ) / 255 ) assert np.abs((expected_image - image).max() ) < 5e-1
39
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ : Optional[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys lowerCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
0